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 
getType(APValue::LValueBase B)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.
getAsField(APValue::LValuePathEntry E)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.
getAsBaseClass(APValue::LValuePathEntry E)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.
isVirtualBaseClass(APValue::LValuePathEntry E)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.
getStorageType(const ASTContext & Ctx,const Expr * E)103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isRValue())
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.
getAllocSizeAttr(const CallExpr * CE)110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     const FunctionDecl *Callee = CE->getDirectCallee();
112     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
113   }
114 
115   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
116   /// This will look through a single cast.
117   ///
118   /// Returns null if we couldn't unwrap a function with alloc_size.
tryUnwrapAllocSizeCall(const Expr * E)119   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
120     if (!E->getType()->isPointerType())
121       return nullptr;
122 
123     E = E->IgnoreParens();
124     // If we're doing a variable assignment from e.g. malloc(N), there will
125     // probably be a cast of some kind. In exotic cases, we might also see a
126     // top-level ExprWithCleanups. Ignore them either way.
127     if (const auto *FE = dyn_cast<FullExpr>(E))
128       E = FE->getSubExpr()->IgnoreParens();
129 
130     if (const auto *Cast = dyn_cast<CastExpr>(E))
131       E = Cast->getSubExpr()->IgnoreParens();
132 
133     if (const auto *CE = dyn_cast<CallExpr>(E))
134       return getAllocSizeAttr(CE) ? CE : nullptr;
135     return nullptr;
136   }
137 
138   /// Determines whether or not the given Base contains a call to a function
139   /// with the alloc_size attribute.
isBaseAnAllocSizeCall(APValue::LValueBase Base)140   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
141     const auto *E = Base.dyn_cast<const Expr *>();
142     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
143   }
144 
145   /// Determines whether the given kind of constant expression is only ever
146   /// used for name mangling. If so, it's permitted to reference things that we
147   /// can't generate code for (in particular, dllimported functions).
isForManglingOnly(ConstantExprKind Kind)148   static bool isForManglingOnly(ConstantExprKind Kind) {
149     switch (Kind) {
150     case ConstantExprKind::Normal:
151     case ConstantExprKind::ClassTemplateArgument:
152     case ConstantExprKind::ImmediateInvocation:
153       // Note that non-type template arguments of class type are emitted as
154       // template parameter objects.
155       return false;
156 
157     case ConstantExprKind::NonClassTemplateArgument:
158       return true;
159     }
160     llvm_unreachable("unknown ConstantExprKind");
161   }
162 
isTemplateArgument(ConstantExprKind Kind)163   static bool isTemplateArgument(ConstantExprKind Kind) {
164     switch (Kind) {
165     case ConstantExprKind::Normal:
166     case ConstantExprKind::ImmediateInvocation:
167       return false;
168 
169     case ConstantExprKind::ClassTemplateArgument:
170     case ConstantExprKind::NonClassTemplateArgument:
171       return true;
172     }
173     llvm_unreachable("unknown ConstantExprKind");
174   }
175 
176   /// The bound to claim that an array of unknown bound has.
177   /// The value in MostDerivedArraySize is undefined in this case. So, set it
178   /// to an arbitrary value that's likely to loudly break things if it's used.
179   static const uint64_t AssumedSizeForUnsizedArray =
180       std::numeric_limits<uint64_t>::max() / 2;
181 
182   /// Determines if an LValue with the given LValueBase will have an unsized
183   /// array in its designator.
184   /// Find the path length and type of the most-derived subobject in the given
185   /// path, and find the size of the containing array, if any.
186   static unsigned
findMostDerivedSubobject(ASTContext & Ctx,APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path,uint64_t & ArraySize,QualType & Type,bool & IsArray,bool & FirstEntryIsUnsizedArray)187   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
188                            ArrayRef<APValue::LValuePathEntry> Path,
189                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
190                            bool &FirstEntryIsUnsizedArray) {
191     // This only accepts LValueBases from APValues, and APValues don't support
192     // arrays that lack size info.
193     assert(!isBaseAnAllocSizeCall(Base) &&
194            "Unsized arrays shouldn't appear here");
195     unsigned MostDerivedLength = 0;
196     Type = getType(Base);
197 
198     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
199       if (Type->isArrayType()) {
200         const ArrayType *AT = Ctx.getAsArrayType(Type);
201         Type = AT->getElementType();
202         MostDerivedLength = I + 1;
203         IsArray = true;
204 
205         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
206           ArraySize = CAT->getSize().getZExtValue();
207         } else {
208           assert(I == 0 && "unexpected unsized array designator");
209           FirstEntryIsUnsizedArray = true;
210           ArraySize = AssumedSizeForUnsizedArray;
211         }
212       } else if (Type->isAnyComplexType()) {
213         const ComplexType *CT = Type->castAs<ComplexType>();
214         Type = CT->getElementType();
215         ArraySize = 2;
216         MostDerivedLength = I + 1;
217         IsArray = true;
218       } else if (const FieldDecl *FD = getAsField(Path[I])) {
219         Type = FD->getType();
220         ArraySize = 0;
221         MostDerivedLength = I + 1;
222         IsArray = false;
223       } else {
224         // Path[I] describes a base class.
225         ArraySize = 0;
226         IsArray = false;
227       }
228     }
229     return MostDerivedLength;
230   }
231 
232   /// A path from a glvalue to a subobject of that glvalue.
233   struct SubobjectDesignator {
234     /// True if the subobject was named in a manner not supported by C++11. Such
235     /// lvalues can still be folded, but they are not core constant expressions
236     /// and we cannot perform lvalue-to-rvalue conversions on them.
237     unsigned Invalid : 1;
238 
239     /// Is this a pointer one past the end of an object?
240     unsigned IsOnePastTheEnd : 1;
241 
242     /// Indicator of whether the first entry is an unsized array.
243     unsigned FirstEntryIsAnUnsizedArray : 1;
244 
245     /// Indicator of whether the most-derived object is an array element.
246     unsigned MostDerivedIsArrayElement : 1;
247 
248     /// The length of the path to the most-derived object of which this is a
249     /// subobject.
250     unsigned MostDerivedPathLength : 28;
251 
252     /// The size of the array of which the most-derived object is an element.
253     /// This will always be 0 if the most-derived object is not an array
254     /// element. 0 is not an indicator of whether or not the most-derived object
255     /// is an array, however, because 0-length arrays are allowed.
256     ///
257     /// If the current array is an unsized array, the value of this is
258     /// undefined.
259     uint64_t MostDerivedArraySize;
260 
261     /// The type of the most derived object referred to by this address.
262     QualType MostDerivedType;
263 
264     typedef APValue::LValuePathEntry PathEntry;
265 
266     /// The entries on the path from the glvalue to the designated subobject.
267     SmallVector<PathEntry, 8> Entries;
268 
SubobjectDesignator__anone93968c60111::SubobjectDesignator269     SubobjectDesignator() : Invalid(true) {}
270 
SubobjectDesignator__anone93968c60111::SubobjectDesignator271     explicit SubobjectDesignator(QualType T)
272         : Invalid(false), IsOnePastTheEnd(false),
273           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
274           MostDerivedPathLength(0), MostDerivedArraySize(0),
275           MostDerivedType(T) {}
276 
SubobjectDesignator__anone93968c60111::SubobjectDesignator277     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
278         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
279           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
280           MostDerivedPathLength(0), MostDerivedArraySize(0) {
281       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
282       if (!Invalid) {
283         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
284         ArrayRef<PathEntry> VEntries = V.getLValuePath();
285         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
286         if (V.getLValueBase()) {
287           bool IsArray = false;
288           bool FirstIsUnsizedArray = false;
289           MostDerivedPathLength = findMostDerivedSubobject(
290               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
291               MostDerivedType, IsArray, FirstIsUnsizedArray);
292           MostDerivedIsArrayElement = IsArray;
293           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
294         }
295       }
296     }
297 
truncate__anone93968c60111::SubobjectDesignator298     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
299                   unsigned NewLength) {
300       if (Invalid)
301         return;
302 
303       assert(Base && "cannot truncate path for null pointer");
304       assert(NewLength <= Entries.size() && "not a truncation");
305 
306       if (NewLength == Entries.size())
307         return;
308       Entries.resize(NewLength);
309 
310       bool IsArray = false;
311       bool FirstIsUnsizedArray = false;
312       MostDerivedPathLength = findMostDerivedSubobject(
313           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
314           FirstIsUnsizedArray);
315       MostDerivedIsArrayElement = IsArray;
316       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
317     }
318 
setInvalid__anone93968c60111::SubobjectDesignator319     void setInvalid() {
320       Invalid = true;
321       Entries.clear();
322     }
323 
324     /// Determine whether the most derived subobject is an array without a
325     /// known bound.
isMostDerivedAnUnsizedArray__anone93968c60111::SubobjectDesignator326     bool isMostDerivedAnUnsizedArray() const {
327       assert(!Invalid && "Calling this makes no sense on invalid designators");
328       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
329     }
330 
331     /// Determine what the most derived array's size is. Results in an assertion
332     /// failure if the most derived array lacks a size.
getMostDerivedArraySize__anone93968c60111::SubobjectDesignator333     uint64_t getMostDerivedArraySize() const {
334       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
335       return MostDerivedArraySize;
336     }
337 
338     /// Determine whether this is a one-past-the-end pointer.
isOnePastTheEnd__anone93968c60111::SubobjectDesignator339     bool isOnePastTheEnd() const {
340       assert(!Invalid);
341       if (IsOnePastTheEnd)
342         return true;
343       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
344           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
345               MostDerivedArraySize)
346         return true;
347       return false;
348     }
349 
350     /// Get the range of valid index adjustments in the form
351     ///   {maximum value that can be subtracted from this pointer,
352     ///    maximum value that can be added to this pointer}
validIndexAdjustments__anone93968c60111::SubobjectDesignator353     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
354       if (Invalid || isMostDerivedAnUnsizedArray())
355         return {0, 0};
356 
357       // [expr.add]p4: For the purposes of these operators, a pointer to a
358       // nonarray object behaves the same as a pointer to the first element of
359       // an array of length one with the type of the object as its element type.
360       bool IsArray = MostDerivedPathLength == Entries.size() &&
361                      MostDerivedIsArrayElement;
362       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
363                                     : (uint64_t)IsOnePastTheEnd;
364       uint64_t ArraySize =
365           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
366       return {ArrayIndex, ArraySize - ArrayIndex};
367     }
368 
369     /// Check that this refers to a valid subobject.
isValidSubobject__anone93968c60111::SubobjectDesignator370     bool isValidSubobject() const {
371       if (Invalid)
372         return false;
373       return !isOnePastTheEnd();
374     }
375     /// Check that this refers to a valid subobject, and if not, produce a
376     /// relevant diagnostic and set the designator as invalid.
377     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
378 
379     /// Get the type of the designated object.
getType__anone93968c60111::SubobjectDesignator380     QualType getType(ASTContext &Ctx) const {
381       assert(!Invalid && "invalid designator has no subobject type");
382       return MostDerivedPathLength == Entries.size()
383                  ? MostDerivedType
384                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
385     }
386 
387     /// Update this designator to refer to the first element within this array.
addArrayUnchecked__anone93968c60111::SubobjectDesignator388     void addArrayUnchecked(const ConstantArrayType *CAT) {
389       Entries.push_back(PathEntry::ArrayIndex(0));
390 
391       // This is a most-derived object.
392       MostDerivedType = CAT->getElementType();
393       MostDerivedIsArrayElement = true;
394       MostDerivedArraySize = CAT->getSize().getZExtValue();
395       MostDerivedPathLength = Entries.size();
396     }
397     /// Update this designator to refer to the first element within the array of
398     /// elements of type T. This is an array of unknown size.
addUnsizedArrayUnchecked__anone93968c60111::SubobjectDesignator399     void addUnsizedArrayUnchecked(QualType ElemTy) {
400       Entries.push_back(PathEntry::ArrayIndex(0));
401 
402       MostDerivedType = ElemTy;
403       MostDerivedIsArrayElement = true;
404       // The value in MostDerivedArraySize is undefined in this case. So, set it
405       // to an arbitrary value that's likely to loudly break things if it's
406       // used.
407       MostDerivedArraySize = AssumedSizeForUnsizedArray;
408       MostDerivedPathLength = Entries.size();
409     }
410     /// Update this designator to refer to the given base or member of this
411     /// object.
addDeclUnchecked__anone93968c60111::SubobjectDesignator412     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
413       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
414 
415       // If this isn't a base class, it's a new most-derived object.
416       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
417         MostDerivedType = FD->getType();
418         MostDerivedIsArrayElement = false;
419         MostDerivedArraySize = 0;
420         MostDerivedPathLength = Entries.size();
421       }
422     }
423     /// Update this designator to refer to the given complex component.
addComplexUnchecked__anone93968c60111::SubobjectDesignator424     void addComplexUnchecked(QualType EltTy, bool Imag) {
425       Entries.push_back(PathEntry::ArrayIndex(Imag));
426 
427       // This is technically a most-derived object, though in practice this
428       // is unlikely to matter.
429       MostDerivedType = EltTy;
430       MostDerivedIsArrayElement = true;
431       MostDerivedArraySize = 2;
432       MostDerivedPathLength = Entries.size();
433     }
434     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
435     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
436                                    const APSInt &N);
437     /// Add N to the address of this subobject.
adjustIndex__anone93968c60111::SubobjectDesignator438     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
439       if (Invalid || !N) return;
440       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
441       if (isMostDerivedAnUnsizedArray()) {
442         diagnoseUnsizedArrayPointerArithmetic(Info, E);
443         // Can't verify -- trust that the user is doing the right thing (or if
444         // not, trust that the caller will catch the bad behavior).
445         // FIXME: Should we reject if this overflows, at least?
446         Entries.back() = PathEntry::ArrayIndex(
447             Entries.back().getAsArrayIndex() + TruncatedN);
448         return;
449       }
450 
451       // [expr.add]p4: For the purposes of these operators, a pointer to a
452       // nonarray object behaves the same as a pointer to the first element of
453       // an array of length one with the type of the object as its element type.
454       bool IsArray = MostDerivedPathLength == Entries.size() &&
455                      MostDerivedIsArrayElement;
456       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
457                                     : (uint64_t)IsOnePastTheEnd;
458       uint64_t ArraySize =
459           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
460 
461       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
462         // Calculate the actual index in a wide enough type, so we can include
463         // it in the note.
464         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
465         (llvm::APInt&)N += ArrayIndex;
466         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
467         diagnosePointerArithmetic(Info, E, N);
468         setInvalid();
469         return;
470       }
471 
472       ArrayIndex += TruncatedN;
473       assert(ArrayIndex <= ArraySize &&
474              "bounds check succeeded for out-of-bounds index");
475 
476       if (IsArray)
477         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
478       else
479         IsOnePastTheEnd = (ArrayIndex != 0);
480     }
481   };
482 
483   /// A scope at the end of which an object can need to be destroyed.
484   enum class ScopeKind {
485     Block,
486     FullExpression,
487     Call
488   };
489 
490   /// A reference to a particular call and its arguments.
491   struct CallRef {
CallRef__anone93968c60111::CallRef492     CallRef() : OrigCallee(), CallIndex(0), Version() {}
CallRef__anone93968c60111::CallRef493     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
494         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
495 
operator bool__anone93968c60111::CallRef496     explicit operator bool() const { return OrigCallee; }
497 
498     /// Get the parameter that the caller initialized, corresponding to the
499     /// given parameter in the callee.
getOrigParam__anone93968c60111::CallRef500     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
501       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
502                         : PVD;
503     }
504 
505     /// The callee at the point where the arguments were evaluated. This might
506     /// be different from the actual callee (a different redeclaration, or a
507     /// virtual override), but this function's parameters are the ones that
508     /// appear in the parameter map.
509     const FunctionDecl *OrigCallee;
510     /// The call index of the frame that holds the argument values.
511     unsigned CallIndex;
512     /// The version of the parameters corresponding to this call.
513     unsigned Version;
514   };
515 
516   /// A stack frame in the constexpr call stack.
517   class CallStackFrame : public interp::Frame {
518   public:
519     EvalInfo &Info;
520 
521     /// Parent - The caller of this stack frame.
522     CallStackFrame *Caller;
523 
524     /// Callee - The function which was called.
525     const FunctionDecl *Callee;
526 
527     /// This - The binding for the this pointer in this call, if any.
528     const LValue *This;
529 
530     /// Information on how to find the arguments to this call. Our arguments
531     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
532     /// key and this value as the version.
533     CallRef Arguments;
534 
535     /// Source location information about the default argument or default
536     /// initializer expression we're evaluating, if any.
537     CurrentSourceLocExprScope CurSourceLocExprScope;
538 
539     // Note that we intentionally use std::map here so that references to
540     // values are stable.
541     typedef std::pair<const void *, unsigned> MapKeyTy;
542     typedef std::map<MapKeyTy, APValue> MapTy;
543     /// Temporaries - Temporary lvalues materialized within this stack frame.
544     MapTy Temporaries;
545 
546     /// CallLoc - The location of the call expression for this call.
547     SourceLocation CallLoc;
548 
549     /// Index - The call index of this call.
550     unsigned Index;
551 
552     /// The stack of integers for tracking version numbers for temporaries.
553     SmallVector<unsigned, 2> TempVersionStack = {1};
554     unsigned CurTempVersion = TempVersionStack.back();
555 
getTempVersion() const556     unsigned getTempVersion() const { return TempVersionStack.back(); }
557 
pushTempVersion()558     void pushTempVersion() {
559       TempVersionStack.push_back(++CurTempVersion);
560     }
561 
popTempVersion()562     void popTempVersion() {
563       TempVersionStack.pop_back();
564     }
565 
createCall(const FunctionDecl * Callee)566     CallRef createCall(const FunctionDecl *Callee) {
567       return {Callee, Index, ++CurTempVersion};
568     }
569 
570     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
571     // on the overall stack usage of deeply-recursing constexpr evaluations.
572     // (We should cache this map rather than recomputing it repeatedly.)
573     // But let's try this and see how it goes; we can look into caching the map
574     // as a later change.
575 
576     /// LambdaCaptureFields - Mapping from captured variables/this to
577     /// corresponding data members in the closure class.
578     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
579     FieldDecl *LambdaThisCaptureField;
580 
581     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
582                    const FunctionDecl *Callee, const LValue *This,
583                    CallRef Arguments);
584     ~CallStackFrame();
585 
586     // Return the temporary for Key whose version number is Version.
getTemporary(const void * Key,unsigned Version)587     APValue *getTemporary(const void *Key, unsigned Version) {
588       MapKeyTy KV(Key, Version);
589       auto LB = Temporaries.lower_bound(KV);
590       if (LB != Temporaries.end() && LB->first == KV)
591         return &LB->second;
592       // Pair (Key,Version) wasn't found in the map. Check that no elements
593       // in the map have 'Key' as their key.
594       assert((LB == Temporaries.end() || LB->first.first != Key) &&
595              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
596              "Element with key 'Key' found in map");
597       return nullptr;
598     }
599 
600     // Return the current temporary for Key in the map.
getCurrentTemporary(const void * Key)601     APValue *getCurrentTemporary(const void *Key) {
602       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
603       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
604         return &std::prev(UB)->second;
605       return nullptr;
606     }
607 
608     // Return the version number of the current temporary for Key.
getCurrentTemporaryVersion(const void * Key) const609     unsigned getCurrentTemporaryVersion(const void *Key) const {
610       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
611       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
612         return std::prev(UB)->first.second;
613       return 0;
614     }
615 
616     /// Allocate storage for an object of type T in this stack frame.
617     /// Populates LV with a handle to the created object. Key identifies
618     /// the temporary within the stack frame, and must not be reused without
619     /// bumping the temporary version number.
620     template<typename KeyT>
621     APValue &createTemporary(const KeyT *Key, QualType T,
622                              ScopeKind Scope, LValue &LV);
623 
624     /// Allocate storage for a parameter of a function call made in this frame.
625     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
626 
627     void describe(llvm::raw_ostream &OS) override;
628 
getCaller() const629     Frame *getCaller() const override { return Caller; }
getCallLocation() const630     SourceLocation getCallLocation() const override { return CallLoc; }
getCallee() const631     const FunctionDecl *getCallee() const override { return Callee; }
632 
isStdFunction() const633     bool isStdFunction() const {
634       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
635         if (DC->isStdNamespace())
636           return true;
637       return false;
638     }
639 
640   private:
641     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
642                          ScopeKind Scope);
643   };
644 
645   /// Temporarily override 'this'.
646   class ThisOverrideRAII {
647   public:
ThisOverrideRAII(CallStackFrame & Frame,const LValue * NewThis,bool Enable)648     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
649         : Frame(Frame), OldThis(Frame.This) {
650       if (Enable)
651         Frame.This = NewThis;
652     }
~ThisOverrideRAII()653     ~ThisOverrideRAII() {
654       Frame.This = OldThis;
655     }
656   private:
657     CallStackFrame &Frame;
658     const LValue *OldThis;
659   };
660 }
661 
662 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
663                               const LValue &This, QualType ThisType);
664 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
665                               APValue::LValueBase LVBase, APValue &Value,
666                               QualType T);
667 
668 namespace {
669   /// A cleanup, and a flag indicating whether it is lifetime-extended.
670   class Cleanup {
671     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
672     APValue::LValueBase Base;
673     QualType T;
674 
675   public:
Cleanup(APValue * Val,APValue::LValueBase Base,QualType T,ScopeKind Scope)676     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
677             ScopeKind Scope)
678         : Value(Val, Scope), Base(Base), T(T) {}
679 
680     /// Determine whether this cleanup should be performed at the end of the
681     /// given kind of scope.
isDestroyedAtEndOf(ScopeKind K) const682     bool isDestroyedAtEndOf(ScopeKind K) const {
683       return (int)Value.getInt() >= (int)K;
684     }
endLifetime(EvalInfo & Info,bool RunDestructors)685     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
686       if (RunDestructors) {
687         SourceLocation Loc;
688         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
689           Loc = VD->getLocation();
690         else if (const Expr *E = Base.dyn_cast<const Expr*>())
691           Loc = E->getExprLoc();
692         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
693       }
694       *Value.getPointer() = APValue();
695       return true;
696     }
697 
hasSideEffect()698     bool hasSideEffect() {
699       return T.isDestructedType();
700     }
701   };
702 
703   /// A reference to an object whose construction we are currently evaluating.
704   struct ObjectUnderConstruction {
705     APValue::LValueBase Base;
706     ArrayRef<APValue::LValuePathEntry> Path;
operator ==(const ObjectUnderConstruction & LHS,const ObjectUnderConstruction & RHS)707     friend bool operator==(const ObjectUnderConstruction &LHS,
708                            const ObjectUnderConstruction &RHS) {
709       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
710     }
hash_value(const ObjectUnderConstruction & Obj)711     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
712       return llvm::hash_combine(Obj.Base, Obj.Path);
713     }
714   };
715   enum class ConstructionPhase {
716     None,
717     Bases,
718     AfterBases,
719     AfterFields,
720     Destroying,
721     DestroyingBases
722   };
723 }
724 
725 namespace llvm {
726 template<> struct DenseMapInfo<ObjectUnderConstruction> {
727   using Base = DenseMapInfo<APValue::LValueBase>;
getEmptyKeyllvm::DenseMapInfo728   static ObjectUnderConstruction getEmptyKey() {
729     return {Base::getEmptyKey(), {}}; }
getTombstoneKeyllvm::DenseMapInfo730   static ObjectUnderConstruction getTombstoneKey() {
731     return {Base::getTombstoneKey(), {}};
732   }
getHashValuellvm::DenseMapInfo733   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
734     return hash_value(Object);
735   }
isEqualllvm::DenseMapInfo736   static bool isEqual(const ObjectUnderConstruction &LHS,
737                       const ObjectUnderConstruction &RHS) {
738     return LHS == RHS;
739   }
740 };
741 }
742 
743 namespace {
744   /// A dynamically-allocated heap object.
745   struct DynAlloc {
746     /// The value of this heap-allocated object.
747     APValue Value;
748     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
749     /// or a CallExpr (the latter is for direct calls to operator new inside
750     /// std::allocator<T>::allocate).
751     const Expr *AllocExpr = nullptr;
752 
753     enum Kind {
754       New,
755       ArrayNew,
756       StdAllocator
757     };
758 
759     /// Get the kind of the allocation. This must match between allocation
760     /// and deallocation.
getKind__anone93968c60311::DynAlloc761     Kind getKind() const {
762       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
763         return NE->isArray() ? ArrayNew : New;
764       assert(isa<CallExpr>(AllocExpr));
765       return StdAllocator;
766     }
767   };
768 
769   struct DynAllocOrder {
operator ()__anone93968c60311::DynAllocOrder770     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
771       return L.getIndex() < R.getIndex();
772     }
773   };
774 
775   /// EvalInfo - This is a private struct used by the evaluator to capture
776   /// information about a subexpression as it is folded.  It retains information
777   /// about the AST context, but also maintains information about the folded
778   /// expression.
779   ///
780   /// If an expression could be evaluated, it is still possible it is not a C
781   /// "integer constant expression" or constant expression.  If not, this struct
782   /// captures information about how and why not.
783   ///
784   /// One bit of information passed *into* the request for constant folding
785   /// indicates whether the subexpression is "evaluated" or not according to C
786   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
787   /// evaluate the expression regardless of what the RHS is, but C only allows
788   /// certain things in certain situations.
789   class EvalInfo : public interp::State {
790   public:
791     ASTContext &Ctx;
792 
793     /// EvalStatus - Contains information about the evaluation.
794     Expr::EvalStatus &EvalStatus;
795 
796     /// CurrentCall - The top of the constexpr call stack.
797     CallStackFrame *CurrentCall;
798 
799     /// CallStackDepth - The number of calls in the call stack right now.
800     unsigned CallStackDepth;
801 
802     /// NextCallIndex - The next call index to assign.
803     unsigned NextCallIndex;
804 
805     /// StepsLeft - The remaining number of evaluation steps we're permitted
806     /// to perform. This is essentially a limit for the number of statements
807     /// we will evaluate.
808     unsigned StepsLeft;
809 
810     /// Enable the experimental new constant interpreter. If an expression is
811     /// not supported by the interpreter, an error is triggered.
812     bool EnableNewConstInterp;
813 
814     /// BottomFrame - The frame in which evaluation started. This must be
815     /// initialized after CurrentCall and CallStackDepth.
816     CallStackFrame BottomFrame;
817 
818     /// A stack of values whose lifetimes end at the end of some surrounding
819     /// evaluation frame.
820     llvm::SmallVector<Cleanup, 16> CleanupStack;
821 
822     /// EvaluatingDecl - This is the declaration whose initializer is being
823     /// evaluated, if any.
824     APValue::LValueBase EvaluatingDecl;
825 
826     enum class EvaluatingDeclKind {
827       None,
828       /// We're evaluating the construction of EvaluatingDecl.
829       Ctor,
830       /// We're evaluating the destruction of EvaluatingDecl.
831       Dtor,
832     };
833     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
834 
835     /// EvaluatingDeclValue - This is the value being constructed for the
836     /// declaration whose initializer is being evaluated, if any.
837     APValue *EvaluatingDeclValue;
838 
839     /// Set of objects that are currently being constructed.
840     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
841         ObjectsUnderConstruction;
842 
843     /// Current heap allocations, along with the location where each was
844     /// allocated. We use std::map here because we need stable addresses
845     /// for the stored APValues.
846     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
847 
848     /// The number of heap allocations performed so far in this evaluation.
849     unsigned NumHeapAllocs = 0;
850 
851     struct EvaluatingConstructorRAII {
852       EvalInfo &EI;
853       ObjectUnderConstruction Object;
854       bool DidInsert;
EvaluatingConstructorRAII__anone93968c60311::EvalInfo::EvaluatingConstructorRAII855       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
856                                 bool HasBases)
857           : EI(EI), Object(Object) {
858         DidInsert =
859             EI.ObjectsUnderConstruction
860                 .insert({Object, HasBases ? ConstructionPhase::Bases
861                                           : ConstructionPhase::AfterBases})
862                 .second;
863       }
finishedConstructingBases__anone93968c60311::EvalInfo::EvaluatingConstructorRAII864       void finishedConstructingBases() {
865         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
866       }
finishedConstructingFields__anone93968c60311::EvalInfo::EvaluatingConstructorRAII867       void finishedConstructingFields() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
869       }
~EvaluatingConstructorRAII__anone93968c60311::EvalInfo::EvaluatingConstructorRAII870       ~EvaluatingConstructorRAII() {
871         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
872       }
873     };
874 
875     struct EvaluatingDestructorRAII {
876       EvalInfo &EI;
877       ObjectUnderConstruction Object;
878       bool DidInsert;
EvaluatingDestructorRAII__anone93968c60311::EvalInfo::EvaluatingDestructorRAII879       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
880           : EI(EI), Object(Object) {
881         DidInsert = EI.ObjectsUnderConstruction
882                         .insert({Object, ConstructionPhase::Destroying})
883                         .second;
884       }
startedDestroyingBases__anone93968c60311::EvalInfo::EvaluatingDestructorRAII885       void startedDestroyingBases() {
886         EI.ObjectsUnderConstruction[Object] =
887             ConstructionPhase::DestroyingBases;
888       }
~EvaluatingDestructorRAII__anone93968c60311::EvalInfo::EvaluatingDestructorRAII889       ~EvaluatingDestructorRAII() {
890         if (DidInsert)
891           EI.ObjectsUnderConstruction.erase(Object);
892       }
893     };
894 
895     ConstructionPhase
isEvaluatingCtorDtor(APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path)896     isEvaluatingCtorDtor(APValue::LValueBase Base,
897                          ArrayRef<APValue::LValuePathEntry> Path) {
898       return ObjectsUnderConstruction.lookup({Base, Path});
899     }
900 
901     /// If we're currently speculatively evaluating, the outermost call stack
902     /// depth at which we can mutate state, otherwise 0.
903     unsigned SpeculativeEvaluationDepth = 0;
904 
905     /// The current array initialization index, if we're performing array
906     /// initialization.
907     uint64_t ArrayInitIndex = -1;
908 
909     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
910     /// notes attached to it will also be stored, otherwise they will not be.
911     bool HasActiveDiagnostic;
912 
913     /// Have we emitted a diagnostic explaining why we couldn't constant
914     /// fold (not just why it's not strictly a constant expression)?
915     bool HasFoldFailureDiagnostic;
916 
917     /// Whether or not we're in a context where the front end requires a
918     /// constant value.
919     bool InConstantContext;
920 
921     /// Whether we're checking that an expression is a potential constant
922     /// expression. If so, do not fail on constructs that could become constant
923     /// later on (such as a use of an undefined global).
924     bool CheckingPotentialConstantExpression = false;
925 
926     /// Whether we're checking for an expression that has undefined behavior.
927     /// If so, we will produce warnings if we encounter an operation that is
928     /// always undefined.
929     bool CheckingForUndefinedBehavior = false;
930 
931     enum EvaluationMode {
932       /// Evaluate as a constant expression. Stop if we find that the expression
933       /// is not a constant expression.
934       EM_ConstantExpression,
935 
936       /// Evaluate as a constant expression. Stop if we find that the expression
937       /// is not a constant expression. Some expressions can be retried in the
938       /// optimizer if we don't constant fold them here, but in an unevaluated
939       /// context we try to fold them immediately since the optimizer never
940       /// gets a chance to look at it.
941       EM_ConstantExpressionUnevaluated,
942 
943       /// Fold the expression to a constant. Stop if we hit a side-effect that
944       /// we can't model.
945       EM_ConstantFold,
946 
947       /// Evaluate in any way we know how. Don't worry about side-effects that
948       /// can't be modeled.
949       EM_IgnoreSideEffects,
950     } EvalMode;
951 
952     /// Are we checking whether the expression is a potential constant
953     /// expression?
checkingPotentialConstantExpression() const954     bool checkingPotentialConstantExpression() const override  {
955       return CheckingPotentialConstantExpression;
956     }
957 
958     /// Are we checking an expression for overflow?
959     // FIXME: We should check for any kind of undefined or suspicious behavior
960     // in such constructs, not just overflow.
checkingForUndefinedBehavior() const961     bool checkingForUndefinedBehavior() const override {
962       return CheckingForUndefinedBehavior;
963     }
964 
EvalInfo(const ASTContext & C,Expr::EvalStatus & S,EvaluationMode Mode)965     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
966         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
967           CallStackDepth(0), NextCallIndex(1),
968           StepsLeft(C.getLangOpts().ConstexprStepLimit),
969           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
970           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
971           EvaluatingDecl((const ValueDecl *)nullptr),
972           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
973           HasFoldFailureDiagnostic(false), InConstantContext(false),
974           EvalMode(Mode) {}
975 
~EvalInfo()976     ~EvalInfo() {
977       discardCleanups();
978     }
979 
setEvaluatingDecl(APValue::LValueBase Base,APValue & Value,EvaluatingDeclKind EDK=EvaluatingDeclKind::Ctor)980     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
981                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
982       EvaluatingDecl = Base;
983       IsEvaluatingDecl = EDK;
984       EvaluatingDeclValue = &Value;
985     }
986 
CheckCallLimit(SourceLocation Loc)987     bool CheckCallLimit(SourceLocation Loc) {
988       // Don't perform any constexpr calls (other than the call we're checking)
989       // when checking a potential constant expression.
990       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
991         return false;
992       if (NextCallIndex == 0) {
993         // NextCallIndex has wrapped around.
994         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
995         return false;
996       }
997       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
998         return true;
999       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1000         << getLangOpts().ConstexprCallDepth;
1001       return false;
1002     }
1003 
1004     std::pair<CallStackFrame *, unsigned>
getCallFrameAndDepth(unsigned CallIndex)1005     getCallFrameAndDepth(unsigned CallIndex) {
1006       assert(CallIndex && "no call index in getCallFrameAndDepth");
1007       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1008       // be null in this loop.
1009       unsigned Depth = CallStackDepth;
1010       CallStackFrame *Frame = CurrentCall;
1011       while (Frame->Index > CallIndex) {
1012         Frame = Frame->Caller;
1013         --Depth;
1014       }
1015       if (Frame->Index == CallIndex)
1016         return {Frame, Depth};
1017       return {nullptr, 0};
1018     }
1019 
nextStep(const Stmt * S)1020     bool nextStep(const Stmt *S) {
1021       if (!StepsLeft) {
1022         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1023         return false;
1024       }
1025       --StepsLeft;
1026       return true;
1027     }
1028 
1029     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1030 
lookupDynamicAlloc(DynamicAllocLValue DA)1031     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1032       Optional<DynAlloc*> Result;
1033       auto It = HeapAllocs.find(DA);
1034       if (It != HeapAllocs.end())
1035         Result = &It->second;
1036       return Result;
1037     }
1038 
1039     /// Get the allocated storage for the given parameter of the given call.
getParamSlot(CallRef Call,const ParmVarDecl * PVD)1040     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1041       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1042       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1043                    : nullptr;
1044     }
1045 
1046     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1047     struct StdAllocatorCaller {
1048       unsigned FrameIndex;
1049       QualType ElemType;
operator bool__anone93968c60311::EvalInfo::StdAllocatorCaller1050       explicit operator bool() const { return FrameIndex != 0; };
1051     };
1052 
getStdAllocatorCaller(StringRef FnName) const1053     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1054       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1055            Call = Call->Caller) {
1056         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1057         if (!MD)
1058           continue;
1059         const IdentifierInfo *FnII = MD->getIdentifier();
1060         if (!FnII || !FnII->isStr(FnName))
1061           continue;
1062 
1063         const auto *CTSD =
1064             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1065         if (!CTSD)
1066           continue;
1067 
1068         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1069         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1070         if (CTSD->isInStdNamespace() && ClassII &&
1071             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1072             TAL[0].getKind() == TemplateArgument::Type)
1073           return {Call->Index, TAL[0].getAsType()};
1074       }
1075 
1076       return {};
1077     }
1078 
performLifetimeExtension()1079     void performLifetimeExtension() {
1080       // Disable the cleanups for lifetime-extended temporaries.
1081       CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1082                                         CleanupStack.end(),
1083                                         [](Cleanup &C) {
1084                                           return !C.isDestroyedAtEndOf(
1085                                               ScopeKind::FullExpression);
1086                                         }),
1087                          CleanupStack.end());
1088      }
1089 
1090     /// Throw away any remaining cleanups at the end of evaluation. If any
1091     /// cleanups would have had a side-effect, note that as an unmodeled
1092     /// side-effect and return false. Otherwise, return true.
discardCleanups()1093     bool discardCleanups() {
1094       for (Cleanup &C : CleanupStack) {
1095         if (C.hasSideEffect() && !noteSideEffect()) {
1096           CleanupStack.clear();
1097           return false;
1098         }
1099       }
1100       CleanupStack.clear();
1101       return true;
1102     }
1103 
1104   private:
getCurrentFrame()1105     interp::Frame *getCurrentFrame() override { return CurrentCall; }
getBottomFrame() const1106     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1107 
hasActiveDiagnostic()1108     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
setActiveDiagnostic(bool Flag)1109     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1110 
setFoldFailureDiagnostic(bool Flag)1111     void setFoldFailureDiagnostic(bool Flag) override {
1112       HasFoldFailureDiagnostic = Flag;
1113     }
1114 
getEvalStatus() const1115     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1116 
getCtx() const1117     ASTContext &getCtx() const override { return Ctx; }
1118 
1119     // If we have a prior diagnostic, it will be noting that the expression
1120     // isn't a constant expression. This diagnostic is more important,
1121     // unless we require this evaluation to produce a constant expression.
1122     //
1123     // FIXME: We might want to show both diagnostics to the user in
1124     // EM_ConstantFold mode.
hasPriorDiagnostic()1125     bool hasPriorDiagnostic() override {
1126       if (!EvalStatus.Diag->empty()) {
1127         switch (EvalMode) {
1128         case EM_ConstantFold:
1129         case EM_IgnoreSideEffects:
1130           if (!HasFoldFailureDiagnostic)
1131             break;
1132           // We've already failed to fold something. Keep that diagnostic.
1133           LLVM_FALLTHROUGH;
1134         case EM_ConstantExpression:
1135         case EM_ConstantExpressionUnevaluated:
1136           setActiveDiagnostic(false);
1137           return true;
1138         }
1139       }
1140       return false;
1141     }
1142 
getCallStackDepth()1143     unsigned getCallStackDepth() override { return CallStackDepth; }
1144 
1145   public:
1146     /// Should we continue evaluation after encountering a side-effect that we
1147     /// couldn't model?
keepEvaluatingAfterSideEffect()1148     bool keepEvaluatingAfterSideEffect() {
1149       switch (EvalMode) {
1150       case EM_IgnoreSideEffects:
1151         return true;
1152 
1153       case EM_ConstantExpression:
1154       case EM_ConstantExpressionUnevaluated:
1155       case EM_ConstantFold:
1156         // By default, assume any side effect might be valid in some other
1157         // evaluation of this expression from a different context.
1158         return checkingPotentialConstantExpression() ||
1159                checkingForUndefinedBehavior();
1160       }
1161       llvm_unreachable("Missed EvalMode case");
1162     }
1163 
1164     /// Note that we have had a side-effect, and determine whether we should
1165     /// keep evaluating.
noteSideEffect()1166     bool noteSideEffect() {
1167       EvalStatus.HasSideEffects = true;
1168       return keepEvaluatingAfterSideEffect();
1169     }
1170 
1171     /// Should we continue evaluation after encountering undefined behavior?
keepEvaluatingAfterUndefinedBehavior()1172     bool keepEvaluatingAfterUndefinedBehavior() {
1173       switch (EvalMode) {
1174       case EM_IgnoreSideEffects:
1175       case EM_ConstantFold:
1176         return true;
1177 
1178       case EM_ConstantExpression:
1179       case EM_ConstantExpressionUnevaluated:
1180         return checkingForUndefinedBehavior();
1181       }
1182       llvm_unreachable("Missed EvalMode case");
1183     }
1184 
1185     /// Note that we hit something that was technically undefined behavior, but
1186     /// that we can evaluate past it (such as signed overflow or floating-point
1187     /// division by zero.)
noteUndefinedBehavior()1188     bool noteUndefinedBehavior() override {
1189       EvalStatus.HasUndefinedBehavior = true;
1190       return keepEvaluatingAfterUndefinedBehavior();
1191     }
1192 
1193     /// Should we continue evaluation as much as possible after encountering a
1194     /// construct which can't be reduced to a value?
keepEvaluatingAfterFailure() const1195     bool keepEvaluatingAfterFailure() const override {
1196       if (!StepsLeft)
1197         return false;
1198 
1199       switch (EvalMode) {
1200       case EM_ConstantExpression:
1201       case EM_ConstantExpressionUnevaluated:
1202       case EM_ConstantFold:
1203       case EM_IgnoreSideEffects:
1204         return checkingPotentialConstantExpression() ||
1205                checkingForUndefinedBehavior();
1206       }
1207       llvm_unreachable("Missed EvalMode case");
1208     }
1209 
1210     /// Notes that we failed to evaluate an expression that other expressions
1211     /// directly depend on, and determine if we should keep evaluating. This
1212     /// should only be called if we actually intend to keep evaluating.
1213     ///
1214     /// Call noteSideEffect() instead if we may be able to ignore the value that
1215     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1216     ///
1217     /// (Foo(), 1)      // use noteSideEffect
1218     /// (Foo() || true) // use noteSideEffect
1219     /// Foo() + 1       // use noteFailure
noteFailure()1220     LLVM_NODISCARD bool noteFailure() {
1221       // Failure when evaluating some expression often means there is some
1222       // subexpression whose evaluation was skipped. Therefore, (because we
1223       // don't track whether we skipped an expression when unwinding after an
1224       // evaluation failure) every evaluation failure that bubbles up from a
1225       // subexpression implies that a side-effect has potentially happened. We
1226       // skip setting the HasSideEffects flag to true until we decide to
1227       // continue evaluating after that point, which happens here.
1228       bool KeepGoing = keepEvaluatingAfterFailure();
1229       EvalStatus.HasSideEffects |= KeepGoing;
1230       return KeepGoing;
1231     }
1232 
1233     class ArrayInitLoopIndex {
1234       EvalInfo &Info;
1235       uint64_t OuterIndex;
1236 
1237     public:
ArrayInitLoopIndex(EvalInfo & Info)1238       ArrayInitLoopIndex(EvalInfo &Info)
1239           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1240         Info.ArrayInitIndex = 0;
1241       }
~ArrayInitLoopIndex()1242       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1243 
operator uint64_t&()1244       operator uint64_t&() { return Info.ArrayInitIndex; }
1245     };
1246   };
1247 
1248   /// Object used to treat all foldable expressions as constant expressions.
1249   struct FoldConstant {
1250     EvalInfo &Info;
1251     bool Enabled;
1252     bool HadNoPriorDiags;
1253     EvalInfo::EvaluationMode OldMode;
1254 
FoldConstant__anone93968c60311::FoldConstant1255     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1256       : Info(Info),
1257         Enabled(Enabled),
1258         HadNoPriorDiags(Info.EvalStatus.Diag &&
1259                         Info.EvalStatus.Diag->empty() &&
1260                         !Info.EvalStatus.HasSideEffects),
1261         OldMode(Info.EvalMode) {
1262       if (Enabled)
1263         Info.EvalMode = EvalInfo::EM_ConstantFold;
1264     }
keepDiagnostics__anone93968c60311::FoldConstant1265     void keepDiagnostics() { Enabled = false; }
~FoldConstant__anone93968c60311::FoldConstant1266     ~FoldConstant() {
1267       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1268           !Info.EvalStatus.HasSideEffects)
1269         Info.EvalStatus.Diag->clear();
1270       Info.EvalMode = OldMode;
1271     }
1272   };
1273 
1274   /// RAII object used to set the current evaluation mode to ignore
1275   /// side-effects.
1276   struct IgnoreSideEffectsRAII {
1277     EvalInfo &Info;
1278     EvalInfo::EvaluationMode OldMode;
IgnoreSideEffectsRAII__anone93968c60311::IgnoreSideEffectsRAII1279     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1280         : Info(Info), OldMode(Info.EvalMode) {
1281       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1282     }
1283 
~IgnoreSideEffectsRAII__anone93968c60311::IgnoreSideEffectsRAII1284     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1285   };
1286 
1287   /// RAII object used to optionally suppress diagnostics and side-effects from
1288   /// a speculative evaluation.
1289   class SpeculativeEvaluationRAII {
1290     EvalInfo *Info = nullptr;
1291     Expr::EvalStatus OldStatus;
1292     unsigned OldSpeculativeEvaluationDepth;
1293 
moveFromAndCancel(SpeculativeEvaluationRAII && Other)1294     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1295       Info = Other.Info;
1296       OldStatus = Other.OldStatus;
1297       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1298       Other.Info = nullptr;
1299     }
1300 
maybeRestoreState()1301     void maybeRestoreState() {
1302       if (!Info)
1303         return;
1304 
1305       Info->EvalStatus = OldStatus;
1306       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1307     }
1308 
1309   public:
1310     SpeculativeEvaluationRAII() = default;
1311 
SpeculativeEvaluationRAII(EvalInfo & Info,SmallVectorImpl<PartialDiagnosticAt> * NewDiag=nullptr)1312     SpeculativeEvaluationRAII(
1313         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1314         : Info(&Info), OldStatus(Info.EvalStatus),
1315           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1316       Info.EvalStatus.Diag = NewDiag;
1317       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1318     }
1319 
1320     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
SpeculativeEvaluationRAII(SpeculativeEvaluationRAII && Other)1321     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1322       moveFromAndCancel(std::move(Other));
1323     }
1324 
operator =(SpeculativeEvaluationRAII && Other)1325     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1326       maybeRestoreState();
1327       moveFromAndCancel(std::move(Other));
1328       return *this;
1329     }
1330 
~SpeculativeEvaluationRAII()1331     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1332   };
1333 
1334   /// RAII object wrapping a full-expression or block scope, and handling
1335   /// the ending of the lifetime of temporaries created within it.
1336   template<ScopeKind Kind>
1337   class ScopeRAII {
1338     EvalInfo &Info;
1339     unsigned OldStackSize;
1340   public:
ScopeRAII(EvalInfo & Info)1341     ScopeRAII(EvalInfo &Info)
1342         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1343       // Push a new temporary version. This is needed to distinguish between
1344       // temporaries created in different iterations of a loop.
1345       Info.CurrentCall->pushTempVersion();
1346     }
destroy(bool RunDestructors=true)1347     bool destroy(bool RunDestructors = true) {
1348       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1349       OldStackSize = -1U;
1350       return OK;
1351     }
~ScopeRAII()1352     ~ScopeRAII() {
1353       if (OldStackSize != -1U)
1354         destroy(false);
1355       // Body moved to a static method to encourage the compiler to inline away
1356       // instances of this class.
1357       Info.CurrentCall->popTempVersion();
1358     }
1359   private:
cleanup(EvalInfo & Info,bool RunDestructors,unsigned OldStackSize)1360     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1361                         unsigned OldStackSize) {
1362       assert(OldStackSize <= Info.CleanupStack.size() &&
1363              "running cleanups out of order?");
1364 
1365       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1366       // for a full-expression scope.
1367       bool Success = true;
1368       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1369         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1370           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1371             Success = false;
1372             break;
1373           }
1374         }
1375       }
1376 
1377       // Compact any retained cleanups.
1378       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1379       if (Kind != ScopeKind::Block)
1380         NewEnd =
1381             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1382               return C.isDestroyedAtEndOf(Kind);
1383             });
1384       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1385       return Success;
1386     }
1387   };
1388   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1389   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1390   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1391 }
1392 
checkSubobject(EvalInfo & Info,const Expr * E,CheckSubobjectKind CSK)1393 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1394                                          CheckSubobjectKind CSK) {
1395   if (Invalid)
1396     return false;
1397   if (isOnePastTheEnd()) {
1398     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1399       << CSK;
1400     setInvalid();
1401     return false;
1402   }
1403   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1404   // must actually be at least one array element; even a VLA cannot have a
1405   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1406   return true;
1407 }
1408 
diagnoseUnsizedArrayPointerArithmetic(EvalInfo & Info,const Expr * E)1409 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1410                                                                 const Expr *E) {
1411   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1412   // Do not set the designator as invalid: we can represent this situation,
1413   // and correct handling of __builtin_object_size requires us to do so.
1414 }
1415 
diagnosePointerArithmetic(EvalInfo & Info,const Expr * E,const APSInt & N)1416 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1417                                                     const Expr *E,
1418                                                     const APSInt &N) {
1419   // If we're complaining, we must be able to statically determine the size of
1420   // the most derived array.
1421   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1422     Info.CCEDiag(E, diag::note_constexpr_array_index)
1423       << N << /*array*/ 0
1424       << static_cast<unsigned>(getMostDerivedArraySize());
1425   else
1426     Info.CCEDiag(E, diag::note_constexpr_array_index)
1427       << N << /*non-array*/ 1;
1428   setInvalid();
1429 }
1430 
CallStackFrame(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,CallRef Call)1431 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1432                                const FunctionDecl *Callee, const LValue *This,
1433                                CallRef Call)
1434     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1435       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1436   Info.CurrentCall = this;
1437   ++Info.CallStackDepth;
1438 }
1439 
~CallStackFrame()1440 CallStackFrame::~CallStackFrame() {
1441   assert(Info.CurrentCall == this && "calls retired out of order");
1442   --Info.CallStackDepth;
1443   Info.CurrentCall = Caller;
1444 }
1445 
isRead(AccessKinds AK)1446 static bool isRead(AccessKinds AK) {
1447   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1448 }
1449 
isModification(AccessKinds AK)1450 static bool isModification(AccessKinds AK) {
1451   switch (AK) {
1452   case AK_Read:
1453   case AK_ReadObjectRepresentation:
1454   case AK_MemberCall:
1455   case AK_DynamicCast:
1456   case AK_TypeId:
1457     return false;
1458   case AK_Assign:
1459   case AK_Increment:
1460   case AK_Decrement:
1461   case AK_Construct:
1462   case AK_Destroy:
1463     return true;
1464   }
1465   llvm_unreachable("unknown access kind");
1466 }
1467 
isAnyAccess(AccessKinds AK)1468 static bool isAnyAccess(AccessKinds AK) {
1469   return isRead(AK) || isModification(AK);
1470 }
1471 
1472 /// Is this an access per the C++ definition?
isFormalAccess(AccessKinds AK)1473 static bool isFormalAccess(AccessKinds AK) {
1474   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1475 }
1476 
1477 /// Is this kind of axcess valid on an indeterminate object value?
isValidIndeterminateAccess(AccessKinds AK)1478 static bool isValidIndeterminateAccess(AccessKinds AK) {
1479   switch (AK) {
1480   case AK_Read:
1481   case AK_Increment:
1482   case AK_Decrement:
1483     // These need the object's value.
1484     return false;
1485 
1486   case AK_ReadObjectRepresentation:
1487   case AK_Assign:
1488   case AK_Construct:
1489   case AK_Destroy:
1490     // Construction and destruction don't need the value.
1491     return true;
1492 
1493   case AK_MemberCall:
1494   case AK_DynamicCast:
1495   case AK_TypeId:
1496     // These aren't really meaningful on scalars.
1497     return true;
1498   }
1499   llvm_unreachable("unknown access kind");
1500 }
1501 
1502 namespace {
1503   struct ComplexValue {
1504   private:
1505     bool IsInt;
1506 
1507   public:
1508     APSInt IntReal, IntImag;
1509     APFloat FloatReal, FloatImag;
1510 
ComplexValue__anone93968c60611::ComplexValue1511     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1512 
makeComplexFloat__anone93968c60611::ComplexValue1513     void makeComplexFloat() { IsInt = false; }
isComplexFloat__anone93968c60611::ComplexValue1514     bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anone93968c60611::ComplexValue1515     APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anone93968c60611::ComplexValue1516     APFloat &getComplexFloatImag() { return FloatImag; }
1517 
makeComplexInt__anone93968c60611::ComplexValue1518     void makeComplexInt() { IsInt = true; }
isComplexInt__anone93968c60611::ComplexValue1519     bool isComplexInt() const { return IsInt; }
getComplexIntReal__anone93968c60611::ComplexValue1520     APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anone93968c60611::ComplexValue1521     APSInt &getComplexIntImag() { return IntImag; }
1522 
moveInto__anone93968c60611::ComplexValue1523     void moveInto(APValue &v) const {
1524       if (isComplexFloat())
1525         v = APValue(FloatReal, FloatImag);
1526       else
1527         v = APValue(IntReal, IntImag);
1528     }
setFrom__anone93968c60611::ComplexValue1529     void setFrom(const APValue &v) {
1530       assert(v.isComplexFloat() || v.isComplexInt());
1531       if (v.isComplexFloat()) {
1532         makeComplexFloat();
1533         FloatReal = v.getComplexFloatReal();
1534         FloatImag = v.getComplexFloatImag();
1535       } else {
1536         makeComplexInt();
1537         IntReal = v.getComplexIntReal();
1538         IntImag = v.getComplexIntImag();
1539       }
1540     }
1541   };
1542 
1543   struct LValue {
1544     APValue::LValueBase Base;
1545     CharUnits Offset;
1546     SubobjectDesignator Designator;
1547     bool IsNullPtr : 1;
1548     bool InvalidBase : 1;
1549 
getLValueBase__anone93968c60611::LValue1550     const APValue::LValueBase getLValueBase() const { return Base; }
getLValueOffset__anone93968c60611::LValue1551     CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anone93968c60611::LValue1552     const CharUnits &getLValueOffset() const { return Offset; }
getLValueDesignator__anone93968c60611::LValue1553     SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anone93968c60611::LValue1554     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
isNullPointer__anone93968c60611::LValue1555     bool isNullPointer() const { return IsNullPtr;}
1556 
getLValueCallIndex__anone93968c60611::LValue1557     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
getLValueVersion__anone93968c60611::LValue1558     unsigned getLValueVersion() const { return Base.getVersion(); }
1559 
moveInto__anone93968c60611::LValue1560     void moveInto(APValue &V) const {
1561       if (Designator.Invalid)
1562         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1563       else {
1564         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1565         V = APValue(Base, Offset, Designator.Entries,
1566                     Designator.IsOnePastTheEnd, IsNullPtr);
1567       }
1568     }
setFrom__anone93968c60611::LValue1569     void setFrom(ASTContext &Ctx, const APValue &V) {
1570       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1571       Base = V.getLValueBase();
1572       Offset = V.getLValueOffset();
1573       InvalidBase = false;
1574       Designator = SubobjectDesignator(Ctx, V);
1575       IsNullPtr = V.isNullPointer();
1576     }
1577 
set__anone93968c60611::LValue1578     void set(APValue::LValueBase B, bool BInvalid = false) {
1579 #ifndef NDEBUG
1580       // We only allow a few types of invalid bases. Enforce that here.
1581       if (BInvalid) {
1582         const auto *E = B.get<const Expr *>();
1583         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1584                "Unexpected type of invalid base");
1585       }
1586 #endif
1587 
1588       Base = B;
1589       Offset = CharUnits::fromQuantity(0);
1590       InvalidBase = BInvalid;
1591       Designator = SubobjectDesignator(getType(B));
1592       IsNullPtr = false;
1593     }
1594 
setNull__anone93968c60611::LValue1595     void setNull(ASTContext &Ctx, QualType PointerTy) {
1596       Base = (const ValueDecl *)nullptr;
1597       Offset =
1598           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1599       InvalidBase = false;
1600       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1601       IsNullPtr = true;
1602     }
1603 
setInvalid__anone93968c60611::LValue1604     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1605       set(B, true);
1606     }
1607 
toString__anone93968c60611::LValue1608     std::string toString(ASTContext &Ctx, QualType T) const {
1609       APValue Printable;
1610       moveInto(Printable);
1611       return Printable.getAsString(Ctx, T);
1612     }
1613 
1614   private:
1615     // Check that this LValue is not based on a null pointer. If it is, produce
1616     // a diagnostic and mark the designator as invalid.
1617     template <typename GenDiagType>
checkNullPointerDiagnosingWith__anone93968c60611::LValue1618     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1619       if (Designator.Invalid)
1620         return false;
1621       if (IsNullPtr) {
1622         GenDiag();
1623         Designator.setInvalid();
1624         return false;
1625       }
1626       return true;
1627     }
1628 
1629   public:
checkNullPointer__anone93968c60611::LValue1630     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1631                           CheckSubobjectKind CSK) {
1632       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1633         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1634       });
1635     }
1636 
checkNullPointerForFoldAccess__anone93968c60611::LValue1637     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1638                                        AccessKinds AK) {
1639       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1640         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1641       });
1642     }
1643 
1644     // Check this LValue refers to an object. If not, set the designator to be
1645     // invalid and emit a diagnostic.
checkSubobject__anone93968c60611::LValue1646     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1647       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1648              Designator.checkSubobject(Info, E, CSK);
1649     }
1650 
addDecl__anone93968c60611::LValue1651     void addDecl(EvalInfo &Info, const Expr *E,
1652                  const Decl *D, bool Virtual = false) {
1653       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1654         Designator.addDeclUnchecked(D, Virtual);
1655     }
addUnsizedArray__anone93968c60611::LValue1656     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1657       if (!Designator.Entries.empty()) {
1658         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1659         Designator.setInvalid();
1660         return;
1661       }
1662       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1663         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1664         Designator.FirstEntryIsAnUnsizedArray = true;
1665         Designator.addUnsizedArrayUnchecked(ElemTy);
1666       }
1667     }
addArray__anone93968c60611::LValue1668     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1669       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1670         Designator.addArrayUnchecked(CAT);
1671     }
addComplex__anone93968c60611::LValue1672     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1673       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1674         Designator.addComplexUnchecked(EltTy, Imag);
1675     }
clearIsNullPointer__anone93968c60611::LValue1676     void clearIsNullPointer() {
1677       IsNullPtr = false;
1678     }
adjustOffsetAndIndex__anone93968c60611::LValue1679     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1680                               const APSInt &Index, CharUnits ElementSize) {
1681       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1682       // but we're not required to diagnose it and it's valid in C++.)
1683       if (!Index)
1684         return;
1685 
1686       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1687       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1688       // offsets.
1689       uint64_t Offset64 = Offset.getQuantity();
1690       uint64_t ElemSize64 = ElementSize.getQuantity();
1691       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1692       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1693 
1694       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1695         Designator.adjustIndex(Info, E, Index);
1696       clearIsNullPointer();
1697     }
adjustOffset__anone93968c60611::LValue1698     void adjustOffset(CharUnits N) {
1699       Offset += N;
1700       if (N.getQuantity())
1701         clearIsNullPointer();
1702     }
1703   };
1704 
1705   struct MemberPtr {
MemberPtr__anone93968c60611::MemberPtr1706     MemberPtr() {}
MemberPtr__anone93968c60611::MemberPtr1707     explicit MemberPtr(const ValueDecl *Decl) :
1708       DeclAndIsDerivedMember(Decl, false), Path() {}
1709 
1710     /// The member or (direct or indirect) field referred to by this member
1711     /// pointer, or 0 if this is a null member pointer.
getDecl__anone93968c60611::MemberPtr1712     const ValueDecl *getDecl() const {
1713       return DeclAndIsDerivedMember.getPointer();
1714     }
1715     /// Is this actually a member of some type derived from the relevant class?
isDerivedMember__anone93968c60611::MemberPtr1716     bool isDerivedMember() const {
1717       return DeclAndIsDerivedMember.getInt();
1718     }
1719     /// Get the class which the declaration actually lives in.
getContainingRecord__anone93968c60611::MemberPtr1720     const CXXRecordDecl *getContainingRecord() const {
1721       return cast<CXXRecordDecl>(
1722           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1723     }
1724 
moveInto__anone93968c60611::MemberPtr1725     void moveInto(APValue &V) const {
1726       V = APValue(getDecl(), isDerivedMember(), Path);
1727     }
setFrom__anone93968c60611::MemberPtr1728     void setFrom(const APValue &V) {
1729       assert(V.isMemberPointer());
1730       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1731       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1732       Path.clear();
1733       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1734       Path.insert(Path.end(), P.begin(), P.end());
1735     }
1736 
1737     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1738     /// whether the member is a member of some class derived from the class type
1739     /// of the member pointer.
1740     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1741     /// Path - The path of base/derived classes from the member declaration's
1742     /// class (exclusive) to the class type of the member pointer (inclusive).
1743     SmallVector<const CXXRecordDecl*, 4> Path;
1744 
1745     /// Perform a cast towards the class of the Decl (either up or down the
1746     /// hierarchy).
castBack__anone93968c60611::MemberPtr1747     bool castBack(const CXXRecordDecl *Class) {
1748       assert(!Path.empty());
1749       const CXXRecordDecl *Expected;
1750       if (Path.size() >= 2)
1751         Expected = Path[Path.size() - 2];
1752       else
1753         Expected = getContainingRecord();
1754       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1755         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1756         // if B does not contain the original member and is not a base or
1757         // derived class of the class containing the original member, the result
1758         // of the cast is undefined.
1759         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1760         // (D::*). We consider that to be a language defect.
1761         return false;
1762       }
1763       Path.pop_back();
1764       return true;
1765     }
1766     /// Perform a base-to-derived member pointer cast.
castToDerived__anone93968c60611::MemberPtr1767     bool castToDerived(const CXXRecordDecl *Derived) {
1768       if (!getDecl())
1769         return true;
1770       if (!isDerivedMember()) {
1771         Path.push_back(Derived);
1772         return true;
1773       }
1774       if (!castBack(Derived))
1775         return false;
1776       if (Path.empty())
1777         DeclAndIsDerivedMember.setInt(false);
1778       return true;
1779     }
1780     /// Perform a derived-to-base member pointer cast.
castToBase__anone93968c60611::MemberPtr1781     bool castToBase(const CXXRecordDecl *Base) {
1782       if (!getDecl())
1783         return true;
1784       if (Path.empty())
1785         DeclAndIsDerivedMember.setInt(true);
1786       if (isDerivedMember()) {
1787         Path.push_back(Base);
1788         return true;
1789       }
1790       return castBack(Base);
1791     }
1792   };
1793 
1794   /// Compare two member pointers, which are assumed to be of the same type.
operator ==(const MemberPtr & LHS,const MemberPtr & RHS)1795   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1796     if (!LHS.getDecl() || !RHS.getDecl())
1797       return !LHS.getDecl() && !RHS.getDecl();
1798     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1799       return false;
1800     return LHS.Path == RHS.Path;
1801   }
1802 }
1803 
1804 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1805 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1806                             const LValue &This, const Expr *E,
1807                             bool AllowNonLiteralTypes = false);
1808 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1809                            bool InvalidBaseOK = false);
1810 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1811                             bool InvalidBaseOK = false);
1812 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1813                                   EvalInfo &Info);
1814 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1815 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1816 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1817                                     EvalInfo &Info);
1818 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1819 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1820 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1821                            EvalInfo &Info);
1822 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1823 
1824 /// Evaluate an integer or fixed point expression into an APResult.
1825 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1826                                         EvalInfo &Info);
1827 
1828 /// Evaluate only a fixed point expression into an APResult.
1829 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1830                                EvalInfo &Info);
1831 
1832 //===----------------------------------------------------------------------===//
1833 // Misc utilities
1834 //===----------------------------------------------------------------------===//
1835 
1836 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1837 /// preserving its value (by extending by up to one bit as needed).
negateAsSigned(APSInt & Int)1838 static void negateAsSigned(APSInt &Int) {
1839   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1840     Int = Int.extend(Int.getBitWidth() + 1);
1841     Int.setIsSigned(true);
1842   }
1843   Int = -Int;
1844 }
1845 
1846 template<typename KeyT>
createTemporary(const KeyT * Key,QualType T,ScopeKind Scope,LValue & LV)1847 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1848                                          ScopeKind Scope, LValue &LV) {
1849   unsigned Version = getTempVersion();
1850   APValue::LValueBase Base(Key, Index, Version);
1851   LV.set(Base);
1852   return createLocal(Base, Key, T, Scope);
1853 }
1854 
1855 /// Allocate storage for a parameter of a function call made in this frame.
createParam(CallRef Args,const ParmVarDecl * PVD,LValue & LV)1856 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1857                                      LValue &LV) {
1858   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1859   APValue::LValueBase Base(PVD, Index, Args.Version);
1860   LV.set(Base);
1861   // We always destroy parameters at the end of the call, even if we'd allow
1862   // them to live to the end of the full-expression at runtime, in order to
1863   // give portable results and match other compilers.
1864   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1865 }
1866 
createLocal(APValue::LValueBase Base,const void * Key,QualType T,ScopeKind Scope)1867 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1868                                      QualType T, ScopeKind Scope) {
1869   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1870   unsigned Version = Base.getVersion();
1871   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1872   assert(Result.isAbsent() && "local created multiple times");
1873 
1874   // If we're creating a local immediately in the operand of a speculative
1875   // evaluation, don't register a cleanup to be run outside the speculative
1876   // evaluation context, since we won't actually be able to initialize this
1877   // object.
1878   if (Index <= Info.SpeculativeEvaluationDepth) {
1879     if (T.isDestructedType())
1880       Info.noteSideEffect();
1881   } else {
1882     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1883   }
1884   return Result;
1885 }
1886 
createHeapAlloc(const Expr * E,QualType T,LValue & LV)1887 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1888   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1889     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1890     return nullptr;
1891   }
1892 
1893   DynamicAllocLValue DA(NumHeapAllocs++);
1894   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1895   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1896                                    std::forward_as_tuple(DA), std::tuple<>());
1897   assert(Result.second && "reused a heap alloc index?");
1898   Result.first->second.AllocExpr = E;
1899   return &Result.first->second.Value;
1900 }
1901 
1902 /// Produce a string describing the given constexpr call.
describe(raw_ostream & Out)1903 void CallStackFrame::describe(raw_ostream &Out) {
1904   unsigned ArgIndex = 0;
1905   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1906                       !isa<CXXConstructorDecl>(Callee) &&
1907                       cast<CXXMethodDecl>(Callee)->isInstance();
1908 
1909   if (!IsMemberCall)
1910     Out << *Callee << '(';
1911 
1912   if (This && IsMemberCall) {
1913     APValue Val;
1914     This->moveInto(Val);
1915     Val.printPretty(Out, Info.Ctx,
1916                     This->Designator.MostDerivedType);
1917     // FIXME: Add parens around Val if needed.
1918     Out << "->" << *Callee << '(';
1919     IsMemberCall = false;
1920   }
1921 
1922   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1923        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1924     if (ArgIndex > (unsigned)IsMemberCall)
1925       Out << ", ";
1926 
1927     const ParmVarDecl *Param = *I;
1928     APValue *V = Info.getParamSlot(Arguments, Param);
1929     if (V)
1930       V->printPretty(Out, Info.Ctx, Param->getType());
1931     else
1932       Out << "<...>";
1933 
1934     if (ArgIndex == 0 && IsMemberCall)
1935       Out << "->" << *Callee << '(';
1936   }
1937 
1938   Out << ')';
1939 }
1940 
1941 /// Evaluate an expression to see if it had side-effects, and discard its
1942 /// result.
1943 /// \return \c true if the caller should keep evaluating.
EvaluateIgnoredValue(EvalInfo & Info,const Expr * E)1944 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1945   assert(!E->isValueDependent());
1946   APValue Scratch;
1947   if (!Evaluate(Scratch, Info, E))
1948     // We don't need the value, but we might have skipped a side effect here.
1949     return Info.noteSideEffect();
1950   return true;
1951 }
1952 
1953 /// Should this call expression be treated as a string literal?
IsStringLiteralCall(const CallExpr * E)1954 static bool IsStringLiteralCall(const CallExpr *E) {
1955   unsigned Builtin = E->getBuiltinCallee();
1956   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1957           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1958 }
1959 
IsGlobalLValue(APValue::LValueBase B)1960 static bool IsGlobalLValue(APValue::LValueBase B) {
1961   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1962   // constant expression of pointer type that evaluates to...
1963 
1964   // ... a null pointer value, or a prvalue core constant expression of type
1965   // std::nullptr_t.
1966   if (!B) return true;
1967 
1968   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1969     // ... the address of an object with static storage duration,
1970     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1971       return VD->hasGlobalStorage();
1972     if (isa<TemplateParamObjectDecl>(D))
1973       return true;
1974     // ... the address of a function,
1975     // ... the address of a GUID [MS extension],
1976     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1977   }
1978 
1979   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1980     return true;
1981 
1982   const Expr *E = B.get<const Expr*>();
1983   switch (E->getStmtClass()) {
1984   default:
1985     return false;
1986   case Expr::CompoundLiteralExprClass: {
1987     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1988     return CLE->isFileScope() && CLE->isLValue();
1989   }
1990   case Expr::MaterializeTemporaryExprClass:
1991     // A materialized temporary might have been lifetime-extended to static
1992     // storage duration.
1993     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1994   // A string literal has static storage duration.
1995   case Expr::StringLiteralClass:
1996   case Expr::PredefinedExprClass:
1997   case Expr::ObjCStringLiteralClass:
1998   case Expr::ObjCEncodeExprClass:
1999     return true;
2000   case Expr::ObjCBoxedExprClass:
2001     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2002   case Expr::CallExprClass:
2003     return IsStringLiteralCall(cast<CallExpr>(E));
2004   // For GCC compatibility, &&label has static storage duration.
2005   case Expr::AddrLabelExprClass:
2006     return true;
2007   // A Block literal expression may be used as the initialization value for
2008   // Block variables at global or local static scope.
2009   case Expr::BlockExprClass:
2010     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2011   case Expr::ImplicitValueInitExprClass:
2012     // FIXME:
2013     // We can never form an lvalue with an implicit value initialization as its
2014     // base through expression evaluation, so these only appear in one case: the
2015     // implicit variable declaration we invent when checking whether a constexpr
2016     // constructor can produce a constant expression. We must assume that such
2017     // an expression might be a global lvalue.
2018     return true;
2019   }
2020 }
2021 
GetLValueBaseDecl(const LValue & LVal)2022 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2023   return LVal.Base.dyn_cast<const ValueDecl*>();
2024 }
2025 
IsLiteralLValue(const LValue & Value)2026 static bool IsLiteralLValue(const LValue &Value) {
2027   if (Value.getLValueCallIndex())
2028     return false;
2029   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2030   return E && !isa<MaterializeTemporaryExpr>(E);
2031 }
2032 
IsWeakLValue(const LValue & Value)2033 static bool IsWeakLValue(const LValue &Value) {
2034   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2035   return Decl && Decl->isWeak();
2036 }
2037 
isZeroSized(const LValue & Value)2038 static bool isZeroSized(const LValue &Value) {
2039   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2040   if (Decl && isa<VarDecl>(Decl)) {
2041     QualType Ty = Decl->getType();
2042     if (Ty->isArrayType())
2043       return Ty->isIncompleteType() ||
2044              Decl->getASTContext().getTypeSize(Ty) == 0;
2045   }
2046   return false;
2047 }
2048 
HasSameBase(const LValue & A,const LValue & B)2049 static bool HasSameBase(const LValue &A, const LValue &B) {
2050   if (!A.getLValueBase())
2051     return !B.getLValueBase();
2052   if (!B.getLValueBase())
2053     return false;
2054 
2055   if (A.getLValueBase().getOpaqueValue() !=
2056       B.getLValueBase().getOpaqueValue())
2057     return false;
2058 
2059   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2060          A.getLValueVersion() == B.getLValueVersion();
2061 }
2062 
NoteLValueLocation(EvalInfo & Info,APValue::LValueBase Base)2063 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2064   assert(Base && "no location for a null lvalue");
2065   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2066 
2067   // For a parameter, find the corresponding call stack frame (if it still
2068   // exists), and point at the parameter of the function definition we actually
2069   // invoked.
2070   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2071     unsigned Idx = PVD->getFunctionScopeIndex();
2072     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2073       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2074           F->Arguments.Version == Base.getVersion() && F->Callee &&
2075           Idx < F->Callee->getNumParams()) {
2076         VD = F->Callee->getParamDecl(Idx);
2077         break;
2078       }
2079     }
2080   }
2081 
2082   if (VD)
2083     Info.Note(VD->getLocation(), diag::note_declared_at);
2084   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2085     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2086   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2087     // FIXME: Produce a note for dangling pointers too.
2088     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2089       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2090                 diag::note_constexpr_dynamic_alloc_here);
2091   }
2092   // We have no information to show for a typeid(T) object.
2093 }
2094 
2095 enum class CheckEvaluationResultKind {
2096   ConstantExpression,
2097   FullyInitialized,
2098 };
2099 
2100 /// Materialized temporaries that we've already checked to determine if they're
2101 /// initializsed by a constant expression.
2102 using CheckedTemporaries =
2103     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2104 
2105 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2106                                   EvalInfo &Info, SourceLocation DiagLoc,
2107                                   QualType Type, const APValue &Value,
2108                                   ConstantExprKind Kind,
2109                                   SourceLocation SubobjectLoc,
2110                                   CheckedTemporaries &CheckedTemps);
2111 
2112 /// Check that this reference or pointer core constant expression is a valid
2113 /// value for an address or reference constant expression. Return true if we
2114 /// can fold this expression, whether or not it's a constant expression.
CheckLValueConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const LValue & LVal,ConstantExprKind Kind,CheckedTemporaries & CheckedTemps)2115 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2116                                           QualType Type, const LValue &LVal,
2117                                           ConstantExprKind Kind,
2118                                           CheckedTemporaries &CheckedTemps) {
2119   bool IsReferenceType = Type->isReferenceType();
2120 
2121   APValue::LValueBase Base = LVal.getLValueBase();
2122   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2123 
2124   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2125   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2126 
2127   // Additional restrictions apply in a template argument. We only enforce the
2128   // C++20 restrictions here; additional syntactic and semantic restrictions
2129   // are applied elsewhere.
2130   if (isTemplateArgument(Kind)) {
2131     int InvalidBaseKind = -1;
2132     StringRef Ident;
2133     if (Base.is<TypeInfoLValue>())
2134       InvalidBaseKind = 0;
2135     else if (isa_and_nonnull<StringLiteral>(BaseE))
2136       InvalidBaseKind = 1;
2137     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2138              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2139       InvalidBaseKind = 2;
2140     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2141       InvalidBaseKind = 3;
2142       Ident = PE->getIdentKindName();
2143     }
2144 
2145     if (InvalidBaseKind != -1) {
2146       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2147           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2148           << Ident;
2149       return false;
2150     }
2151   }
2152 
2153   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2154     if (FD->isConsteval()) {
2155       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2156           << !Type->isAnyPointerType();
2157       Info.Note(FD->getLocation(), diag::note_declared_at);
2158       return false;
2159     }
2160   }
2161 
2162   // Check that the object is a global. Note that the fake 'this' object we
2163   // manufacture when checking potential constant expressions is conservatively
2164   // assumed to be global here.
2165   if (!IsGlobalLValue(Base)) {
2166     if (Info.getLangOpts().CPlusPlus11) {
2167       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2168       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2169         << IsReferenceType << !Designator.Entries.empty()
2170         << !!VD << VD;
2171 
2172       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2173       if (VarD && VarD->isConstexpr()) {
2174         // Non-static local constexpr variables have unintuitive semantics:
2175         //   constexpr int a = 1;
2176         //   constexpr const int *p = &a;
2177         // ... is invalid because the address of 'a' is not constant. Suggest
2178         // adding a 'static' in this case.
2179         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2180             << VarD
2181             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2182       } else {
2183         NoteLValueLocation(Info, Base);
2184       }
2185     } else {
2186       Info.FFDiag(Loc);
2187     }
2188     // Don't allow references to temporaries to escape.
2189     return false;
2190   }
2191   assert((Info.checkingPotentialConstantExpression() ||
2192           LVal.getLValueCallIndex() == 0) &&
2193          "have call index for global lvalue");
2194 
2195   if (Base.is<DynamicAllocLValue>()) {
2196     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2197         << IsReferenceType << !Designator.Entries.empty();
2198     NoteLValueLocation(Info, Base);
2199     return false;
2200   }
2201 
2202   if (BaseVD) {
2203     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2204       // Check if this is a thread-local variable.
2205       if (Var->getTLSKind())
2206         // FIXME: Diagnostic!
2207         return false;
2208 
2209       // A dllimport variable never acts like a constant, unless we're
2210       // evaluating a value for use only in name mangling.
2211       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2212         // FIXME: Diagnostic!
2213         return false;
2214     }
2215     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2216       // __declspec(dllimport) must be handled very carefully:
2217       // We must never initialize an expression with the thunk in C++.
2218       // Doing otherwise would allow the same id-expression to yield
2219       // different addresses for the same function in different translation
2220       // units.  However, this means that we must dynamically initialize the
2221       // expression with the contents of the import address table at runtime.
2222       //
2223       // The C language has no notion of ODR; furthermore, it has no notion of
2224       // dynamic initialization.  This means that we are permitted to
2225       // perform initialization with the address of the thunk.
2226       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2227           FD->hasAttr<DLLImportAttr>())
2228         // FIXME: Diagnostic!
2229         return false;
2230     }
2231   } else if (const auto *MTE =
2232                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2233     if (CheckedTemps.insert(MTE).second) {
2234       QualType TempType = getType(Base);
2235       if (TempType.isDestructedType()) {
2236         Info.FFDiag(MTE->getExprLoc(),
2237                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2238             << TempType;
2239         return false;
2240       }
2241 
2242       APValue *V = MTE->getOrCreateValue(false);
2243       assert(V && "evasluation result refers to uninitialised temporary");
2244       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2245                                  Info, MTE->getExprLoc(), TempType, *V,
2246                                  Kind, SourceLocation(), CheckedTemps))
2247         return false;
2248     }
2249   }
2250 
2251   // Allow address constant expressions to be past-the-end pointers. This is
2252   // an extension: the standard requires them to point to an object.
2253   if (!IsReferenceType)
2254     return true;
2255 
2256   // A reference constant expression must refer to an object.
2257   if (!Base) {
2258     // FIXME: diagnostic
2259     Info.CCEDiag(Loc);
2260     return true;
2261   }
2262 
2263   // Does this refer one past the end of some object?
2264   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2265     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2266       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2267     NoteLValueLocation(Info, Base);
2268   }
2269 
2270   return true;
2271 }
2272 
2273 /// Member pointers are constant expressions unless they point to a
2274 /// non-virtual dllimport member function.
CheckMemberPointerConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const APValue & Value,ConstantExprKind Kind)2275 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2276                                                  SourceLocation Loc,
2277                                                  QualType Type,
2278                                                  const APValue &Value,
2279                                                  ConstantExprKind Kind) {
2280   const ValueDecl *Member = Value.getMemberPointerDecl();
2281   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2282   if (!FD)
2283     return true;
2284   if (FD->isConsteval()) {
2285     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2286     Info.Note(FD->getLocation(), diag::note_declared_at);
2287     return false;
2288   }
2289   return isForManglingOnly(Kind) || FD->isVirtual() ||
2290          !FD->hasAttr<DLLImportAttr>();
2291 }
2292 
2293 /// Check that this core constant expression is of literal type, and if not,
2294 /// produce an appropriate diagnostic.
CheckLiteralType(EvalInfo & Info,const Expr * E,const LValue * This=nullptr)2295 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2296                              const LValue *This = nullptr) {
2297   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2298     return true;
2299 
2300   // C++1y: A constant initializer for an object o [...] may also invoke
2301   // constexpr constructors for o and its subobjects even if those objects
2302   // are of non-literal class types.
2303   //
2304   // C++11 missed this detail for aggregates, so classes like this:
2305   //   struct foo_t { union { int i; volatile int j; } u; };
2306   // are not (obviously) initializable like so:
2307   //   __attribute__((__require_constant_initialization__))
2308   //   static const foo_t x = {{0}};
2309   // because "i" is a subobject with non-literal initialization (due to the
2310   // volatile member of the union). See:
2311   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2312   // Therefore, we use the C++1y behavior.
2313   if (This && Info.EvaluatingDecl == This->getLValueBase())
2314     return true;
2315 
2316   // Prvalue constant expressions must be of literal types.
2317   if (Info.getLangOpts().CPlusPlus11)
2318     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2319       << E->getType();
2320   else
2321     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2322   return false;
2323 }
2324 
CheckEvaluationResult(CheckEvaluationResultKind CERK,EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind,SourceLocation SubobjectLoc,CheckedTemporaries & CheckedTemps)2325 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2326                                   EvalInfo &Info, SourceLocation DiagLoc,
2327                                   QualType Type, const APValue &Value,
2328                                   ConstantExprKind Kind,
2329                                   SourceLocation SubobjectLoc,
2330                                   CheckedTemporaries &CheckedTemps) {
2331   if (!Value.hasValue()) {
2332     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2333       << true << Type;
2334     if (SubobjectLoc.isValid())
2335       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2336     return false;
2337   }
2338 
2339   // We allow _Atomic(T) to be initialized from anything that T can be
2340   // initialized from.
2341   if (const AtomicType *AT = Type->getAs<AtomicType>())
2342     Type = AT->getValueType();
2343 
2344   // Core issue 1454: For a literal constant expression of array or class type,
2345   // each subobject of its value shall have been initialized by a constant
2346   // expression.
2347   if (Value.isArray()) {
2348     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2349     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2350       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2351                                  Value.getArrayInitializedElt(I), Kind,
2352                                  SubobjectLoc, CheckedTemps))
2353         return false;
2354     }
2355     if (!Value.hasArrayFiller())
2356       return true;
2357     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2358                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2359                                  CheckedTemps);
2360   }
2361   if (Value.isUnion() && Value.getUnionField()) {
2362     return CheckEvaluationResult(
2363         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2364         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2365         CheckedTemps);
2366   }
2367   if (Value.isStruct()) {
2368     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2369     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2370       unsigned BaseIndex = 0;
2371       for (const CXXBaseSpecifier &BS : CD->bases()) {
2372         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2373                                    Value.getStructBase(BaseIndex), Kind,
2374                                    BS.getBeginLoc(), CheckedTemps))
2375           return false;
2376         ++BaseIndex;
2377       }
2378     }
2379     for (const auto *I : RD->fields()) {
2380       if (I->isUnnamedBitfield())
2381         continue;
2382 
2383       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2384                                  Value.getStructField(I->getFieldIndex()),
2385                                  Kind, I->getLocation(), CheckedTemps))
2386         return false;
2387     }
2388   }
2389 
2390   if (Value.isLValue() &&
2391       CERK == CheckEvaluationResultKind::ConstantExpression) {
2392     LValue LVal;
2393     LVal.setFrom(Info.Ctx, Value);
2394     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2395                                          CheckedTemps);
2396   }
2397 
2398   if (Value.isMemberPointer() &&
2399       CERK == CheckEvaluationResultKind::ConstantExpression)
2400     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2401 
2402   // Everything else is fine.
2403   return true;
2404 }
2405 
2406 /// Check that this core constant expression value is a valid value for a
2407 /// constant expression. If not, report an appropriate diagnostic. Does not
2408 /// check that the expression is of literal type.
CheckConstantExpression(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind)2409 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2410                                     QualType Type, const APValue &Value,
2411                                     ConstantExprKind Kind) {
2412   // Nothing to check for a constant expression of type 'cv void'.
2413   if (Type->isVoidType())
2414     return true;
2415 
2416   CheckedTemporaries CheckedTemps;
2417   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2418                                Info, DiagLoc, Type, Value, Kind,
2419                                SourceLocation(), CheckedTemps);
2420 }
2421 
2422 /// Check that this evaluated value is fully-initialized and can be loaded by
2423 /// an lvalue-to-rvalue conversion.
CheckFullyInitialized(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value)2424 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2425                                   QualType Type, const APValue &Value) {
2426   CheckedTemporaries CheckedTemps;
2427   return CheckEvaluationResult(
2428       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2429       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2430 }
2431 
2432 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2433 /// "the allocated storage is deallocated within the evaluation".
CheckMemoryLeaks(EvalInfo & Info)2434 static bool CheckMemoryLeaks(EvalInfo &Info) {
2435   if (!Info.HeapAllocs.empty()) {
2436     // We can still fold to a constant despite a compile-time memory leak,
2437     // so long as the heap allocation isn't referenced in the result (we check
2438     // that in CheckConstantExpression).
2439     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2440                  diag::note_constexpr_memory_leak)
2441         << unsigned(Info.HeapAllocs.size() - 1);
2442   }
2443   return true;
2444 }
2445 
EvalPointerValueAsBool(const APValue & Value,bool & Result)2446 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2447   // A null base expression indicates a null pointer.  These are always
2448   // evaluatable, and they are false unless the offset is zero.
2449   if (!Value.getLValueBase()) {
2450     Result = !Value.getLValueOffset().isZero();
2451     return true;
2452   }
2453 
2454   // We have a non-null base.  These are generally known to be true, but if it's
2455   // a weak declaration it can be null at runtime.
2456   Result = true;
2457   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2458   return !Decl || !Decl->isWeak();
2459 }
2460 
HandleConversionToBool(const APValue & Val,bool & Result)2461 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2462   switch (Val.getKind()) {
2463   case APValue::None:
2464   case APValue::Indeterminate:
2465     return false;
2466   case APValue::Int:
2467     Result = Val.getInt().getBoolValue();
2468     return true;
2469   case APValue::FixedPoint:
2470     Result = Val.getFixedPoint().getBoolValue();
2471     return true;
2472   case APValue::Float:
2473     Result = !Val.getFloat().isZero();
2474     return true;
2475   case APValue::ComplexInt:
2476     Result = Val.getComplexIntReal().getBoolValue() ||
2477              Val.getComplexIntImag().getBoolValue();
2478     return true;
2479   case APValue::ComplexFloat:
2480     Result = !Val.getComplexFloatReal().isZero() ||
2481              !Val.getComplexFloatImag().isZero();
2482     return true;
2483   case APValue::LValue:
2484     return EvalPointerValueAsBool(Val, Result);
2485   case APValue::MemberPointer:
2486     Result = Val.getMemberPointerDecl();
2487     return true;
2488   case APValue::Vector:
2489   case APValue::Array:
2490   case APValue::Struct:
2491   case APValue::Union:
2492   case APValue::AddrLabelDiff:
2493     return false;
2494   }
2495 
2496   llvm_unreachable("unknown APValue kind");
2497 }
2498 
EvaluateAsBooleanCondition(const Expr * E,bool & Result,EvalInfo & Info)2499 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2500                                        EvalInfo &Info) {
2501   assert(!E->isValueDependent());
2502   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2503   APValue Val;
2504   if (!Evaluate(Val, Info, E))
2505     return false;
2506   return HandleConversionToBool(Val, Result);
2507 }
2508 
2509 template<typename T>
HandleOverflow(EvalInfo & Info,const Expr * E,const T & SrcValue,QualType DestType)2510 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2511                            const T &SrcValue, QualType DestType) {
2512   Info.CCEDiag(E, diag::note_constexpr_overflow)
2513     << SrcValue << DestType;
2514   return Info.noteUndefinedBehavior();
2515 }
2516 
HandleFloatToIntCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APFloat & Value,QualType DestType,APSInt & Result)2517 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2518                                  QualType SrcType, const APFloat &Value,
2519                                  QualType DestType, APSInt &Result) {
2520   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2521   // Determine whether we are converting to unsigned or signed.
2522   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2523 
2524   Result = APSInt(DestWidth, !DestSigned);
2525   bool ignored;
2526   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2527       & APFloat::opInvalidOp)
2528     return HandleOverflow(Info, E, Value, DestType);
2529   return true;
2530 }
2531 
2532 /// Get rounding mode used for evaluation of the specified expression.
2533 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2534 ///                       dynamic.
2535 /// If rounding mode is unknown at compile time, still try to evaluate the
2536 /// expression. If the result is exact, it does not depend on rounding mode.
2537 /// So return "tonearest" mode instead of "dynamic".
getActiveRoundingMode(EvalInfo & Info,const Expr * E,bool & DynamicRM)2538 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2539                                                 bool &DynamicRM) {
2540   llvm::RoundingMode RM =
2541       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2542   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2543   if (DynamicRM)
2544     RM = llvm::RoundingMode::NearestTiesToEven;
2545   return RM;
2546 }
2547 
2548 /// Check if the given evaluation result is allowed for constant evaluation.
checkFloatingPointResult(EvalInfo & Info,const Expr * E,APFloat::opStatus St)2549 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2550                                      APFloat::opStatus St) {
2551   // In a constant context, assume that any dynamic rounding mode or FP
2552   // exception state matches the default floating-point environment.
2553   if (Info.InConstantContext)
2554     return true;
2555 
2556   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2557   if ((St & APFloat::opInexact) &&
2558       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2559     // Inexact result means that it depends on rounding mode. If the requested
2560     // mode is dynamic, the evaluation cannot be made in compile time.
2561     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2562     return false;
2563   }
2564 
2565   if ((St != APFloat::opOK) &&
2566       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2567        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2568        FPO.getAllowFEnvAccess())) {
2569     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2570     return false;
2571   }
2572 
2573   if ((St & APFloat::opStatus::opInvalidOp) &&
2574       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2575     // There is no usefully definable result.
2576     Info.FFDiag(E);
2577     return false;
2578   }
2579 
2580   // FIXME: if:
2581   // - evaluation triggered other FP exception, and
2582   // - exception mode is not "ignore", and
2583   // - the expression being evaluated is not a part of global variable
2584   //   initializer,
2585   // the evaluation probably need to be rejected.
2586   return true;
2587 }
2588 
HandleFloatToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,QualType DestType,APFloat & Result)2589 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2590                                    QualType SrcType, QualType DestType,
2591                                    APFloat &Result) {
2592   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2593   bool DynamicRM;
2594   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2595   APFloat::opStatus St;
2596   APFloat Value = Result;
2597   bool ignored;
2598   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2599   return checkFloatingPointResult(Info, E, St);
2600 }
2601 
HandleIntToIntCast(EvalInfo & Info,const Expr * E,QualType DestType,QualType SrcType,const APSInt & Value)2602 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2603                                  QualType DestType, QualType SrcType,
2604                                  const APSInt &Value) {
2605   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2606   // Figure out if this is a truncate, extend or noop cast.
2607   // If the input is signed, do a sign extend, noop, or truncate.
2608   APSInt Result = Value.extOrTrunc(DestWidth);
2609   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2610   if (DestType->isBooleanType())
2611     Result = Value.getBoolValue();
2612   return Result;
2613 }
2614 
HandleIntToFloatCast(EvalInfo & Info,const Expr * E,const FPOptions FPO,QualType SrcType,const APSInt & Value,QualType DestType,APFloat & Result)2615 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2616                                  const FPOptions FPO,
2617                                  QualType SrcType, const APSInt &Value,
2618                                  QualType DestType, APFloat &Result) {
2619   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2620   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2621        APFloat::rmNearestTiesToEven);
2622   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2623       FPO.isFPConstrained()) {
2624     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2625     return false;
2626   }
2627   return true;
2628 }
2629 
truncateBitfieldValue(EvalInfo & Info,const Expr * E,APValue & Value,const FieldDecl * FD)2630 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2631                                   APValue &Value, const FieldDecl *FD) {
2632   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2633 
2634   if (!Value.isInt()) {
2635     // Trying to store a pointer-cast-to-integer into a bitfield.
2636     // FIXME: In this case, we should provide the diagnostic for casting
2637     // a pointer to an integer.
2638     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2639     Info.FFDiag(E);
2640     return false;
2641   }
2642 
2643   APSInt &Int = Value.getInt();
2644   unsigned OldBitWidth = Int.getBitWidth();
2645   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2646   if (NewBitWidth < OldBitWidth)
2647     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2648   return true;
2649 }
2650 
EvalAndBitcastToAPInt(EvalInfo & Info,const Expr * E,llvm::APInt & Res)2651 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2652                                   llvm::APInt &Res) {
2653   APValue SVal;
2654   if (!Evaluate(SVal, Info, E))
2655     return false;
2656   if (SVal.isInt()) {
2657     Res = SVal.getInt();
2658     return true;
2659   }
2660   if (SVal.isFloat()) {
2661     Res = SVal.getFloat().bitcastToAPInt();
2662     return true;
2663   }
2664   if (SVal.isVector()) {
2665     QualType VecTy = E->getType();
2666     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2667     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2668     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2669     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2670     Res = llvm::APInt::getNullValue(VecSize);
2671     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2672       APValue &Elt = SVal.getVectorElt(i);
2673       llvm::APInt EltAsInt;
2674       if (Elt.isInt()) {
2675         EltAsInt = Elt.getInt();
2676       } else if (Elt.isFloat()) {
2677         EltAsInt = Elt.getFloat().bitcastToAPInt();
2678       } else {
2679         // Don't try to handle vectors of anything other than int or float
2680         // (not sure if it's possible to hit this case).
2681         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2682         return false;
2683       }
2684       unsigned BaseEltSize = EltAsInt.getBitWidth();
2685       if (BigEndian)
2686         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2687       else
2688         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2689     }
2690     return true;
2691   }
2692   // Give up if the input isn't an int, float, or vector.  For example, we
2693   // reject "(v4i16)(intptr_t)&a".
2694   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2695   return false;
2696 }
2697 
2698 /// Perform the given integer operation, which is known to need at most BitWidth
2699 /// bits, and check for overflow in the original type (if that type was not an
2700 /// unsigned type).
2701 template<typename Operation>
CheckedIntArithmetic(EvalInfo & Info,const Expr * E,const APSInt & LHS,const APSInt & RHS,unsigned BitWidth,Operation Op,APSInt & Result)2702 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2703                                  const APSInt &LHS, const APSInt &RHS,
2704                                  unsigned BitWidth, Operation Op,
2705                                  APSInt &Result) {
2706   if (LHS.isUnsigned()) {
2707     Result = Op(LHS, RHS);
2708     return true;
2709   }
2710 
2711   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2712   Result = Value.trunc(LHS.getBitWidth());
2713   if (Result.extend(BitWidth) != Value) {
2714     if (Info.checkingForUndefinedBehavior())
2715       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2716                                        diag::warn_integer_constant_overflow)
2717           << Result.toString(10) << E->getType();
2718     else
2719       return HandleOverflow(Info, E, Value, E->getType());
2720   }
2721   return true;
2722 }
2723 
2724 /// Perform the given binary integer operation.
handleIntIntBinOp(EvalInfo & Info,const Expr * E,const APSInt & LHS,BinaryOperatorKind Opcode,APSInt RHS,APSInt & Result)2725 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2726                               BinaryOperatorKind Opcode, APSInt RHS,
2727                               APSInt &Result) {
2728   switch (Opcode) {
2729   default:
2730     Info.FFDiag(E);
2731     return false;
2732   case BO_Mul:
2733     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2734                                 std::multiplies<APSInt>(), Result);
2735   case BO_Add:
2736     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2737                                 std::plus<APSInt>(), Result);
2738   case BO_Sub:
2739     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2740                                 std::minus<APSInt>(), Result);
2741   case BO_And: Result = LHS & RHS; return true;
2742   case BO_Xor: Result = LHS ^ RHS; return true;
2743   case BO_Or:  Result = LHS | RHS; return true;
2744   case BO_Div:
2745   case BO_Rem:
2746     if (RHS == 0) {
2747       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2748       return false;
2749     }
2750     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2751     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2752     // this operation and gives the two's complement result.
2753     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2754         LHS.isSigned() && LHS.isMinSignedValue())
2755       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2756                             E->getType());
2757     return true;
2758   case BO_Shl: {
2759     if (Info.getLangOpts().OpenCL)
2760       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2761       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2762                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2763                     RHS.isUnsigned());
2764     else if (RHS.isSigned() && RHS.isNegative()) {
2765       // During constant-folding, a negative shift is an opposite shift. Such
2766       // a shift is not a constant expression.
2767       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2768       RHS = -RHS;
2769       goto shift_right;
2770     }
2771   shift_left:
2772     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2773     // the shifted type.
2774     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2775     if (SA != RHS) {
2776       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2777         << RHS << E->getType() << LHS.getBitWidth();
2778     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2779       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2780       // operand, and must not overflow the corresponding unsigned type.
2781       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2782       // E1 x 2^E2 module 2^N.
2783       if (LHS.isNegative())
2784         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2785       else if (LHS.countLeadingZeros() < SA)
2786         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2787     }
2788     Result = LHS << SA;
2789     return true;
2790   }
2791   case BO_Shr: {
2792     if (Info.getLangOpts().OpenCL)
2793       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2794       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2795                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2796                     RHS.isUnsigned());
2797     else if (RHS.isSigned() && RHS.isNegative()) {
2798       // During constant-folding, a negative shift is an opposite shift. Such a
2799       // shift is not a constant expression.
2800       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2801       RHS = -RHS;
2802       goto shift_left;
2803     }
2804   shift_right:
2805     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2806     // shifted type.
2807     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2808     if (SA != RHS)
2809       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2810         << RHS << E->getType() << LHS.getBitWidth();
2811     Result = LHS >> SA;
2812     return true;
2813   }
2814 
2815   case BO_LT: Result = LHS < RHS; return true;
2816   case BO_GT: Result = LHS > RHS; return true;
2817   case BO_LE: Result = LHS <= RHS; return true;
2818   case BO_GE: Result = LHS >= RHS; return true;
2819   case BO_EQ: Result = LHS == RHS; return true;
2820   case BO_NE: Result = LHS != RHS; return true;
2821   case BO_Cmp:
2822     llvm_unreachable("BO_Cmp should be handled elsewhere");
2823   }
2824 }
2825 
2826 /// Perform the given binary floating-point operation, in-place, on LHS.
handleFloatFloatBinOp(EvalInfo & Info,const BinaryOperator * E,APFloat & LHS,BinaryOperatorKind Opcode,const APFloat & RHS)2827 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2828                                   APFloat &LHS, BinaryOperatorKind Opcode,
2829                                   const APFloat &RHS) {
2830   bool DynamicRM;
2831   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2832   APFloat::opStatus St;
2833   switch (Opcode) {
2834   default:
2835     Info.FFDiag(E);
2836     return false;
2837   case BO_Mul:
2838     St = LHS.multiply(RHS, RM);
2839     break;
2840   case BO_Add:
2841     St = LHS.add(RHS, RM);
2842     break;
2843   case BO_Sub:
2844     St = LHS.subtract(RHS, RM);
2845     break;
2846   case BO_Div:
2847     // [expr.mul]p4:
2848     //   If the second operand of / or % is zero the behavior is undefined.
2849     if (RHS.isZero())
2850       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2851     St = LHS.divide(RHS, RM);
2852     break;
2853   }
2854 
2855   // [expr.pre]p4:
2856   //   If during the evaluation of an expression, the result is not
2857   //   mathematically defined [...], the behavior is undefined.
2858   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2859   if (LHS.isNaN()) {
2860     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2861     return Info.noteUndefinedBehavior();
2862   }
2863 
2864   return checkFloatingPointResult(Info, E, St);
2865 }
2866 
handleLogicalOpForVector(const APInt & LHSValue,BinaryOperatorKind Opcode,const APInt & RHSValue,APInt & Result)2867 static bool handleLogicalOpForVector(const APInt &LHSValue,
2868                                      BinaryOperatorKind Opcode,
2869                                      const APInt &RHSValue, APInt &Result) {
2870   bool LHS = (LHSValue != 0);
2871   bool RHS = (RHSValue != 0);
2872 
2873   if (Opcode == BO_LAnd)
2874     Result = LHS && RHS;
2875   else
2876     Result = LHS || RHS;
2877   return true;
2878 }
handleLogicalOpForVector(const APFloat & LHSValue,BinaryOperatorKind Opcode,const APFloat & RHSValue,APInt & Result)2879 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2880                                      BinaryOperatorKind Opcode,
2881                                      const APFloat &RHSValue, APInt &Result) {
2882   bool LHS = !LHSValue.isZero();
2883   bool RHS = !RHSValue.isZero();
2884 
2885   if (Opcode == BO_LAnd)
2886     Result = LHS && RHS;
2887   else
2888     Result = LHS || RHS;
2889   return true;
2890 }
2891 
handleLogicalOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2892 static bool handleLogicalOpForVector(const APValue &LHSValue,
2893                                      BinaryOperatorKind Opcode,
2894                                      const APValue &RHSValue, APInt &Result) {
2895   // The result is always an int type, however operands match the first.
2896   if (LHSValue.getKind() == APValue::Int)
2897     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2898                                     RHSValue.getInt(), Result);
2899   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2900   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2901                                   RHSValue.getFloat(), Result);
2902 }
2903 
2904 template <typename APTy>
2905 static bool
handleCompareOpForVectorHelper(const APTy & LHSValue,BinaryOperatorKind Opcode,const APTy & RHSValue,APInt & Result)2906 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2907                                const APTy &RHSValue, APInt &Result) {
2908   switch (Opcode) {
2909   default:
2910     llvm_unreachable("unsupported binary operator");
2911   case BO_EQ:
2912     Result = (LHSValue == RHSValue);
2913     break;
2914   case BO_NE:
2915     Result = (LHSValue != RHSValue);
2916     break;
2917   case BO_LT:
2918     Result = (LHSValue < RHSValue);
2919     break;
2920   case BO_GT:
2921     Result = (LHSValue > RHSValue);
2922     break;
2923   case BO_LE:
2924     Result = (LHSValue <= RHSValue);
2925     break;
2926   case BO_GE:
2927     Result = (LHSValue >= RHSValue);
2928     break;
2929   }
2930 
2931   return true;
2932 }
2933 
handleCompareOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2934 static bool handleCompareOpForVector(const APValue &LHSValue,
2935                                      BinaryOperatorKind Opcode,
2936                                      const APValue &RHSValue, APInt &Result) {
2937   // The result is always an int type, however operands match the first.
2938   if (LHSValue.getKind() == APValue::Int)
2939     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2940                                           RHSValue.getInt(), Result);
2941   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2942   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2943                                         RHSValue.getFloat(), Result);
2944 }
2945 
2946 // Perform binary operations for vector types, in place on the LHS.
handleVectorVectorBinOp(EvalInfo & Info,const BinaryOperator * E,BinaryOperatorKind Opcode,APValue & LHSValue,const APValue & RHSValue)2947 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2948                                     BinaryOperatorKind Opcode,
2949                                     APValue &LHSValue,
2950                                     const APValue &RHSValue) {
2951   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2952          "Operation not supported on vector types");
2953 
2954   const auto *VT = E->getType()->castAs<VectorType>();
2955   unsigned NumElements = VT->getNumElements();
2956   QualType EltTy = VT->getElementType();
2957 
2958   // In the cases (typically C as I've observed) where we aren't evaluating
2959   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2960   // just give up.
2961   if (!LHSValue.isVector()) {
2962     assert(LHSValue.isLValue() &&
2963            "A vector result that isn't a vector OR uncalculated LValue");
2964     Info.FFDiag(E);
2965     return false;
2966   }
2967 
2968   assert(LHSValue.getVectorLength() == NumElements &&
2969          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2970 
2971   SmallVector<APValue, 4> ResultElements;
2972 
2973   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2974     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2975     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2976 
2977     if (EltTy->isIntegerType()) {
2978       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2979                        EltTy->isUnsignedIntegerType()};
2980       bool Success = true;
2981 
2982       if (BinaryOperator::isLogicalOp(Opcode))
2983         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2984       else if (BinaryOperator::isComparisonOp(Opcode))
2985         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2986       else
2987         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2988                                     RHSElt.getInt(), EltResult);
2989 
2990       if (!Success) {
2991         Info.FFDiag(E);
2992         return false;
2993       }
2994       ResultElements.emplace_back(EltResult);
2995 
2996     } else if (EltTy->isFloatingType()) {
2997       assert(LHSElt.getKind() == APValue::Float &&
2998              RHSElt.getKind() == APValue::Float &&
2999              "Mismatched LHS/RHS/Result Type");
3000       APFloat LHSFloat = LHSElt.getFloat();
3001 
3002       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3003                                  RHSElt.getFloat())) {
3004         Info.FFDiag(E);
3005         return false;
3006       }
3007 
3008       ResultElements.emplace_back(LHSFloat);
3009     }
3010   }
3011 
3012   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3013   return true;
3014 }
3015 
3016 /// Cast an lvalue referring to a base subobject to a derived class, by
3017 /// truncating the lvalue's path to the given length.
CastToDerivedClass(EvalInfo & Info,const Expr * E,LValue & Result,const RecordDecl * TruncatedType,unsigned TruncatedElements)3018 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3019                                const RecordDecl *TruncatedType,
3020                                unsigned TruncatedElements) {
3021   SubobjectDesignator &D = Result.Designator;
3022 
3023   // Check we actually point to a derived class object.
3024   if (TruncatedElements == D.Entries.size())
3025     return true;
3026   assert(TruncatedElements >= D.MostDerivedPathLength &&
3027          "not casting to a derived class");
3028   if (!Result.checkSubobject(Info, E, CSK_Derived))
3029     return false;
3030 
3031   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3032   const RecordDecl *RD = TruncatedType;
3033   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3034     if (RD->isInvalidDecl()) return false;
3035     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3036     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3037     if (isVirtualBaseClass(D.Entries[I]))
3038       Result.Offset -= Layout.getVBaseClassOffset(Base);
3039     else
3040       Result.Offset -= Layout.getBaseClassOffset(Base);
3041     RD = Base;
3042   }
3043   D.Entries.resize(TruncatedElements);
3044   return true;
3045 }
3046 
HandleLValueDirectBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,const ASTRecordLayout * RL=nullptr)3047 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3048                                    const CXXRecordDecl *Derived,
3049                                    const CXXRecordDecl *Base,
3050                                    const ASTRecordLayout *RL = nullptr) {
3051   if (!RL) {
3052     if (Derived->isInvalidDecl()) return false;
3053     RL = &Info.Ctx.getASTRecordLayout(Derived);
3054   }
3055 
3056   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3057   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3058   return true;
3059 }
3060 
HandleLValueBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * DerivedDecl,const CXXBaseSpecifier * Base)3061 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3062                              const CXXRecordDecl *DerivedDecl,
3063                              const CXXBaseSpecifier *Base) {
3064   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3065 
3066   if (!Base->isVirtual())
3067     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3068 
3069   SubobjectDesignator &D = Obj.Designator;
3070   if (D.Invalid)
3071     return false;
3072 
3073   // Extract most-derived object and corresponding type.
3074   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3075   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3076     return false;
3077 
3078   // Find the virtual base class.
3079   if (DerivedDecl->isInvalidDecl()) return false;
3080   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3081   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3082   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3083   return true;
3084 }
3085 
HandleLValueBasePath(EvalInfo & Info,const CastExpr * E,QualType Type,LValue & Result)3086 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3087                                  QualType Type, LValue &Result) {
3088   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3089                                      PathE = E->path_end();
3090        PathI != PathE; ++PathI) {
3091     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3092                           *PathI))
3093       return false;
3094     Type = (*PathI)->getType();
3095   }
3096   return true;
3097 }
3098 
3099 /// Cast an lvalue referring to a derived class to a known base subobject.
CastToBaseClass(EvalInfo & Info,const Expr * E,LValue & Result,const CXXRecordDecl * DerivedRD,const CXXRecordDecl * BaseRD)3100 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3101                             const CXXRecordDecl *DerivedRD,
3102                             const CXXRecordDecl *BaseRD) {
3103   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3104                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3105   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3106     llvm_unreachable("Class must be derived from the passed in base class!");
3107 
3108   for (CXXBasePathElement &Elem : Paths.front())
3109     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3110       return false;
3111   return true;
3112 }
3113 
3114 /// Update LVal to refer to the given field, which must be a member of the type
3115 /// currently described by LVal.
HandleLValueMember(EvalInfo & Info,const Expr * E,LValue & LVal,const FieldDecl * FD,const ASTRecordLayout * RL=nullptr)3116 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3117                                const FieldDecl *FD,
3118                                const ASTRecordLayout *RL = nullptr) {
3119   if (!RL) {
3120     if (FD->getParent()->isInvalidDecl()) return false;
3121     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3122   }
3123 
3124   unsigned I = FD->getFieldIndex();
3125   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3126   LVal.addDecl(Info, E, FD);
3127   return true;
3128 }
3129 
3130 /// Update LVal to refer to the given indirect field.
HandleLValueIndirectMember(EvalInfo & Info,const Expr * E,LValue & LVal,const IndirectFieldDecl * IFD)3131 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3132                                        LValue &LVal,
3133                                        const IndirectFieldDecl *IFD) {
3134   for (const auto *C : IFD->chain())
3135     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3136       return false;
3137   return true;
3138 }
3139 
3140 /// Get the size of the given type in char units.
HandleSizeof(EvalInfo & Info,SourceLocation Loc,QualType Type,CharUnits & Size)3141 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3142                          QualType Type, CharUnits &Size) {
3143   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3144   // extension.
3145   if (Type->isVoidType() || Type->isFunctionType()) {
3146     Size = CharUnits::One();
3147     return true;
3148   }
3149 
3150   if (Type->isDependentType()) {
3151     Info.FFDiag(Loc);
3152     return false;
3153   }
3154 
3155   if (!Type->isConstantSizeType()) {
3156     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3157     // FIXME: Better diagnostic.
3158     Info.FFDiag(Loc);
3159     return false;
3160   }
3161 
3162   Size = Info.Ctx.getTypeSizeInChars(Type);
3163   return true;
3164 }
3165 
3166 /// Update a pointer value to model pointer arithmetic.
3167 /// \param Info - Information about the ongoing evaluation.
3168 /// \param E - The expression being evaluated, for diagnostic purposes.
3169 /// \param LVal - The pointer value to be updated.
3170 /// \param EltTy - The pointee type represented by LVal.
3171 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,APSInt Adjustment)3172 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3173                                         LValue &LVal, QualType EltTy,
3174                                         APSInt Adjustment) {
3175   CharUnits SizeOfPointee;
3176   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3177     return false;
3178 
3179   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3180   return true;
3181 }
3182 
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,int64_t Adjustment)3183 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3184                                         LValue &LVal, QualType EltTy,
3185                                         int64_t Adjustment) {
3186   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3187                                      APSInt::get(Adjustment));
3188 }
3189 
3190 /// Update an lvalue to refer to a component of a complex number.
3191 /// \param Info - Information about the ongoing evaluation.
3192 /// \param LVal - The lvalue to be updated.
3193 /// \param EltTy - The complex number's component type.
3194 /// \param Imag - False for the real component, true for the imaginary.
HandleLValueComplexElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,bool Imag)3195 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3196                                        LValue &LVal, QualType EltTy,
3197                                        bool Imag) {
3198   if (Imag) {
3199     CharUnits SizeOfComponent;
3200     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3201       return false;
3202     LVal.Offset += SizeOfComponent;
3203   }
3204   LVal.addComplex(Info, E, EltTy, Imag);
3205   return true;
3206 }
3207 
3208 /// Try to evaluate the initializer for a variable declaration.
3209 ///
3210 /// \param Info   Information about the ongoing evaluation.
3211 /// \param E      An expression to be used when printing diagnostics.
3212 /// \param VD     The variable whose initializer should be obtained.
3213 /// \param Version The version of the variable within the frame.
3214 /// \param Frame  The frame in which the variable was created. Must be null
3215 ///               if this variable is not local to the evaluation.
3216 /// \param Result Filled in with a pointer to the value of the variable.
evaluateVarDeclInit(EvalInfo & Info,const Expr * E,const VarDecl * VD,CallStackFrame * Frame,unsigned Version,APValue * & Result)3217 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3218                                 const VarDecl *VD, CallStackFrame *Frame,
3219                                 unsigned Version, APValue *&Result) {
3220   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3221 
3222   // If this is a local variable, dig out its value.
3223   if (Frame) {
3224     Result = Frame->getTemporary(VD, Version);
3225     if (Result)
3226       return true;
3227 
3228     if (!isa<ParmVarDecl>(VD)) {
3229       // Assume variables referenced within a lambda's call operator that were
3230       // not declared within the call operator are captures and during checking
3231       // of a potential constant expression, assume they are unknown constant
3232       // expressions.
3233       assert(isLambdaCallOperator(Frame->Callee) &&
3234              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3235              "missing value for local variable");
3236       if (Info.checkingPotentialConstantExpression())
3237         return false;
3238       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3239       // still reachable at all?
3240       Info.FFDiag(E->getBeginLoc(),
3241                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3242           << "captures not currently allowed";
3243       return false;
3244     }
3245   }
3246 
3247   // If we're currently evaluating the initializer of this declaration, use that
3248   // in-flight value.
3249   if (Info.EvaluatingDecl == Base) {
3250     Result = Info.EvaluatingDeclValue;
3251     return true;
3252   }
3253 
3254   if (isa<ParmVarDecl>(VD)) {
3255     // Assume parameters of a potential constant expression are usable in
3256     // constant expressions.
3257     if (!Info.checkingPotentialConstantExpression() ||
3258         !Info.CurrentCall->Callee ||
3259         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3260       if (Info.getLangOpts().CPlusPlus11) {
3261         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3262             << VD;
3263         NoteLValueLocation(Info, Base);
3264       } else {
3265         Info.FFDiag(E);
3266       }
3267     }
3268     return false;
3269   }
3270 
3271   // Dig out the initializer, and use the declaration which it's attached to.
3272   // FIXME: We should eventually check whether the variable has a reachable
3273   // initializing declaration.
3274   const Expr *Init = VD->getAnyInitializer(VD);
3275   if (!Init) {
3276     // Don't diagnose during potential constant expression checking; an
3277     // initializer might be added later.
3278     if (!Info.checkingPotentialConstantExpression()) {
3279       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3280         << VD;
3281       NoteLValueLocation(Info, Base);
3282     }
3283     return false;
3284   }
3285 
3286   if (Init->isValueDependent()) {
3287     // The DeclRefExpr is not value-dependent, but the variable it refers to
3288     // has a value-dependent initializer. This should only happen in
3289     // constant-folding cases, where the variable is not actually of a suitable
3290     // type for use in a constant expression (otherwise the DeclRefExpr would
3291     // have been value-dependent too), so diagnose that.
3292     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3293     if (!Info.checkingPotentialConstantExpression()) {
3294       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3295                          ? diag::note_constexpr_ltor_non_constexpr
3296                          : diag::note_constexpr_ltor_non_integral, 1)
3297           << VD << VD->getType();
3298       NoteLValueLocation(Info, Base);
3299     }
3300     return false;
3301   }
3302 
3303   // Check that we can fold the initializer. In C++, we will have already done
3304   // this in the cases where it matters for conformance.
3305   if (!VD->evaluateValue()) {
3306     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3307     NoteLValueLocation(Info, Base);
3308     return false;
3309   }
3310 
3311   // Check that the variable is actually usable in constant expressions. For a
3312   // const integral variable or a reference, we might have a non-constant
3313   // initializer that we can nonetheless evaluate the initializer for. Such
3314   // variables are not usable in constant expressions. In C++98, the
3315   // initializer also syntactically needs to be an ICE.
3316   //
3317   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3318   // expressions here; doing so would regress diagnostics for things like
3319   // reading from a volatile constexpr variable.
3320   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3321        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3322       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3323        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3324     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3325     NoteLValueLocation(Info, Base);
3326   }
3327 
3328   // Never use the initializer of a weak variable, not even for constant
3329   // folding. We can't be sure that this is the definition that will be used.
3330   if (VD->isWeak()) {
3331     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3332     NoteLValueLocation(Info, Base);
3333     return false;
3334   }
3335 
3336   Result = VD->getEvaluatedValue();
3337   return true;
3338 }
3339 
3340 /// Get the base index of the given base class within an APValue representing
3341 /// the given derived class.
getBaseIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)3342 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3343                              const CXXRecordDecl *Base) {
3344   Base = Base->getCanonicalDecl();
3345   unsigned Index = 0;
3346   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3347          E = Derived->bases_end(); I != E; ++I, ++Index) {
3348     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3349       return Index;
3350   }
3351 
3352   llvm_unreachable("base class missing from derived class's bases list");
3353 }
3354 
3355 /// Extract the value of a character from a string literal.
extractStringLiteralCharacter(EvalInfo & Info,const Expr * Lit,uint64_t Index)3356 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3357                                             uint64_t Index) {
3358   assert(!isa<SourceLocExpr>(Lit) &&
3359          "SourceLocExpr should have already been converted to a StringLiteral");
3360 
3361   // FIXME: Support MakeStringConstant
3362   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3363     std::string Str;
3364     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3365     assert(Index <= Str.size() && "Index too large");
3366     return APSInt::getUnsigned(Str.c_str()[Index]);
3367   }
3368 
3369   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3370     Lit = PE->getFunctionName();
3371   const StringLiteral *S = cast<StringLiteral>(Lit);
3372   const ConstantArrayType *CAT =
3373       Info.Ctx.getAsConstantArrayType(S->getType());
3374   assert(CAT && "string literal isn't an array");
3375   QualType CharType = CAT->getElementType();
3376   assert(CharType->isIntegerType() && "unexpected character type");
3377 
3378   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3379                CharType->isUnsignedIntegerType());
3380   if (Index < S->getLength())
3381     Value = S->getCodeUnit(Index);
3382   return Value;
3383 }
3384 
3385 // Expand a string literal into an array of characters.
3386 //
3387 // FIXME: This is inefficient; we should probably introduce something similar
3388 // to the LLVM ConstantDataArray to make this cheaper.
expandStringLiteral(EvalInfo & Info,const StringLiteral * S,APValue & Result,QualType AllocType=QualType ())3389 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3390                                 APValue &Result,
3391                                 QualType AllocType = QualType()) {
3392   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3393       AllocType.isNull() ? S->getType() : AllocType);
3394   assert(CAT && "string literal isn't an array");
3395   QualType CharType = CAT->getElementType();
3396   assert(CharType->isIntegerType() && "unexpected character type");
3397 
3398   unsigned Elts = CAT->getSize().getZExtValue();
3399   Result = APValue(APValue::UninitArray(),
3400                    std::min(S->getLength(), Elts), Elts);
3401   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3402                CharType->isUnsignedIntegerType());
3403   if (Result.hasArrayFiller())
3404     Result.getArrayFiller() = APValue(Value);
3405   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3406     Value = S->getCodeUnit(I);
3407     Result.getArrayInitializedElt(I) = APValue(Value);
3408   }
3409 }
3410 
3411 // Expand an array so that it has more than Index filled elements.
expandArray(APValue & Array,unsigned Index)3412 static void expandArray(APValue &Array, unsigned Index) {
3413   unsigned Size = Array.getArraySize();
3414   assert(Index < Size);
3415 
3416   // Always at least double the number of elements for which we store a value.
3417   unsigned OldElts = Array.getArrayInitializedElts();
3418   unsigned NewElts = std::max(Index+1, OldElts * 2);
3419   NewElts = std::min(Size, std::max(NewElts, 8u));
3420 
3421   // Copy the data across.
3422   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3423   for (unsigned I = 0; I != OldElts; ++I)
3424     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3425   for (unsigned I = OldElts; I != NewElts; ++I)
3426     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3427   if (NewValue.hasArrayFiller())
3428     NewValue.getArrayFiller() = Array.getArrayFiller();
3429   Array.swap(NewValue);
3430 }
3431 
3432 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3433 /// conversion. If it's of class type, we may assume that the copy operation
3434 /// is trivial. Note that this is never true for a union type with fields
3435 /// (because the copy always "reads" the active member) and always true for
3436 /// a non-class type.
3437 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
isReadByLvalueToRvalueConversion(QualType T)3438 static bool isReadByLvalueToRvalueConversion(QualType T) {
3439   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3440   return !RD || isReadByLvalueToRvalueConversion(RD);
3441 }
isReadByLvalueToRvalueConversion(const CXXRecordDecl * RD)3442 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3443   // FIXME: A trivial copy of a union copies the object representation, even if
3444   // the union is empty.
3445   if (RD->isUnion())
3446     return !RD->field_empty();
3447   if (RD->isEmpty())
3448     return false;
3449 
3450   for (auto *Field : RD->fields())
3451     if (!Field->isUnnamedBitfield() &&
3452         isReadByLvalueToRvalueConversion(Field->getType()))
3453       return true;
3454 
3455   for (auto &BaseSpec : RD->bases())
3456     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3457       return true;
3458 
3459   return false;
3460 }
3461 
3462 /// Diagnose an attempt to read from any unreadable field within the specified
3463 /// type, which might be a class type.
diagnoseMutableFields(EvalInfo & Info,const Expr * E,AccessKinds AK,QualType T)3464 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3465                                   QualType T) {
3466   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3467   if (!RD)
3468     return false;
3469 
3470   if (!RD->hasMutableFields())
3471     return false;
3472 
3473   for (auto *Field : RD->fields()) {
3474     // If we're actually going to read this field in some way, then it can't
3475     // be mutable. If we're in a union, then assigning to a mutable field
3476     // (even an empty one) can change the active member, so that's not OK.
3477     // FIXME: Add core issue number for the union case.
3478     if (Field->isMutable() &&
3479         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3480       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3481       Info.Note(Field->getLocation(), diag::note_declared_at);
3482       return true;
3483     }
3484 
3485     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3486       return true;
3487   }
3488 
3489   for (auto &BaseSpec : RD->bases())
3490     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3491       return true;
3492 
3493   // All mutable fields were empty, and thus not actually read.
3494   return false;
3495 }
3496 
lifetimeStartedInEvaluation(EvalInfo & Info,APValue::LValueBase Base,bool MutableSubobject=false)3497 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3498                                         APValue::LValueBase Base,
3499                                         bool MutableSubobject = false) {
3500   // A temporary or transient heap allocation we created.
3501   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3502     return true;
3503 
3504   switch (Info.IsEvaluatingDecl) {
3505   case EvalInfo::EvaluatingDeclKind::None:
3506     return false;
3507 
3508   case EvalInfo::EvaluatingDeclKind::Ctor:
3509     // The variable whose initializer we're evaluating.
3510     if (Info.EvaluatingDecl == Base)
3511       return true;
3512 
3513     // A temporary lifetime-extended by the variable whose initializer we're
3514     // evaluating.
3515     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3516       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3517         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3518     return false;
3519 
3520   case EvalInfo::EvaluatingDeclKind::Dtor:
3521     // C++2a [expr.const]p6:
3522     //   [during constant destruction] the lifetime of a and its non-mutable
3523     //   subobjects (but not its mutable subobjects) [are] considered to start
3524     //   within e.
3525     if (MutableSubobject || Base != Info.EvaluatingDecl)
3526       return false;
3527     // FIXME: We can meaningfully extend this to cover non-const objects, but
3528     // we will need special handling: we should be able to access only
3529     // subobjects of such objects that are themselves declared const.
3530     QualType T = getType(Base);
3531     return T.isConstQualified() || T->isReferenceType();
3532   }
3533 
3534   llvm_unreachable("unknown evaluating decl kind");
3535 }
3536 
3537 namespace {
3538 /// A handle to a complete object (an object that is not a subobject of
3539 /// another object).
3540 struct CompleteObject {
3541   /// The identity of the object.
3542   APValue::LValueBase Base;
3543   /// The value of the complete object.
3544   APValue *Value;
3545   /// The type of the complete object.
3546   QualType Type;
3547 
CompleteObject__anone93968c60911::CompleteObject3548   CompleteObject() : Value(nullptr) {}
CompleteObject__anone93968c60911::CompleteObject3549   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3550       : Base(Base), Value(Value), Type(Type) {}
3551 
mayAccessMutableMembers__anone93968c60911::CompleteObject3552   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3553     // If this isn't a "real" access (eg, if it's just accessing the type
3554     // info), allow it. We assume the type doesn't change dynamically for
3555     // subobjects of constexpr objects (even though we'd hit UB here if it
3556     // did). FIXME: Is this right?
3557     if (!isAnyAccess(AK))
3558       return true;
3559 
3560     // In C++14 onwards, it is permitted to read a mutable member whose
3561     // lifetime began within the evaluation.
3562     // FIXME: Should we also allow this in C++11?
3563     if (!Info.getLangOpts().CPlusPlus14)
3564       return false;
3565     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3566   }
3567 
operator bool__anone93968c60911::CompleteObject3568   explicit operator bool() const { return !Type.isNull(); }
3569 };
3570 } // end anonymous namespace
3571 
getSubobjectType(QualType ObjType,QualType SubobjType,bool IsMutable=false)3572 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3573                                  bool IsMutable = false) {
3574   // C++ [basic.type.qualifier]p1:
3575   // - A const object is an object of type const T or a non-mutable subobject
3576   //   of a const object.
3577   if (ObjType.isConstQualified() && !IsMutable)
3578     SubobjType.addConst();
3579   // - A volatile object is an object of type const T or a subobject of a
3580   //   volatile object.
3581   if (ObjType.isVolatileQualified())
3582     SubobjType.addVolatile();
3583   return SubobjType;
3584 }
3585 
3586 /// Find the designated sub-object of an rvalue.
3587 template<typename SubobjectHandler>
3588 typename SubobjectHandler::result_type
findSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,SubobjectHandler & handler)3589 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3590               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3591   if (Sub.Invalid)
3592     // A diagnostic will have already been produced.
3593     return handler.failed();
3594   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3595     if (Info.getLangOpts().CPlusPlus11)
3596       Info.FFDiag(E, Sub.isOnePastTheEnd()
3597                          ? diag::note_constexpr_access_past_end
3598                          : diag::note_constexpr_access_unsized_array)
3599           << handler.AccessKind;
3600     else
3601       Info.FFDiag(E);
3602     return handler.failed();
3603   }
3604 
3605   APValue *O = Obj.Value;
3606   QualType ObjType = Obj.Type;
3607   const FieldDecl *LastField = nullptr;
3608   const FieldDecl *VolatileField = nullptr;
3609 
3610   // Walk the designator's path to find the subobject.
3611   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3612     // Reading an indeterminate value is undefined, but assigning over one is OK.
3613     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3614         (O->isIndeterminate() &&
3615          !isValidIndeterminateAccess(handler.AccessKind))) {
3616       if (!Info.checkingPotentialConstantExpression())
3617         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3618             << handler.AccessKind << O->isIndeterminate();
3619       return handler.failed();
3620     }
3621 
3622     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3623     //    const and volatile semantics are not applied on an object under
3624     //    {con,de}struction.
3625     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3626         ObjType->isRecordType() &&
3627         Info.isEvaluatingCtorDtor(
3628             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3629                                          Sub.Entries.begin() + I)) !=
3630                           ConstructionPhase::None) {
3631       ObjType = Info.Ctx.getCanonicalType(ObjType);
3632       ObjType.removeLocalConst();
3633       ObjType.removeLocalVolatile();
3634     }
3635 
3636     // If this is our last pass, check that the final object type is OK.
3637     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3638       // Accesses to volatile objects are prohibited.
3639       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3640         if (Info.getLangOpts().CPlusPlus) {
3641           int DiagKind;
3642           SourceLocation Loc;
3643           const NamedDecl *Decl = nullptr;
3644           if (VolatileField) {
3645             DiagKind = 2;
3646             Loc = VolatileField->getLocation();
3647             Decl = VolatileField;
3648           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3649             DiagKind = 1;
3650             Loc = VD->getLocation();
3651             Decl = VD;
3652           } else {
3653             DiagKind = 0;
3654             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3655               Loc = E->getExprLoc();
3656           }
3657           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3658               << handler.AccessKind << DiagKind << Decl;
3659           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3660         } else {
3661           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3662         }
3663         return handler.failed();
3664       }
3665 
3666       // If we are reading an object of class type, there may still be more
3667       // things we need to check: if there are any mutable subobjects, we
3668       // cannot perform this read. (This only happens when performing a trivial
3669       // copy or assignment.)
3670       if (ObjType->isRecordType() &&
3671           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3672           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3673         return handler.failed();
3674     }
3675 
3676     if (I == N) {
3677       if (!handler.found(*O, ObjType))
3678         return false;
3679 
3680       // If we modified a bit-field, truncate it to the right width.
3681       if (isModification(handler.AccessKind) &&
3682           LastField && LastField->isBitField() &&
3683           !truncateBitfieldValue(Info, E, *O, LastField))
3684         return false;
3685 
3686       return true;
3687     }
3688 
3689     LastField = nullptr;
3690     if (ObjType->isArrayType()) {
3691       // Next subobject is an array element.
3692       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3693       assert(CAT && "vla in literal type?");
3694       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3695       if (CAT->getSize().ule(Index)) {
3696         // Note, it should not be possible to form a pointer with a valid
3697         // designator which points more than one past the end of the array.
3698         if (Info.getLangOpts().CPlusPlus11)
3699           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3700             << handler.AccessKind;
3701         else
3702           Info.FFDiag(E);
3703         return handler.failed();
3704       }
3705 
3706       ObjType = CAT->getElementType();
3707 
3708       if (O->getArrayInitializedElts() > Index)
3709         O = &O->getArrayInitializedElt(Index);
3710       else if (!isRead(handler.AccessKind)) {
3711         expandArray(*O, Index);
3712         O = &O->getArrayInitializedElt(Index);
3713       } else
3714         O = &O->getArrayFiller();
3715     } else if (ObjType->isAnyComplexType()) {
3716       // Next subobject is a complex number.
3717       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3718       if (Index > 1) {
3719         if (Info.getLangOpts().CPlusPlus11)
3720           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3721             << handler.AccessKind;
3722         else
3723           Info.FFDiag(E);
3724         return handler.failed();
3725       }
3726 
3727       ObjType = getSubobjectType(
3728           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3729 
3730       assert(I == N - 1 && "extracting subobject of scalar?");
3731       if (O->isComplexInt()) {
3732         return handler.found(Index ? O->getComplexIntImag()
3733                                    : O->getComplexIntReal(), ObjType);
3734       } else {
3735         assert(O->isComplexFloat());
3736         return handler.found(Index ? O->getComplexFloatImag()
3737                                    : O->getComplexFloatReal(), ObjType);
3738       }
3739     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3740       if (Field->isMutable() &&
3741           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3742         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3743           << handler.AccessKind << Field;
3744         Info.Note(Field->getLocation(), diag::note_declared_at);
3745         return handler.failed();
3746       }
3747 
3748       // Next subobject is a class, struct or union field.
3749       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3750       if (RD->isUnion()) {
3751         const FieldDecl *UnionField = O->getUnionField();
3752         if (!UnionField ||
3753             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3754           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3755             // Placement new onto an inactive union member makes it active.
3756             O->setUnion(Field, APValue());
3757           } else {
3758             // FIXME: If O->getUnionValue() is absent, report that there's no
3759             // active union member rather than reporting the prior active union
3760             // member. We'll need to fix nullptr_t to not use APValue() as its
3761             // representation first.
3762             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3763                 << handler.AccessKind << Field << !UnionField << UnionField;
3764             return handler.failed();
3765           }
3766         }
3767         O = &O->getUnionValue();
3768       } else
3769         O = &O->getStructField(Field->getFieldIndex());
3770 
3771       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3772       LastField = Field;
3773       if (Field->getType().isVolatileQualified())
3774         VolatileField = Field;
3775     } else {
3776       // Next subobject is a base class.
3777       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3778       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3779       O = &O->getStructBase(getBaseIndex(Derived, Base));
3780 
3781       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3782     }
3783   }
3784 }
3785 
3786 namespace {
3787 struct ExtractSubobjectHandler {
3788   EvalInfo &Info;
3789   const Expr *E;
3790   APValue &Result;
3791   const AccessKinds AccessKind;
3792 
3793   typedef bool result_type;
failed__anone93968c60a11::ExtractSubobjectHandler3794   bool failed() { return false; }
found__anone93968c60a11::ExtractSubobjectHandler3795   bool found(APValue &Subobj, QualType SubobjType) {
3796     Result = Subobj;
3797     if (AccessKind == AK_ReadObjectRepresentation)
3798       return true;
3799     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3800   }
found__anone93968c60a11::ExtractSubobjectHandler3801   bool found(APSInt &Value, QualType SubobjType) {
3802     Result = APValue(Value);
3803     return true;
3804   }
found__anone93968c60a11::ExtractSubobjectHandler3805   bool found(APFloat &Value, QualType SubobjType) {
3806     Result = APValue(Value);
3807     return true;
3808   }
3809 };
3810 } // end anonymous namespace
3811 
3812 /// Extract the designated sub-object of an rvalue.
extractSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & Result,AccessKinds AK=AK_Read)3813 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3814                              const CompleteObject &Obj,
3815                              const SubobjectDesignator &Sub, APValue &Result,
3816                              AccessKinds AK = AK_Read) {
3817   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3818   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3819   return findSubobject(Info, E, Obj, Sub, Handler);
3820 }
3821 
3822 namespace {
3823 struct ModifySubobjectHandler {
3824   EvalInfo &Info;
3825   APValue &NewVal;
3826   const Expr *E;
3827 
3828   typedef bool result_type;
3829   static const AccessKinds AccessKind = AK_Assign;
3830 
checkConst__anone93968c60b11::ModifySubobjectHandler3831   bool checkConst(QualType QT) {
3832     // Assigning to a const object has undefined behavior.
3833     if (QT.isConstQualified()) {
3834       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3835       return false;
3836     }
3837     return true;
3838   }
3839 
failed__anone93968c60b11::ModifySubobjectHandler3840   bool failed() { return false; }
found__anone93968c60b11::ModifySubobjectHandler3841   bool found(APValue &Subobj, QualType SubobjType) {
3842     if (!checkConst(SubobjType))
3843       return false;
3844     // We've been given ownership of NewVal, so just swap it in.
3845     Subobj.swap(NewVal);
3846     return true;
3847   }
found__anone93968c60b11::ModifySubobjectHandler3848   bool found(APSInt &Value, QualType SubobjType) {
3849     if (!checkConst(SubobjType))
3850       return false;
3851     if (!NewVal.isInt()) {
3852       // Maybe trying to write a cast pointer value into a complex?
3853       Info.FFDiag(E);
3854       return false;
3855     }
3856     Value = NewVal.getInt();
3857     return true;
3858   }
found__anone93968c60b11::ModifySubobjectHandler3859   bool found(APFloat &Value, QualType SubobjType) {
3860     if (!checkConst(SubobjType))
3861       return false;
3862     Value = NewVal.getFloat();
3863     return true;
3864   }
3865 };
3866 } // end anonymous namespace
3867 
3868 const AccessKinds ModifySubobjectHandler::AccessKind;
3869 
3870 /// Update the designated sub-object of an rvalue to the given value.
modifySubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & NewVal)3871 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3872                             const CompleteObject &Obj,
3873                             const SubobjectDesignator &Sub,
3874                             APValue &NewVal) {
3875   ModifySubobjectHandler Handler = { Info, NewVal, E };
3876   return findSubobject(Info, E, Obj, Sub, Handler);
3877 }
3878 
3879 /// Find the position where two subobject designators diverge, or equivalently
3880 /// the length of the common initial subsequence.
FindDesignatorMismatch(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B,bool & WasArrayIndex)3881 static unsigned FindDesignatorMismatch(QualType ObjType,
3882                                        const SubobjectDesignator &A,
3883                                        const SubobjectDesignator &B,
3884                                        bool &WasArrayIndex) {
3885   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3886   for (/**/; I != N; ++I) {
3887     if (!ObjType.isNull() &&
3888         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3889       // Next subobject is an array element.
3890       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3891         WasArrayIndex = true;
3892         return I;
3893       }
3894       if (ObjType->isAnyComplexType())
3895         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3896       else
3897         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3898     } else {
3899       if (A.Entries[I].getAsBaseOrMember() !=
3900           B.Entries[I].getAsBaseOrMember()) {
3901         WasArrayIndex = false;
3902         return I;
3903       }
3904       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3905         // Next subobject is a field.
3906         ObjType = FD->getType();
3907       else
3908         // Next subobject is a base class.
3909         ObjType = QualType();
3910     }
3911   }
3912   WasArrayIndex = false;
3913   return I;
3914 }
3915 
3916 /// Determine whether the given subobject designators refer to elements of the
3917 /// same array object.
AreElementsOfSameArray(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B)3918 static bool AreElementsOfSameArray(QualType ObjType,
3919                                    const SubobjectDesignator &A,
3920                                    const SubobjectDesignator &B) {
3921   if (A.Entries.size() != B.Entries.size())
3922     return false;
3923 
3924   bool IsArray = A.MostDerivedIsArrayElement;
3925   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3926     // A is a subobject of the array element.
3927     return false;
3928 
3929   // If A (and B) designates an array element, the last entry will be the array
3930   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3931   // of length 1' case, and the entire path must match.
3932   bool WasArrayIndex;
3933   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3934   return CommonLength >= A.Entries.size() - IsArray;
3935 }
3936 
3937 /// Find the complete object to which an LValue refers.
findCompleteObject(EvalInfo & Info,const Expr * E,AccessKinds AK,const LValue & LVal,QualType LValType)3938 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3939                                          AccessKinds AK, const LValue &LVal,
3940                                          QualType LValType) {
3941   if (LVal.InvalidBase) {
3942     Info.FFDiag(E);
3943     return CompleteObject();
3944   }
3945 
3946   if (!LVal.Base) {
3947     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3948     return CompleteObject();
3949   }
3950 
3951   CallStackFrame *Frame = nullptr;
3952   unsigned Depth = 0;
3953   if (LVal.getLValueCallIndex()) {
3954     std::tie(Frame, Depth) =
3955         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3956     if (!Frame) {
3957       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3958         << AK << LVal.Base.is<const ValueDecl*>();
3959       NoteLValueLocation(Info, LVal.Base);
3960       return CompleteObject();
3961     }
3962   }
3963 
3964   bool IsAccess = isAnyAccess(AK);
3965 
3966   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3967   // is not a constant expression (even if the object is non-volatile). We also
3968   // apply this rule to C++98, in order to conform to the expected 'volatile'
3969   // semantics.
3970   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3971     if (Info.getLangOpts().CPlusPlus)
3972       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3973         << AK << LValType;
3974     else
3975       Info.FFDiag(E);
3976     return CompleteObject();
3977   }
3978 
3979   // Compute value storage location and type of base object.
3980   APValue *BaseVal = nullptr;
3981   QualType BaseType = getType(LVal.Base);
3982 
3983   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3984       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3985     // This is the object whose initializer we're evaluating, so its lifetime
3986     // started in the current evaluation.
3987     BaseVal = Info.EvaluatingDeclValue;
3988   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3989     // Allow reading from a GUID declaration.
3990     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3991       if (isModification(AK)) {
3992         // All the remaining cases do not permit modification of the object.
3993         Info.FFDiag(E, diag::note_constexpr_modify_global);
3994         return CompleteObject();
3995       }
3996       APValue &V = GD->getAsAPValue();
3997       if (V.isAbsent()) {
3998         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3999             << GD->getType();
4000         return CompleteObject();
4001       }
4002       return CompleteObject(LVal.Base, &V, GD->getType());
4003     }
4004 
4005     // Allow reading from template parameter objects.
4006     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4007       if (isModification(AK)) {
4008         Info.FFDiag(E, diag::note_constexpr_modify_global);
4009         return CompleteObject();
4010       }
4011       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4012                             TPO->getType());
4013     }
4014 
4015     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4016     // In C++11, constexpr, non-volatile variables initialized with constant
4017     // expressions are constant expressions too. Inside constexpr functions,
4018     // parameters are constant expressions even if they're non-const.
4019     // In C++1y, objects local to a constant expression (those with a Frame) are
4020     // both readable and writable inside constant expressions.
4021     // In C, such things can also be folded, although they are not ICEs.
4022     const VarDecl *VD = dyn_cast<VarDecl>(D);
4023     if (VD) {
4024       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4025         VD = VDef;
4026     }
4027     if (!VD || VD->isInvalidDecl()) {
4028       Info.FFDiag(E);
4029       return CompleteObject();
4030     }
4031 
4032     bool IsConstant = BaseType.isConstant(Info.Ctx);
4033 
4034     // Unless we're looking at a local variable or argument in a constexpr call,
4035     // the variable we're reading must be const.
4036     if (!Frame) {
4037       if (IsAccess && isa<ParmVarDecl>(VD)) {
4038         // Access of a parameter that's not associated with a frame isn't going
4039         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4040         // suitable diagnostic.
4041       } else if (Info.getLangOpts().CPlusPlus14 &&
4042                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4043         // OK, we can read and modify an object if we're in the process of
4044         // evaluating its initializer, because its lifetime began in this
4045         // evaluation.
4046       } else if (isModification(AK)) {
4047         // All the remaining cases do not permit modification of the object.
4048         Info.FFDiag(E, diag::note_constexpr_modify_global);
4049         return CompleteObject();
4050       } else if (VD->isConstexpr()) {
4051         // OK, we can read this variable.
4052       } else if (BaseType->isIntegralOrEnumerationType()) {
4053         if (!IsConstant) {
4054           if (!IsAccess)
4055             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4056           if (Info.getLangOpts().CPlusPlus) {
4057             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4058             Info.Note(VD->getLocation(), diag::note_declared_at);
4059           } else {
4060             Info.FFDiag(E);
4061           }
4062           return CompleteObject();
4063         }
4064       } else if (!IsAccess) {
4065         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4066       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4067                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4068         // This variable might end up being constexpr. Don't diagnose it yet.
4069       } else if (IsConstant) {
4070         // Keep evaluating to see what we can do. In particular, we support
4071         // folding of const floating-point types, in order to make static const
4072         // data members of such types (supported as an extension) more useful.
4073         if (Info.getLangOpts().CPlusPlus) {
4074           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4075                               ? diag::note_constexpr_ltor_non_constexpr
4076                               : diag::note_constexpr_ltor_non_integral, 1)
4077               << VD << BaseType;
4078           Info.Note(VD->getLocation(), diag::note_declared_at);
4079         } else {
4080           Info.CCEDiag(E);
4081         }
4082       } else {
4083         // Never allow reading a non-const value.
4084         if (Info.getLangOpts().CPlusPlus) {
4085           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4086                              ? diag::note_constexpr_ltor_non_constexpr
4087                              : diag::note_constexpr_ltor_non_integral, 1)
4088               << VD << BaseType;
4089           Info.Note(VD->getLocation(), diag::note_declared_at);
4090         } else {
4091           Info.FFDiag(E);
4092         }
4093         return CompleteObject();
4094       }
4095     }
4096 
4097     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4098       return CompleteObject();
4099   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4100     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4101     if (!Alloc) {
4102       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4103       return CompleteObject();
4104     }
4105     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4106                           LVal.Base.getDynamicAllocType());
4107   } else {
4108     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4109 
4110     if (!Frame) {
4111       if (const MaterializeTemporaryExpr *MTE =
4112               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4113         assert(MTE->getStorageDuration() == SD_Static &&
4114                "should have a frame for a non-global materialized temporary");
4115 
4116         // C++20 [expr.const]p4: [DR2126]
4117         //   An object or reference is usable in constant expressions if it is
4118         //   - a temporary object of non-volatile const-qualified literal type
4119         //     whose lifetime is extended to that of a variable that is usable
4120         //     in constant expressions
4121         //
4122         // C++20 [expr.const]p5:
4123         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4124         //   - a non-volatile glvalue that refers to an object that is usable
4125         //     in constant expressions, or
4126         //   - a non-volatile glvalue of literal type that refers to a
4127         //     non-volatile object whose lifetime began within the evaluation
4128         //     of E;
4129         //
4130         // C++11 misses the 'began within the evaluation of e' check and
4131         // instead allows all temporaries, including things like:
4132         //   int &&r = 1;
4133         //   int x = ++r;
4134         //   constexpr int k = r;
4135         // Therefore we use the C++14-onwards rules in C++11 too.
4136         //
4137         // Note that temporaries whose lifetimes began while evaluating a
4138         // variable's constructor are not usable while evaluating the
4139         // corresponding destructor, not even if they're of const-qualified
4140         // types.
4141         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4142             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4143           if (!IsAccess)
4144             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4145           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4146           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4147           return CompleteObject();
4148         }
4149 
4150         BaseVal = MTE->getOrCreateValue(false);
4151         assert(BaseVal && "got reference to unevaluated temporary");
4152       } else {
4153         if (!IsAccess)
4154           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4155         APValue Val;
4156         LVal.moveInto(Val);
4157         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4158             << AK
4159             << Val.getAsString(Info.Ctx,
4160                                Info.Ctx.getLValueReferenceType(LValType));
4161         NoteLValueLocation(Info, LVal.Base);
4162         return CompleteObject();
4163       }
4164     } else {
4165       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4166       assert(BaseVal && "missing value for temporary");
4167     }
4168   }
4169 
4170   // In C++14, we can't safely access any mutable state when we might be
4171   // evaluating after an unmodeled side effect. Parameters are modeled as state
4172   // in the caller, but aren't visible once the call returns, so they can be
4173   // modified in a speculatively-evaluated call.
4174   //
4175   // FIXME: Not all local state is mutable. Allow local constant subobjects
4176   // to be read here (but take care with 'mutable' fields).
4177   unsigned VisibleDepth = Depth;
4178   if (llvm::isa_and_nonnull<ParmVarDecl>(
4179           LVal.Base.dyn_cast<const ValueDecl *>()))
4180     ++VisibleDepth;
4181   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4182        Info.EvalStatus.HasSideEffects) ||
4183       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4184     return CompleteObject();
4185 
4186   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4187 }
4188 
4189 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4190 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4191 /// glvalue referred to by an entity of reference type.
4192 ///
4193 /// \param Info - Information about the ongoing evaluation.
4194 /// \param Conv - The expression for which we are performing the conversion.
4195 ///               Used for diagnostics.
4196 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4197 ///               case of a non-class type).
4198 /// \param LVal - The glvalue on which we are attempting to perform this action.
4199 /// \param RVal - The produced value will be placed here.
4200 /// \param WantObjectRepresentation - If true, we're looking for the object
4201 ///               representation rather than the value, and in particular,
4202 ///               there is no requirement that the result be fully initialized.
4203 static bool
handleLValueToRValueConversion(EvalInfo & Info,const Expr * Conv,QualType Type,const LValue & LVal,APValue & RVal,bool WantObjectRepresentation=false)4204 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4205                                const LValue &LVal, APValue &RVal,
4206                                bool WantObjectRepresentation = false) {
4207   if (LVal.Designator.Invalid)
4208     return false;
4209 
4210   // Check for special cases where there is no existing APValue to look at.
4211   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4212 
4213   AccessKinds AK =
4214       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4215 
4216   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4217     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4218       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4219       // initializer until now for such expressions. Such an expression can't be
4220       // an ICE in C, so this only matters for fold.
4221       if (Type.isVolatileQualified()) {
4222         Info.FFDiag(Conv);
4223         return false;
4224       }
4225       APValue Lit;
4226       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4227         return false;
4228       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4229       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4230     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4231       // Special-case character extraction so we don't have to construct an
4232       // APValue for the whole string.
4233       assert(LVal.Designator.Entries.size() <= 1 &&
4234              "Can only read characters from string literals");
4235       if (LVal.Designator.Entries.empty()) {
4236         // Fail for now for LValue to RValue conversion of an array.
4237         // (This shouldn't show up in C/C++, but it could be triggered by a
4238         // weird EvaluateAsRValue call from a tool.)
4239         Info.FFDiag(Conv);
4240         return false;
4241       }
4242       if (LVal.Designator.isOnePastTheEnd()) {
4243         if (Info.getLangOpts().CPlusPlus11)
4244           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4245         else
4246           Info.FFDiag(Conv);
4247         return false;
4248       }
4249       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4250       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4251       return true;
4252     }
4253   }
4254 
4255   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4256   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4257 }
4258 
4259 /// Perform an assignment of Val to LVal. Takes ownership of Val.
handleAssignment(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,APValue & Val)4260 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4261                              QualType LValType, APValue &Val) {
4262   if (LVal.Designator.Invalid)
4263     return false;
4264 
4265   if (!Info.getLangOpts().CPlusPlus14) {
4266     Info.FFDiag(E);
4267     return false;
4268   }
4269 
4270   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4271   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4272 }
4273 
4274 namespace {
4275 struct CompoundAssignSubobjectHandler {
4276   EvalInfo &Info;
4277   const CompoundAssignOperator *E;
4278   QualType PromotedLHSType;
4279   BinaryOperatorKind Opcode;
4280   const APValue &RHS;
4281 
4282   static const AccessKinds AccessKind = AK_Assign;
4283 
4284   typedef bool result_type;
4285 
checkConst__anone93968c60c11::CompoundAssignSubobjectHandler4286   bool checkConst(QualType QT) {
4287     // Assigning to a const object has undefined behavior.
4288     if (QT.isConstQualified()) {
4289       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4290       return false;
4291     }
4292     return true;
4293   }
4294 
failed__anone93968c60c11::CompoundAssignSubobjectHandler4295   bool failed() { return false; }
found__anone93968c60c11::CompoundAssignSubobjectHandler4296   bool found(APValue &Subobj, QualType SubobjType) {
4297     switch (Subobj.getKind()) {
4298     case APValue::Int:
4299       return found(Subobj.getInt(), SubobjType);
4300     case APValue::Float:
4301       return found(Subobj.getFloat(), SubobjType);
4302     case APValue::ComplexInt:
4303     case APValue::ComplexFloat:
4304       // FIXME: Implement complex compound assignment.
4305       Info.FFDiag(E);
4306       return false;
4307     case APValue::LValue:
4308       return foundPointer(Subobj, SubobjType);
4309     case APValue::Vector:
4310       return foundVector(Subobj, SubobjType);
4311     default:
4312       // FIXME: can this happen?
4313       Info.FFDiag(E);
4314       return false;
4315     }
4316   }
4317 
foundVector__anone93968c60c11::CompoundAssignSubobjectHandler4318   bool foundVector(APValue &Value, QualType SubobjType) {
4319     if (!checkConst(SubobjType))
4320       return false;
4321 
4322     if (!SubobjType->isVectorType()) {
4323       Info.FFDiag(E);
4324       return false;
4325     }
4326     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4327   }
4328 
found__anone93968c60c11::CompoundAssignSubobjectHandler4329   bool found(APSInt &Value, QualType SubobjType) {
4330     if (!checkConst(SubobjType))
4331       return false;
4332 
4333     if (!SubobjType->isIntegerType()) {
4334       // We don't support compound assignment on integer-cast-to-pointer
4335       // values.
4336       Info.FFDiag(E);
4337       return false;
4338     }
4339 
4340     if (RHS.isInt()) {
4341       APSInt LHS =
4342           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4343       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4344         return false;
4345       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4346       return true;
4347     } else if (RHS.isFloat()) {
4348       const FPOptions FPO = E->getFPFeaturesInEffect(
4349                                     Info.Ctx.getLangOpts());
4350       APFloat FValue(0.0);
4351       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4352                                   PromotedLHSType, FValue) &&
4353              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4354              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4355                                   Value);
4356     }
4357 
4358     Info.FFDiag(E);
4359     return false;
4360   }
found__anone93968c60c11::CompoundAssignSubobjectHandler4361   bool found(APFloat &Value, QualType SubobjType) {
4362     return checkConst(SubobjType) &&
4363            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4364                                   Value) &&
4365            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4366            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4367   }
foundPointer__anone93968c60c11::CompoundAssignSubobjectHandler4368   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4369     if (!checkConst(SubobjType))
4370       return false;
4371 
4372     QualType PointeeType;
4373     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4374       PointeeType = PT->getPointeeType();
4375 
4376     if (PointeeType.isNull() || !RHS.isInt() ||
4377         (Opcode != BO_Add && Opcode != BO_Sub)) {
4378       Info.FFDiag(E);
4379       return false;
4380     }
4381 
4382     APSInt Offset = RHS.getInt();
4383     if (Opcode == BO_Sub)
4384       negateAsSigned(Offset);
4385 
4386     LValue LVal;
4387     LVal.setFrom(Info.Ctx, Subobj);
4388     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4389       return false;
4390     LVal.moveInto(Subobj);
4391     return true;
4392   }
4393 };
4394 } // end anonymous namespace
4395 
4396 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4397 
4398 /// Perform a compound assignment of LVal <op>= RVal.
handleCompoundAssignment(EvalInfo & Info,const CompoundAssignOperator * E,const LValue & LVal,QualType LValType,QualType PromotedLValType,BinaryOperatorKind Opcode,const APValue & RVal)4399 static bool handleCompoundAssignment(EvalInfo &Info,
4400                                      const CompoundAssignOperator *E,
4401                                      const LValue &LVal, QualType LValType,
4402                                      QualType PromotedLValType,
4403                                      BinaryOperatorKind Opcode,
4404                                      const APValue &RVal) {
4405   if (LVal.Designator.Invalid)
4406     return false;
4407 
4408   if (!Info.getLangOpts().CPlusPlus14) {
4409     Info.FFDiag(E);
4410     return false;
4411   }
4412 
4413   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4414   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4415                                              RVal };
4416   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4417 }
4418 
4419 namespace {
4420 struct IncDecSubobjectHandler {
4421   EvalInfo &Info;
4422   const UnaryOperator *E;
4423   AccessKinds AccessKind;
4424   APValue *Old;
4425 
4426   typedef bool result_type;
4427 
checkConst__anone93968c60d11::IncDecSubobjectHandler4428   bool checkConst(QualType QT) {
4429     // Assigning to a const object has undefined behavior.
4430     if (QT.isConstQualified()) {
4431       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4432       return false;
4433     }
4434     return true;
4435   }
4436 
failed__anone93968c60d11::IncDecSubobjectHandler4437   bool failed() { return false; }
found__anone93968c60d11::IncDecSubobjectHandler4438   bool found(APValue &Subobj, QualType SubobjType) {
4439     // Stash the old value. Also clear Old, so we don't clobber it later
4440     // if we're post-incrementing a complex.
4441     if (Old) {
4442       *Old = Subobj;
4443       Old = nullptr;
4444     }
4445 
4446     switch (Subobj.getKind()) {
4447     case APValue::Int:
4448       return found(Subobj.getInt(), SubobjType);
4449     case APValue::Float:
4450       return found(Subobj.getFloat(), SubobjType);
4451     case APValue::ComplexInt:
4452       return found(Subobj.getComplexIntReal(),
4453                    SubobjType->castAs<ComplexType>()->getElementType()
4454                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4455     case APValue::ComplexFloat:
4456       return found(Subobj.getComplexFloatReal(),
4457                    SubobjType->castAs<ComplexType>()->getElementType()
4458                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4459     case APValue::LValue:
4460       return foundPointer(Subobj, SubobjType);
4461     default:
4462       // FIXME: can this happen?
4463       Info.FFDiag(E);
4464       return false;
4465     }
4466   }
found__anone93968c60d11::IncDecSubobjectHandler4467   bool found(APSInt &Value, QualType SubobjType) {
4468     if (!checkConst(SubobjType))
4469       return false;
4470 
4471     if (!SubobjType->isIntegerType()) {
4472       // We don't support increment / decrement on integer-cast-to-pointer
4473       // values.
4474       Info.FFDiag(E);
4475       return false;
4476     }
4477 
4478     if (Old) *Old = APValue(Value);
4479 
4480     // bool arithmetic promotes to int, and the conversion back to bool
4481     // doesn't reduce mod 2^n, so special-case it.
4482     if (SubobjType->isBooleanType()) {
4483       if (AccessKind == AK_Increment)
4484         Value = 1;
4485       else
4486         Value = !Value;
4487       return true;
4488     }
4489 
4490     bool WasNegative = Value.isNegative();
4491     if (AccessKind == AK_Increment) {
4492       ++Value;
4493 
4494       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4495         APSInt ActualValue(Value, /*IsUnsigned*/true);
4496         return HandleOverflow(Info, E, ActualValue, SubobjType);
4497       }
4498     } else {
4499       --Value;
4500 
4501       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4502         unsigned BitWidth = Value.getBitWidth();
4503         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4504         ActualValue.setBit(BitWidth);
4505         return HandleOverflow(Info, E, ActualValue, SubobjType);
4506       }
4507     }
4508     return true;
4509   }
found__anone93968c60d11::IncDecSubobjectHandler4510   bool found(APFloat &Value, QualType SubobjType) {
4511     if (!checkConst(SubobjType))
4512       return false;
4513 
4514     if (Old) *Old = APValue(Value);
4515 
4516     APFloat One(Value.getSemantics(), 1);
4517     if (AccessKind == AK_Increment)
4518       Value.add(One, APFloat::rmNearestTiesToEven);
4519     else
4520       Value.subtract(One, APFloat::rmNearestTiesToEven);
4521     return true;
4522   }
foundPointer__anone93968c60d11::IncDecSubobjectHandler4523   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4524     if (!checkConst(SubobjType))
4525       return false;
4526 
4527     QualType PointeeType;
4528     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4529       PointeeType = PT->getPointeeType();
4530     else {
4531       Info.FFDiag(E);
4532       return false;
4533     }
4534 
4535     LValue LVal;
4536     LVal.setFrom(Info.Ctx, Subobj);
4537     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4538                                      AccessKind == AK_Increment ? 1 : -1))
4539       return false;
4540     LVal.moveInto(Subobj);
4541     return true;
4542   }
4543 };
4544 } // end anonymous namespace
4545 
4546 /// Perform an increment or decrement on LVal.
handleIncDec(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,bool IsIncrement,APValue * Old)4547 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4548                          QualType LValType, bool IsIncrement, APValue *Old) {
4549   if (LVal.Designator.Invalid)
4550     return false;
4551 
4552   if (!Info.getLangOpts().CPlusPlus14) {
4553     Info.FFDiag(E);
4554     return false;
4555   }
4556 
4557   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4558   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4559   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4560   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4561 }
4562 
4563 /// Build an lvalue for the object argument of a member function call.
EvaluateObjectArgument(EvalInfo & Info,const Expr * Object,LValue & This)4564 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4565                                    LValue &This) {
4566   if (Object->getType()->isPointerType() && Object->isRValue())
4567     return EvaluatePointer(Object, This, Info);
4568 
4569   if (Object->isGLValue())
4570     return EvaluateLValue(Object, This, Info);
4571 
4572   if (Object->getType()->isLiteralType(Info.Ctx))
4573     return EvaluateTemporary(Object, This, Info);
4574 
4575   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4576   return false;
4577 }
4578 
4579 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4580 /// lvalue referring to the result.
4581 ///
4582 /// \param Info - Information about the ongoing evaluation.
4583 /// \param LV - An lvalue referring to the base of the member pointer.
4584 /// \param RHS - The member pointer expression.
4585 /// \param IncludeMember - Specifies whether the member itself is included in
4586 ///        the resulting LValue subobject designator. This is not possible when
4587 ///        creating a bound member function.
4588 /// \return The field or method declaration to which the member pointer refers,
4589 ///         or 0 if evaluation fails.
HandleMemberPointerAccess(EvalInfo & Info,QualType LVType,LValue & LV,const Expr * RHS,bool IncludeMember=true)4590 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4591                                                   QualType LVType,
4592                                                   LValue &LV,
4593                                                   const Expr *RHS,
4594                                                   bool IncludeMember = true) {
4595   MemberPtr MemPtr;
4596   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4597     return nullptr;
4598 
4599   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4600   // member value, the behavior is undefined.
4601   if (!MemPtr.getDecl()) {
4602     // FIXME: Specific diagnostic.
4603     Info.FFDiag(RHS);
4604     return nullptr;
4605   }
4606 
4607   if (MemPtr.isDerivedMember()) {
4608     // This is a member of some derived class. Truncate LV appropriately.
4609     // The end of the derived-to-base path for the base object must match the
4610     // derived-to-base path for the member pointer.
4611     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4612         LV.Designator.Entries.size()) {
4613       Info.FFDiag(RHS);
4614       return nullptr;
4615     }
4616     unsigned PathLengthToMember =
4617         LV.Designator.Entries.size() - MemPtr.Path.size();
4618     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4619       const CXXRecordDecl *LVDecl = getAsBaseClass(
4620           LV.Designator.Entries[PathLengthToMember + I]);
4621       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4622       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4623         Info.FFDiag(RHS);
4624         return nullptr;
4625       }
4626     }
4627 
4628     // Truncate the lvalue to the appropriate derived class.
4629     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4630                             PathLengthToMember))
4631       return nullptr;
4632   } else if (!MemPtr.Path.empty()) {
4633     // Extend the LValue path with the member pointer's path.
4634     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4635                                   MemPtr.Path.size() + IncludeMember);
4636 
4637     // Walk down to the appropriate base class.
4638     if (const PointerType *PT = LVType->getAs<PointerType>())
4639       LVType = PT->getPointeeType();
4640     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4641     assert(RD && "member pointer access on non-class-type expression");
4642     // The first class in the path is that of the lvalue.
4643     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4644       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4645       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4646         return nullptr;
4647       RD = Base;
4648     }
4649     // Finally cast to the class containing the member.
4650     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4651                                 MemPtr.getContainingRecord()))
4652       return nullptr;
4653   }
4654 
4655   // Add the member. Note that we cannot build bound member functions here.
4656   if (IncludeMember) {
4657     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4658       if (!HandleLValueMember(Info, RHS, LV, FD))
4659         return nullptr;
4660     } else if (const IndirectFieldDecl *IFD =
4661                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4662       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4663         return nullptr;
4664     } else {
4665       llvm_unreachable("can't construct reference to bound member function");
4666     }
4667   }
4668 
4669   return MemPtr.getDecl();
4670 }
4671 
HandleMemberPointerAccess(EvalInfo & Info,const BinaryOperator * BO,LValue & LV,bool IncludeMember=true)4672 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4673                                                   const BinaryOperator *BO,
4674                                                   LValue &LV,
4675                                                   bool IncludeMember = true) {
4676   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4677 
4678   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4679     if (Info.noteFailure()) {
4680       MemberPtr MemPtr;
4681       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4682     }
4683     return nullptr;
4684   }
4685 
4686   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4687                                    BO->getRHS(), IncludeMember);
4688 }
4689 
4690 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4691 /// the provided lvalue, which currently refers to the base object.
HandleBaseToDerivedCast(EvalInfo & Info,const CastExpr * E,LValue & Result)4692 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4693                                     LValue &Result) {
4694   SubobjectDesignator &D = Result.Designator;
4695   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4696     return false;
4697 
4698   QualType TargetQT = E->getType();
4699   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4700     TargetQT = PT->getPointeeType();
4701 
4702   // Check this cast lands within the final derived-to-base subobject path.
4703   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4704     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4705       << D.MostDerivedType << TargetQT;
4706     return false;
4707   }
4708 
4709   // Check the type of the final cast. We don't need to check the path,
4710   // since a cast can only be formed if the path is unique.
4711   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4712   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4713   const CXXRecordDecl *FinalType;
4714   if (NewEntriesSize == D.MostDerivedPathLength)
4715     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4716   else
4717     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4718   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4719     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4720       << D.MostDerivedType << TargetQT;
4721     return false;
4722   }
4723 
4724   // Truncate the lvalue to the appropriate derived class.
4725   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4726 }
4727 
4728 /// Get the value to use for a default-initialized object of type T.
4729 /// Return false if it encounters something invalid.
getDefaultInitValue(QualType T,APValue & Result)4730 static bool getDefaultInitValue(QualType T, APValue &Result) {
4731   bool Success = true;
4732   if (auto *RD = T->getAsCXXRecordDecl()) {
4733     if (RD->isInvalidDecl()) {
4734       Result = APValue();
4735       return false;
4736     }
4737     if (RD->isUnion()) {
4738       Result = APValue((const FieldDecl *)nullptr);
4739       return true;
4740     }
4741     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4742                      std::distance(RD->field_begin(), RD->field_end()));
4743 
4744     unsigned Index = 0;
4745     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4746                                                   End = RD->bases_end();
4747          I != End; ++I, ++Index)
4748       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4749 
4750     for (const auto *I : RD->fields()) {
4751       if (I->isUnnamedBitfield())
4752         continue;
4753       Success &= getDefaultInitValue(I->getType(),
4754                                      Result.getStructField(I->getFieldIndex()));
4755     }
4756     return Success;
4757   }
4758 
4759   if (auto *AT =
4760           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4761     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4762     if (Result.hasArrayFiller())
4763       Success &=
4764           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4765 
4766     return Success;
4767   }
4768 
4769   Result = APValue::IndeterminateValue();
4770   return true;
4771 }
4772 
4773 namespace {
4774 enum EvalStmtResult {
4775   /// Evaluation failed.
4776   ESR_Failed,
4777   /// Hit a 'return' statement.
4778   ESR_Returned,
4779   /// Evaluation succeeded.
4780   ESR_Succeeded,
4781   /// Hit a 'continue' statement.
4782   ESR_Continue,
4783   /// Hit a 'break' statement.
4784   ESR_Break,
4785   /// Still scanning for 'case' or 'default' statement.
4786   ESR_CaseNotFound
4787 };
4788 }
4789 
EvaluateVarDecl(EvalInfo & Info,const VarDecl * VD)4790 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4791   // We don't need to evaluate the initializer for a static local.
4792   if (!VD->hasLocalStorage())
4793     return true;
4794 
4795   LValue Result;
4796   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4797                                                    ScopeKind::Block, Result);
4798 
4799   const Expr *InitE = VD->getInit();
4800   if (!InitE) {
4801     if (VD->getType()->isDependentType())
4802       return Info.noteSideEffect();
4803     return getDefaultInitValue(VD->getType(), Val);
4804   }
4805   if (InitE->isValueDependent())
4806     return false;
4807 
4808   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4809     // Wipe out any partially-computed value, to allow tracking that this
4810     // evaluation failed.
4811     Val = APValue();
4812     return false;
4813   }
4814 
4815   return true;
4816 }
4817 
EvaluateDecl(EvalInfo & Info,const Decl * D)4818 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4819   bool OK = true;
4820 
4821   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4822     OK &= EvaluateVarDecl(Info, VD);
4823 
4824   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4825     for (auto *BD : DD->bindings())
4826       if (auto *VD = BD->getHoldingVar())
4827         OK &= EvaluateDecl(Info, VD);
4828 
4829   return OK;
4830 }
4831 
EvaluateDependentExpr(const Expr * E,EvalInfo & Info)4832 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4833   assert(E->isValueDependent());
4834   if (Info.noteSideEffect())
4835     return true;
4836   assert(E->containsErrors() && "valid value-dependent expression should never "
4837                                 "reach invalid code path.");
4838   return false;
4839 }
4840 
4841 /// Evaluate a condition (either a variable declaration or an expression).
EvaluateCond(EvalInfo & Info,const VarDecl * CondDecl,const Expr * Cond,bool & Result)4842 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4843                          const Expr *Cond, bool &Result) {
4844   if (Cond->isValueDependent())
4845     return false;
4846   FullExpressionRAII Scope(Info);
4847   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4848     return false;
4849   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4850     return false;
4851   return Scope.destroy();
4852 }
4853 
4854 namespace {
4855 /// A location where the result (returned value) of evaluating a
4856 /// statement should be stored.
4857 struct StmtResult {
4858   /// The APValue that should be filled in with the returned value.
4859   APValue &Value;
4860   /// The location containing the result, if any (used to support RVO).
4861   const LValue *Slot;
4862 };
4863 
4864 struct TempVersionRAII {
4865   CallStackFrame &Frame;
4866 
TempVersionRAII__anone93968c60f11::TempVersionRAII4867   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4868     Frame.pushTempVersion();
4869   }
4870 
~TempVersionRAII__anone93968c60f11::TempVersionRAII4871   ~TempVersionRAII() {
4872     Frame.popTempVersion();
4873   }
4874 };
4875 
4876 }
4877 
4878 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4879                                    const Stmt *S,
4880                                    const SwitchCase *SC = nullptr);
4881 
4882 /// Evaluate the body of a loop, and translate the result as appropriate.
EvaluateLoopBody(StmtResult & Result,EvalInfo & Info,const Stmt * Body,const SwitchCase * Case=nullptr)4883 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4884                                        const Stmt *Body,
4885                                        const SwitchCase *Case = nullptr) {
4886   BlockScopeRAII Scope(Info);
4887 
4888   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4889   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4890     ESR = ESR_Failed;
4891 
4892   switch (ESR) {
4893   case ESR_Break:
4894     return ESR_Succeeded;
4895   case ESR_Succeeded:
4896   case ESR_Continue:
4897     return ESR_Continue;
4898   case ESR_Failed:
4899   case ESR_Returned:
4900   case ESR_CaseNotFound:
4901     return ESR;
4902   }
4903   llvm_unreachable("Invalid EvalStmtResult!");
4904 }
4905 
4906 /// Evaluate a switch statement.
EvaluateSwitch(StmtResult & Result,EvalInfo & Info,const SwitchStmt * SS)4907 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4908                                      const SwitchStmt *SS) {
4909   BlockScopeRAII Scope(Info);
4910 
4911   // Evaluate the switch condition.
4912   APSInt Value;
4913   {
4914     if (const Stmt *Init = SS->getInit()) {
4915       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4916       if (ESR != ESR_Succeeded) {
4917         if (ESR != ESR_Failed && !Scope.destroy())
4918           ESR = ESR_Failed;
4919         return ESR;
4920       }
4921     }
4922 
4923     FullExpressionRAII CondScope(Info);
4924     if (SS->getConditionVariable() &&
4925         !EvaluateDecl(Info, SS->getConditionVariable()))
4926       return ESR_Failed;
4927     if (!EvaluateInteger(SS->getCond(), Value, Info))
4928       return ESR_Failed;
4929     if (!CondScope.destroy())
4930       return ESR_Failed;
4931   }
4932 
4933   // Find the switch case corresponding to the value of the condition.
4934   // FIXME: Cache this lookup.
4935   const SwitchCase *Found = nullptr;
4936   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4937        SC = SC->getNextSwitchCase()) {
4938     if (isa<DefaultStmt>(SC)) {
4939       Found = SC;
4940       continue;
4941     }
4942 
4943     const CaseStmt *CS = cast<CaseStmt>(SC);
4944     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4945     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4946                               : LHS;
4947     if (LHS <= Value && Value <= RHS) {
4948       Found = SC;
4949       break;
4950     }
4951   }
4952 
4953   if (!Found)
4954     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4955 
4956   // Search the switch body for the switch case and evaluate it from there.
4957   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4958   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4959     return ESR_Failed;
4960 
4961   switch (ESR) {
4962   case ESR_Break:
4963     return ESR_Succeeded;
4964   case ESR_Succeeded:
4965   case ESR_Continue:
4966   case ESR_Failed:
4967   case ESR_Returned:
4968     return ESR;
4969   case ESR_CaseNotFound:
4970     // This can only happen if the switch case is nested within a statement
4971     // expression. We have no intention of supporting that.
4972     Info.FFDiag(Found->getBeginLoc(),
4973                 diag::note_constexpr_stmt_expr_unsupported);
4974     return ESR_Failed;
4975   }
4976   llvm_unreachable("Invalid EvalStmtResult!");
4977 }
4978 
4979 // Evaluate a statement.
EvaluateStmt(StmtResult & Result,EvalInfo & Info,const Stmt * S,const SwitchCase * Case)4980 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4981                                    const Stmt *S, const SwitchCase *Case) {
4982   if (!Info.nextStep(S))
4983     return ESR_Failed;
4984 
4985   // If we're hunting down a 'case' or 'default' label, recurse through
4986   // substatements until we hit the label.
4987   if (Case) {
4988     switch (S->getStmtClass()) {
4989     case Stmt::CompoundStmtClass:
4990       // FIXME: Precompute which substatement of a compound statement we
4991       // would jump to, and go straight there rather than performing a
4992       // linear scan each time.
4993     case Stmt::LabelStmtClass:
4994     case Stmt::AttributedStmtClass:
4995     case Stmt::DoStmtClass:
4996       break;
4997 
4998     case Stmt::CaseStmtClass:
4999     case Stmt::DefaultStmtClass:
5000       if (Case == S)
5001         Case = nullptr;
5002       break;
5003 
5004     case Stmt::IfStmtClass: {
5005       // FIXME: Precompute which side of an 'if' we would jump to, and go
5006       // straight there rather than scanning both sides.
5007       const IfStmt *IS = cast<IfStmt>(S);
5008 
5009       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5010       // preceded by our switch label.
5011       BlockScopeRAII Scope(Info);
5012 
5013       // Step into the init statement in case it brings an (uninitialized)
5014       // variable into scope.
5015       if (const Stmt *Init = IS->getInit()) {
5016         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5017         if (ESR != ESR_CaseNotFound) {
5018           assert(ESR != ESR_Succeeded);
5019           return ESR;
5020         }
5021       }
5022 
5023       // Condition variable must be initialized if it exists.
5024       // FIXME: We can skip evaluating the body if there's a condition
5025       // variable, as there can't be any case labels within it.
5026       // (The same is true for 'for' statements.)
5027 
5028       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5029       if (ESR == ESR_Failed)
5030         return ESR;
5031       if (ESR != ESR_CaseNotFound)
5032         return Scope.destroy() ? ESR : ESR_Failed;
5033       if (!IS->getElse())
5034         return ESR_CaseNotFound;
5035 
5036       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5037       if (ESR == ESR_Failed)
5038         return ESR;
5039       if (ESR != ESR_CaseNotFound)
5040         return Scope.destroy() ? ESR : ESR_Failed;
5041       return ESR_CaseNotFound;
5042     }
5043 
5044     case Stmt::WhileStmtClass: {
5045       EvalStmtResult ESR =
5046           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5047       if (ESR != ESR_Continue)
5048         return ESR;
5049       break;
5050     }
5051 
5052     case Stmt::ForStmtClass: {
5053       const ForStmt *FS = cast<ForStmt>(S);
5054       BlockScopeRAII Scope(Info);
5055 
5056       // Step into the init statement in case it brings an (uninitialized)
5057       // variable into scope.
5058       if (const Stmt *Init = FS->getInit()) {
5059         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5060         if (ESR != ESR_CaseNotFound) {
5061           assert(ESR != ESR_Succeeded);
5062           return ESR;
5063         }
5064       }
5065 
5066       EvalStmtResult ESR =
5067           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5068       if (ESR != ESR_Continue)
5069         return ESR;
5070       if (const auto *Inc = FS->getInc()) {
5071         if (Inc->isValueDependent()) {
5072           if (!EvaluateDependentExpr(Inc, Info))
5073             return ESR_Failed;
5074         } else {
5075           FullExpressionRAII IncScope(Info);
5076           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5077             return ESR_Failed;
5078         }
5079       }
5080       break;
5081     }
5082 
5083     case Stmt::DeclStmtClass: {
5084       // Start the lifetime of any uninitialized variables we encounter. They
5085       // might be used by the selected branch of the switch.
5086       const DeclStmt *DS = cast<DeclStmt>(S);
5087       for (const auto *D : DS->decls()) {
5088         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5089           if (VD->hasLocalStorage() && !VD->getInit())
5090             if (!EvaluateVarDecl(Info, VD))
5091               return ESR_Failed;
5092           // FIXME: If the variable has initialization that can't be jumped
5093           // over, bail out of any immediately-surrounding compound-statement
5094           // too. There can't be any case labels here.
5095         }
5096       }
5097       return ESR_CaseNotFound;
5098     }
5099 
5100     default:
5101       return ESR_CaseNotFound;
5102     }
5103   }
5104 
5105   switch (S->getStmtClass()) {
5106   default:
5107     if (const Expr *E = dyn_cast<Expr>(S)) {
5108       if (E->isValueDependent()) {
5109         if (!EvaluateDependentExpr(E, Info))
5110           return ESR_Failed;
5111       } else {
5112         // Don't bother evaluating beyond an expression-statement which couldn't
5113         // be evaluated.
5114         // FIXME: Do we need the FullExpressionRAII object here?
5115         // VisitExprWithCleanups should create one when necessary.
5116         FullExpressionRAII Scope(Info);
5117         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5118           return ESR_Failed;
5119       }
5120       return ESR_Succeeded;
5121     }
5122 
5123     Info.FFDiag(S->getBeginLoc());
5124     return ESR_Failed;
5125 
5126   case Stmt::NullStmtClass:
5127     return ESR_Succeeded;
5128 
5129   case Stmt::DeclStmtClass: {
5130     const DeclStmt *DS = cast<DeclStmt>(S);
5131     for (const auto *D : DS->decls()) {
5132       // Each declaration initialization is its own full-expression.
5133       FullExpressionRAII Scope(Info);
5134       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5135         return ESR_Failed;
5136       if (!Scope.destroy())
5137         return ESR_Failed;
5138     }
5139     return ESR_Succeeded;
5140   }
5141 
5142   case Stmt::ReturnStmtClass: {
5143     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5144     FullExpressionRAII Scope(Info);
5145     if (RetExpr && RetExpr->isValueDependent()) {
5146       EvaluateDependentExpr(RetExpr, Info);
5147       // We know we returned, but we don't know what the value is.
5148       return ESR_Failed;
5149     }
5150     if (RetExpr &&
5151         !(Result.Slot
5152               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5153               : Evaluate(Result.Value, Info, RetExpr)))
5154       return ESR_Failed;
5155     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5156   }
5157 
5158   case Stmt::CompoundStmtClass: {
5159     BlockScopeRAII Scope(Info);
5160 
5161     const CompoundStmt *CS = cast<CompoundStmt>(S);
5162     for (const auto *BI : CS->body()) {
5163       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5164       if (ESR == ESR_Succeeded)
5165         Case = nullptr;
5166       else if (ESR != ESR_CaseNotFound) {
5167         if (ESR != ESR_Failed && !Scope.destroy())
5168           return ESR_Failed;
5169         return ESR;
5170       }
5171     }
5172     if (Case)
5173       return ESR_CaseNotFound;
5174     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5175   }
5176 
5177   case Stmt::IfStmtClass: {
5178     const IfStmt *IS = cast<IfStmt>(S);
5179 
5180     // Evaluate the condition, as either a var decl or as an expression.
5181     BlockScopeRAII Scope(Info);
5182     if (const Stmt *Init = IS->getInit()) {
5183       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5184       if (ESR != ESR_Succeeded) {
5185         if (ESR != ESR_Failed && !Scope.destroy())
5186           return ESR_Failed;
5187         return ESR;
5188       }
5189     }
5190     bool Cond;
5191     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5192       return ESR_Failed;
5193 
5194     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5195       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5196       if (ESR != ESR_Succeeded) {
5197         if (ESR != ESR_Failed && !Scope.destroy())
5198           return ESR_Failed;
5199         return ESR;
5200       }
5201     }
5202     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5203   }
5204 
5205   case Stmt::WhileStmtClass: {
5206     const WhileStmt *WS = cast<WhileStmt>(S);
5207     while (true) {
5208       BlockScopeRAII Scope(Info);
5209       bool Continue;
5210       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5211                         Continue))
5212         return ESR_Failed;
5213       if (!Continue)
5214         break;
5215 
5216       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5217       if (ESR != ESR_Continue) {
5218         if (ESR != ESR_Failed && !Scope.destroy())
5219           return ESR_Failed;
5220         return ESR;
5221       }
5222       if (!Scope.destroy())
5223         return ESR_Failed;
5224     }
5225     return ESR_Succeeded;
5226   }
5227 
5228   case Stmt::DoStmtClass: {
5229     const DoStmt *DS = cast<DoStmt>(S);
5230     bool Continue;
5231     do {
5232       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5233       if (ESR != ESR_Continue)
5234         return ESR;
5235       Case = nullptr;
5236 
5237       if (DS->getCond()->isValueDependent()) {
5238         EvaluateDependentExpr(DS->getCond(), Info);
5239         // Bailout as we don't know whether to keep going or terminate the loop.
5240         return ESR_Failed;
5241       }
5242       FullExpressionRAII CondScope(Info);
5243       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5244           !CondScope.destroy())
5245         return ESR_Failed;
5246     } while (Continue);
5247     return ESR_Succeeded;
5248   }
5249 
5250   case Stmt::ForStmtClass: {
5251     const ForStmt *FS = cast<ForStmt>(S);
5252     BlockScopeRAII ForScope(Info);
5253     if (FS->getInit()) {
5254       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5255       if (ESR != ESR_Succeeded) {
5256         if (ESR != ESR_Failed && !ForScope.destroy())
5257           return ESR_Failed;
5258         return ESR;
5259       }
5260     }
5261     while (true) {
5262       BlockScopeRAII IterScope(Info);
5263       bool Continue = true;
5264       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5265                                          FS->getCond(), Continue))
5266         return ESR_Failed;
5267       if (!Continue)
5268         break;
5269 
5270       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5271       if (ESR != ESR_Continue) {
5272         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5273           return ESR_Failed;
5274         return ESR;
5275       }
5276 
5277       if (const auto *Inc = FS->getInc()) {
5278         if (Inc->isValueDependent()) {
5279           if (!EvaluateDependentExpr(Inc, Info))
5280             return ESR_Failed;
5281         } else {
5282           FullExpressionRAII IncScope(Info);
5283           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5284             return ESR_Failed;
5285         }
5286       }
5287 
5288       if (!IterScope.destroy())
5289         return ESR_Failed;
5290     }
5291     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5292   }
5293 
5294   case Stmt::CXXForRangeStmtClass: {
5295     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5296     BlockScopeRAII Scope(Info);
5297 
5298     // Evaluate the init-statement if present.
5299     if (FS->getInit()) {
5300       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5301       if (ESR != ESR_Succeeded) {
5302         if (ESR != ESR_Failed && !Scope.destroy())
5303           return ESR_Failed;
5304         return ESR;
5305       }
5306     }
5307 
5308     // Initialize the __range variable.
5309     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5310     if (ESR != ESR_Succeeded) {
5311       if (ESR != ESR_Failed && !Scope.destroy())
5312         return ESR_Failed;
5313       return ESR;
5314     }
5315 
5316     // Create the __begin and __end iterators.
5317     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5318     if (ESR != ESR_Succeeded) {
5319       if (ESR != ESR_Failed && !Scope.destroy())
5320         return ESR_Failed;
5321       return ESR;
5322     }
5323     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5324     if (ESR != ESR_Succeeded) {
5325       if (ESR != ESR_Failed && !Scope.destroy())
5326         return ESR_Failed;
5327       return ESR;
5328     }
5329 
5330     while (true) {
5331       // Condition: __begin != __end.
5332       {
5333         if (FS->getCond()->isValueDependent()) {
5334           EvaluateDependentExpr(FS->getCond(), Info);
5335           // We don't know whether to keep going or terminate the loop.
5336           return ESR_Failed;
5337         }
5338         bool Continue = true;
5339         FullExpressionRAII CondExpr(Info);
5340         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5341           return ESR_Failed;
5342         if (!Continue)
5343           break;
5344       }
5345 
5346       // User's variable declaration, initialized by *__begin.
5347       BlockScopeRAII InnerScope(Info);
5348       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5349       if (ESR != ESR_Succeeded) {
5350         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5351           return ESR_Failed;
5352         return ESR;
5353       }
5354 
5355       // Loop body.
5356       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5357       if (ESR != ESR_Continue) {
5358         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5359           return ESR_Failed;
5360         return ESR;
5361       }
5362       if (FS->getInc()->isValueDependent()) {
5363         if (!EvaluateDependentExpr(FS->getInc(), Info))
5364           return ESR_Failed;
5365       } else {
5366         // Increment: ++__begin
5367         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5368           return ESR_Failed;
5369       }
5370 
5371       if (!InnerScope.destroy())
5372         return ESR_Failed;
5373     }
5374 
5375     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5376   }
5377 
5378   case Stmt::SwitchStmtClass:
5379     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5380 
5381   case Stmt::ContinueStmtClass:
5382     return ESR_Continue;
5383 
5384   case Stmt::BreakStmtClass:
5385     return ESR_Break;
5386 
5387   case Stmt::LabelStmtClass:
5388     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5389 
5390   case Stmt::AttributedStmtClass:
5391     // As a general principle, C++11 attributes can be ignored without
5392     // any semantic impact.
5393     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5394                         Case);
5395 
5396   case Stmt::CaseStmtClass:
5397   case Stmt::DefaultStmtClass:
5398     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5399   case Stmt::CXXTryStmtClass:
5400     // Evaluate try blocks by evaluating all sub statements.
5401     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5402   }
5403 }
5404 
5405 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5406 /// default constructor. If so, we'll fold it whether or not it's marked as
5407 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5408 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)5409 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5410                                            const CXXConstructorDecl *CD,
5411                                            bool IsValueInitialization) {
5412   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5413     return false;
5414 
5415   // Value-initialization does not call a trivial default constructor, so such a
5416   // call is a core constant expression whether or not the constructor is
5417   // constexpr.
5418   if (!CD->isConstexpr() && !IsValueInitialization) {
5419     if (Info.getLangOpts().CPlusPlus11) {
5420       // FIXME: If DiagDecl is an implicitly-declared special member function,
5421       // we should be much more explicit about why it's not constexpr.
5422       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5423         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5424       Info.Note(CD->getLocation(), diag::note_declared_at);
5425     } else {
5426       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5427     }
5428   }
5429   return true;
5430 }
5431 
5432 /// CheckConstexprFunction - Check that a function can be called in a constant
5433 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition,const Stmt * Body)5434 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5435                                    const FunctionDecl *Declaration,
5436                                    const FunctionDecl *Definition,
5437                                    const Stmt *Body) {
5438   // Potential constant expressions can contain calls to declared, but not yet
5439   // defined, constexpr functions.
5440   if (Info.checkingPotentialConstantExpression() && !Definition &&
5441       Declaration->isConstexpr())
5442     return false;
5443 
5444   // Bail out if the function declaration itself is invalid.  We will
5445   // have produced a relevant diagnostic while parsing it, so just
5446   // note the problematic sub-expression.
5447   if (Declaration->isInvalidDecl()) {
5448     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5449     return false;
5450   }
5451 
5452   // DR1872: An instantiated virtual constexpr function can't be called in a
5453   // constant expression (prior to C++20). We can still constant-fold such a
5454   // call.
5455   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5456       cast<CXXMethodDecl>(Declaration)->isVirtual())
5457     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5458 
5459   if (Definition && Definition->isInvalidDecl()) {
5460     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5461     return false;
5462   }
5463 
5464   // Can we evaluate this function call?
5465   if (Definition && Definition->isConstexpr() && Body)
5466     return true;
5467 
5468   if (Info.getLangOpts().CPlusPlus11) {
5469     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5470 
5471     // If this function is not constexpr because it is an inherited
5472     // non-constexpr constructor, diagnose that directly.
5473     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5474     if (CD && CD->isInheritingConstructor()) {
5475       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5476       if (!Inherited->isConstexpr())
5477         DiagDecl = CD = Inherited;
5478     }
5479 
5480     // FIXME: If DiagDecl is an implicitly-declared special member function
5481     // or an inheriting constructor, we should be much more explicit about why
5482     // it's not constexpr.
5483     if (CD && CD->isInheritingConstructor())
5484       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5485         << CD->getInheritedConstructor().getConstructor()->getParent();
5486     else
5487       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5488         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5489     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5490   } else {
5491     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5492   }
5493   return false;
5494 }
5495 
5496 namespace {
5497 struct CheckDynamicTypeHandler {
5498   AccessKinds AccessKind;
5499   typedef bool result_type;
failed__anone93968c61011::CheckDynamicTypeHandler5500   bool failed() { return false; }
found__anone93968c61011::CheckDynamicTypeHandler5501   bool found(APValue &Subobj, QualType SubobjType) { return true; }
found__anone93968c61011::CheckDynamicTypeHandler5502   bool found(APSInt &Value, QualType SubobjType) { return true; }
found__anone93968c61011::CheckDynamicTypeHandler5503   bool found(APFloat &Value, QualType SubobjType) { return true; }
5504 };
5505 } // end anonymous namespace
5506 
5507 /// Check that we can access the notional vptr of an object / determine its
5508 /// dynamic type.
checkDynamicType(EvalInfo & Info,const Expr * E,const LValue & This,AccessKinds AK,bool Polymorphic)5509 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5510                              AccessKinds AK, bool Polymorphic) {
5511   if (This.Designator.Invalid)
5512     return false;
5513 
5514   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5515 
5516   if (!Obj)
5517     return false;
5518 
5519   if (!Obj.Value) {
5520     // The object is not usable in constant expressions, so we can't inspect
5521     // its value to see if it's in-lifetime or what the active union members
5522     // are. We can still check for a one-past-the-end lvalue.
5523     if (This.Designator.isOnePastTheEnd() ||
5524         This.Designator.isMostDerivedAnUnsizedArray()) {
5525       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5526                          ? diag::note_constexpr_access_past_end
5527                          : diag::note_constexpr_access_unsized_array)
5528           << AK;
5529       return false;
5530     } else if (Polymorphic) {
5531       // Conservatively refuse to perform a polymorphic operation if we would
5532       // not be able to read a notional 'vptr' value.
5533       APValue Val;
5534       This.moveInto(Val);
5535       QualType StarThisType =
5536           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5537       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5538           << AK << Val.getAsString(Info.Ctx, StarThisType);
5539       return false;
5540     }
5541     return true;
5542   }
5543 
5544   CheckDynamicTypeHandler Handler{AK};
5545   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5546 }
5547 
5548 /// Check that the pointee of the 'this' pointer in a member function call is
5549 /// either within its lifetime or in its period of construction or destruction.
5550 static bool
checkNonVirtualMemberCallThisPointer(EvalInfo & Info,const Expr * E,const LValue & This,const CXXMethodDecl * NamedMember)5551 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5552                                      const LValue &This,
5553                                      const CXXMethodDecl *NamedMember) {
5554   return checkDynamicType(
5555       Info, E, This,
5556       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5557 }
5558 
5559 struct DynamicType {
5560   /// The dynamic class type of the object.
5561   const CXXRecordDecl *Type;
5562   /// The corresponding path length in the lvalue.
5563   unsigned PathLength;
5564 };
5565 
getBaseClassType(SubobjectDesignator & Designator,unsigned PathLength)5566 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5567                                              unsigned PathLength) {
5568   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5569       Designator.Entries.size() && "invalid path length");
5570   return (PathLength == Designator.MostDerivedPathLength)
5571              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5572              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5573 }
5574 
5575 /// Determine the dynamic type of an object.
ComputeDynamicType(EvalInfo & Info,const Expr * E,LValue & This,AccessKinds AK)5576 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5577                                                 LValue &This, AccessKinds AK) {
5578   // If we don't have an lvalue denoting an object of class type, there is no
5579   // meaningful dynamic type. (We consider objects of non-class type to have no
5580   // dynamic type.)
5581   if (!checkDynamicType(Info, E, This, AK, true))
5582     return None;
5583 
5584   // Refuse to compute a dynamic type in the presence of virtual bases. This
5585   // shouldn't happen other than in constant-folding situations, since literal
5586   // types can't have virtual bases.
5587   //
5588   // Note that consumers of DynamicType assume that the type has no virtual
5589   // bases, and will need modifications if this restriction is relaxed.
5590   const CXXRecordDecl *Class =
5591       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5592   if (!Class || Class->getNumVBases()) {
5593     Info.FFDiag(E);
5594     return None;
5595   }
5596 
5597   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5598   // binary search here instead. But the overwhelmingly common case is that
5599   // we're not in the middle of a constructor, so it probably doesn't matter
5600   // in practice.
5601   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5602   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5603        PathLength <= Path.size(); ++PathLength) {
5604     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5605                                       Path.slice(0, PathLength))) {
5606     case ConstructionPhase::Bases:
5607     case ConstructionPhase::DestroyingBases:
5608       // We're constructing or destroying a base class. This is not the dynamic
5609       // type.
5610       break;
5611 
5612     case ConstructionPhase::None:
5613     case ConstructionPhase::AfterBases:
5614     case ConstructionPhase::AfterFields:
5615     case ConstructionPhase::Destroying:
5616       // We've finished constructing the base classes and not yet started
5617       // destroying them again, so this is the dynamic type.
5618       return DynamicType{getBaseClassType(This.Designator, PathLength),
5619                          PathLength};
5620     }
5621   }
5622 
5623   // CWG issue 1517: we're constructing a base class of the object described by
5624   // 'This', so that object has not yet begun its period of construction and
5625   // any polymorphic operation on it results in undefined behavior.
5626   Info.FFDiag(E);
5627   return None;
5628 }
5629 
5630 /// Perform virtual dispatch.
HandleVirtualDispatch(EvalInfo & Info,const Expr * E,LValue & This,const CXXMethodDecl * Found,llvm::SmallVectorImpl<QualType> & CovariantAdjustmentPath)5631 static const CXXMethodDecl *HandleVirtualDispatch(
5632     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5633     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5634   Optional<DynamicType> DynType = ComputeDynamicType(
5635       Info, E, This,
5636       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5637   if (!DynType)
5638     return nullptr;
5639 
5640   // Find the final overrider. It must be declared in one of the classes on the
5641   // path from the dynamic type to the static type.
5642   // FIXME: If we ever allow literal types to have virtual base classes, that
5643   // won't be true.
5644   const CXXMethodDecl *Callee = Found;
5645   unsigned PathLength = DynType->PathLength;
5646   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5647     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5648     const CXXMethodDecl *Overrider =
5649         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5650     if (Overrider) {
5651       Callee = Overrider;
5652       break;
5653     }
5654   }
5655 
5656   // C++2a [class.abstract]p6:
5657   //   the effect of making a virtual call to a pure virtual function [...] is
5658   //   undefined
5659   if (Callee->isPure()) {
5660     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5661     Info.Note(Callee->getLocation(), diag::note_declared_at);
5662     return nullptr;
5663   }
5664 
5665   // If necessary, walk the rest of the path to determine the sequence of
5666   // covariant adjustment steps to apply.
5667   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5668                                        Found->getReturnType())) {
5669     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5670     for (unsigned CovariantPathLength = PathLength + 1;
5671          CovariantPathLength != This.Designator.Entries.size();
5672          ++CovariantPathLength) {
5673       const CXXRecordDecl *NextClass =
5674           getBaseClassType(This.Designator, CovariantPathLength);
5675       const CXXMethodDecl *Next =
5676           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5677       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5678                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5679         CovariantAdjustmentPath.push_back(Next->getReturnType());
5680     }
5681     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5682                                          CovariantAdjustmentPath.back()))
5683       CovariantAdjustmentPath.push_back(Found->getReturnType());
5684   }
5685 
5686   // Perform 'this' adjustment.
5687   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5688     return nullptr;
5689 
5690   return Callee;
5691 }
5692 
5693 /// Perform the adjustment from a value returned by a virtual function to
5694 /// a value of the statically expected type, which may be a pointer or
5695 /// reference to a base class of the returned type.
HandleCovariantReturnAdjustment(EvalInfo & Info,const Expr * E,APValue & Result,ArrayRef<QualType> Path)5696 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5697                                             APValue &Result,
5698                                             ArrayRef<QualType> Path) {
5699   assert(Result.isLValue() &&
5700          "unexpected kind of APValue for covariant return");
5701   if (Result.isNullPointer())
5702     return true;
5703 
5704   LValue LVal;
5705   LVal.setFrom(Info.Ctx, Result);
5706 
5707   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5708   for (unsigned I = 1; I != Path.size(); ++I) {
5709     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5710     assert(OldClass && NewClass && "unexpected kind of covariant return");
5711     if (OldClass != NewClass &&
5712         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5713       return false;
5714     OldClass = NewClass;
5715   }
5716 
5717   LVal.moveInto(Result);
5718   return true;
5719 }
5720 
5721 /// Determine whether \p Base, which is known to be a direct base class of
5722 /// \p Derived, is a public base class.
isBaseClassPublic(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)5723 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5724                               const CXXRecordDecl *Base) {
5725   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5726     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5727     if (BaseClass && declaresSameEntity(BaseClass, Base))
5728       return BaseSpec.getAccessSpecifier() == AS_public;
5729   }
5730   llvm_unreachable("Base is not a direct base of Derived");
5731 }
5732 
5733 /// Apply the given dynamic cast operation on the provided lvalue.
5734 ///
5735 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5736 /// to find a suitable target subobject.
HandleDynamicCast(EvalInfo & Info,const ExplicitCastExpr * E,LValue & Ptr)5737 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5738                               LValue &Ptr) {
5739   // We can't do anything with a non-symbolic pointer value.
5740   SubobjectDesignator &D = Ptr.Designator;
5741   if (D.Invalid)
5742     return false;
5743 
5744   // C++ [expr.dynamic.cast]p6:
5745   //   If v is a null pointer value, the result is a null pointer value.
5746   if (Ptr.isNullPointer() && !E->isGLValue())
5747     return true;
5748 
5749   // For all the other cases, we need the pointer to point to an object within
5750   // its lifetime / period of construction / destruction, and we need to know
5751   // its dynamic type.
5752   Optional<DynamicType> DynType =
5753       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5754   if (!DynType)
5755     return false;
5756 
5757   // C++ [expr.dynamic.cast]p7:
5758   //   If T is "pointer to cv void", then the result is a pointer to the most
5759   //   derived object
5760   if (E->getType()->isVoidPointerType())
5761     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5762 
5763   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5764   assert(C && "dynamic_cast target is not void pointer nor class");
5765   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5766 
5767   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5768     // C++ [expr.dynamic.cast]p9:
5769     if (!E->isGLValue()) {
5770       //   The value of a failed cast to pointer type is the null pointer value
5771       //   of the required result type.
5772       Ptr.setNull(Info.Ctx, E->getType());
5773       return true;
5774     }
5775 
5776     //   A failed cast to reference type throws [...] std::bad_cast.
5777     unsigned DiagKind;
5778     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5779                    DynType->Type->isDerivedFrom(C)))
5780       DiagKind = 0;
5781     else if (!Paths || Paths->begin() == Paths->end())
5782       DiagKind = 1;
5783     else if (Paths->isAmbiguous(CQT))
5784       DiagKind = 2;
5785     else {
5786       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5787       DiagKind = 3;
5788     }
5789     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5790         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5791         << Info.Ctx.getRecordType(DynType->Type)
5792         << E->getType().getUnqualifiedType();
5793     return false;
5794   };
5795 
5796   // Runtime check, phase 1:
5797   //   Walk from the base subobject towards the derived object looking for the
5798   //   target type.
5799   for (int PathLength = Ptr.Designator.Entries.size();
5800        PathLength >= (int)DynType->PathLength; --PathLength) {
5801     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5802     if (declaresSameEntity(Class, C))
5803       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5804     // We can only walk across public inheritance edges.
5805     if (PathLength > (int)DynType->PathLength &&
5806         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5807                            Class))
5808       return RuntimeCheckFailed(nullptr);
5809   }
5810 
5811   // Runtime check, phase 2:
5812   //   Search the dynamic type for an unambiguous public base of type C.
5813   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5814                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5815   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5816       Paths.front().Access == AS_public) {
5817     // Downcast to the dynamic type...
5818     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5819       return false;
5820     // ... then upcast to the chosen base class subobject.
5821     for (CXXBasePathElement &Elem : Paths.front())
5822       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5823         return false;
5824     return true;
5825   }
5826 
5827   // Otherwise, the runtime check fails.
5828   return RuntimeCheckFailed(&Paths);
5829 }
5830 
5831 namespace {
5832 struct StartLifetimeOfUnionMemberHandler {
5833   EvalInfo &Info;
5834   const Expr *LHSExpr;
5835   const FieldDecl *Field;
5836   bool DuringInit;
5837   bool Failed = false;
5838   static const AccessKinds AccessKind = AK_Assign;
5839 
5840   typedef bool result_type;
failed__anone93968c61211::StartLifetimeOfUnionMemberHandler5841   bool failed() { return Failed; }
found__anone93968c61211::StartLifetimeOfUnionMemberHandler5842   bool found(APValue &Subobj, QualType SubobjType) {
5843     // We are supposed to perform no initialization but begin the lifetime of
5844     // the object. We interpret that as meaning to do what default
5845     // initialization of the object would do if all constructors involved were
5846     // trivial:
5847     //  * All base, non-variant member, and array element subobjects' lifetimes
5848     //    begin
5849     //  * No variant members' lifetimes begin
5850     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5851     assert(SubobjType->isUnionType());
5852     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5853       // This union member is already active. If it's also in-lifetime, there's
5854       // nothing to do.
5855       if (Subobj.getUnionValue().hasValue())
5856         return true;
5857     } else if (DuringInit) {
5858       // We're currently in the process of initializing a different union
5859       // member.  If we carried on, that initialization would attempt to
5860       // store to an inactive union member, resulting in undefined behavior.
5861       Info.FFDiag(LHSExpr,
5862                   diag::note_constexpr_union_member_change_during_init);
5863       return false;
5864     }
5865     APValue Result;
5866     Failed = !getDefaultInitValue(Field->getType(), Result);
5867     Subobj.setUnion(Field, Result);
5868     return true;
5869   }
found__anone93968c61211::StartLifetimeOfUnionMemberHandler5870   bool found(APSInt &Value, QualType SubobjType) {
5871     llvm_unreachable("wrong value kind for union object");
5872   }
found__anone93968c61211::StartLifetimeOfUnionMemberHandler5873   bool found(APFloat &Value, QualType SubobjType) {
5874     llvm_unreachable("wrong value kind for union object");
5875   }
5876 };
5877 } // end anonymous namespace
5878 
5879 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5880 
5881 /// Handle a builtin simple-assignment or a call to a trivial assignment
5882 /// operator whose left-hand side might involve a union member access. If it
5883 /// does, implicitly start the lifetime of any accessed union elements per
5884 /// C++20 [class.union]5.
HandleUnionActiveMemberChange(EvalInfo & Info,const Expr * LHSExpr,const LValue & LHS)5885 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5886                                           const LValue &LHS) {
5887   if (LHS.InvalidBase || LHS.Designator.Invalid)
5888     return false;
5889 
5890   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5891   // C++ [class.union]p5:
5892   //   define the set S(E) of subexpressions of E as follows:
5893   unsigned PathLength = LHS.Designator.Entries.size();
5894   for (const Expr *E = LHSExpr; E != nullptr;) {
5895     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5896     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5897       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5898       // Note that we can't implicitly start the lifetime of a reference,
5899       // so we don't need to proceed any further if we reach one.
5900       if (!FD || FD->getType()->isReferenceType())
5901         break;
5902 
5903       //    ... and also contains A.B if B names a union member ...
5904       if (FD->getParent()->isUnion()) {
5905         //    ... of a non-class, non-array type, or of a class type with a
5906         //    trivial default constructor that is not deleted, or an array of
5907         //    such types.
5908         auto *RD =
5909             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5910         if (!RD || RD->hasTrivialDefaultConstructor())
5911           UnionPathLengths.push_back({PathLength - 1, FD});
5912       }
5913 
5914       E = ME->getBase();
5915       --PathLength;
5916       assert(declaresSameEntity(FD,
5917                                 LHS.Designator.Entries[PathLength]
5918                                     .getAsBaseOrMember().getPointer()));
5919 
5920       //   -- If E is of the form A[B] and is interpreted as a built-in array
5921       //      subscripting operator, S(E) is [S(the array operand, if any)].
5922     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5923       // Step over an ArrayToPointerDecay implicit cast.
5924       auto *Base = ASE->getBase()->IgnoreImplicit();
5925       if (!Base->getType()->isArrayType())
5926         break;
5927 
5928       E = Base;
5929       --PathLength;
5930 
5931     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5932       // Step over a derived-to-base conversion.
5933       E = ICE->getSubExpr();
5934       if (ICE->getCastKind() == CK_NoOp)
5935         continue;
5936       if (ICE->getCastKind() != CK_DerivedToBase &&
5937           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5938         break;
5939       // Walk path backwards as we walk up from the base to the derived class.
5940       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5941         --PathLength;
5942         (void)Elt;
5943         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5944                                   LHS.Designator.Entries[PathLength]
5945                                       .getAsBaseOrMember().getPointer()));
5946       }
5947 
5948     //   -- Otherwise, S(E) is empty.
5949     } else {
5950       break;
5951     }
5952   }
5953 
5954   // Common case: no unions' lifetimes are started.
5955   if (UnionPathLengths.empty())
5956     return true;
5957 
5958   //   if modification of X [would access an inactive union member], an object
5959   //   of the type of X is implicitly created
5960   CompleteObject Obj =
5961       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5962   if (!Obj)
5963     return false;
5964   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5965            llvm::reverse(UnionPathLengths)) {
5966     // Form a designator for the union object.
5967     SubobjectDesignator D = LHS.Designator;
5968     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5969 
5970     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5971                       ConstructionPhase::AfterBases;
5972     StartLifetimeOfUnionMemberHandler StartLifetime{
5973         Info, LHSExpr, LengthAndField.second, DuringInit};
5974     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5975       return false;
5976   }
5977 
5978   return true;
5979 }
5980 
EvaluateCallArg(const ParmVarDecl * PVD,const Expr * Arg,CallRef Call,EvalInfo & Info,bool NonNull=false)5981 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5982                             CallRef Call, EvalInfo &Info,
5983                             bool NonNull = false) {
5984   LValue LV;
5985   // Create the parameter slot and register its destruction. For a vararg
5986   // argument, create a temporary.
5987   // FIXME: For calling conventions that destroy parameters in the callee,
5988   // should we consider performing destruction when the function returns
5989   // instead?
5990   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5991                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5992                                                        ScopeKind::Call, LV);
5993   if (!EvaluateInPlace(V, Info, LV, Arg))
5994     return false;
5995 
5996   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
5997   // undefined behavior, so is non-constant.
5998   if (NonNull && V.isLValue() && V.isNullPointer()) {
5999     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6000     return false;
6001   }
6002 
6003   return true;
6004 }
6005 
6006 /// Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,CallRef Call,EvalInfo & Info,const FunctionDecl * Callee,bool RightToLeft=false)6007 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6008                          EvalInfo &Info, const FunctionDecl *Callee,
6009                          bool RightToLeft = false) {
6010   bool Success = true;
6011   llvm::SmallBitVector ForbiddenNullArgs;
6012   if (Callee->hasAttr<NonNullAttr>()) {
6013     ForbiddenNullArgs.resize(Args.size());
6014     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6015       if (!Attr->args_size()) {
6016         ForbiddenNullArgs.set();
6017         break;
6018       } else
6019         for (auto Idx : Attr->args()) {
6020           unsigned ASTIdx = Idx.getASTIndex();
6021           if (ASTIdx >= Args.size())
6022             continue;
6023           ForbiddenNullArgs[ASTIdx] = 1;
6024         }
6025     }
6026   }
6027   for (unsigned I = 0; I < Args.size(); I++) {
6028     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6029     const ParmVarDecl *PVD =
6030         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6031     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6032     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6033       // If we're checking for a potential constant expression, evaluate all
6034       // initializers even if some of them fail.
6035       if (!Info.noteFailure())
6036         return false;
6037       Success = false;
6038     }
6039   }
6040   return Success;
6041 }
6042 
6043 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6044 /// constructor or assignment operator.
handleTrivialCopy(EvalInfo & Info,const ParmVarDecl * Param,const Expr * E,APValue & Result,bool CopyObjectRepresentation)6045 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6046                               const Expr *E, APValue &Result,
6047                               bool CopyObjectRepresentation) {
6048   // Find the reference argument.
6049   CallStackFrame *Frame = Info.CurrentCall;
6050   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6051   if (!RefValue) {
6052     Info.FFDiag(E);
6053     return false;
6054   }
6055 
6056   // Copy out the contents of the RHS object.
6057   LValue RefLValue;
6058   RefLValue.setFrom(Info.Ctx, *RefValue);
6059   return handleLValueToRValueConversion(
6060       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6061       CopyObjectRepresentation);
6062 }
6063 
6064 /// Evaluate a function call.
HandleFunctionCall(SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,ArrayRef<const Expr * > Args,CallRef Call,const Stmt * Body,EvalInfo & Info,APValue & Result,const LValue * ResultSlot)6065 static bool HandleFunctionCall(SourceLocation CallLoc,
6066                                const FunctionDecl *Callee, const LValue *This,
6067                                ArrayRef<const Expr *> Args, CallRef Call,
6068                                const Stmt *Body, EvalInfo &Info,
6069                                APValue &Result, const LValue *ResultSlot) {
6070   if (!Info.CheckCallLimit(CallLoc))
6071     return false;
6072 
6073   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6074 
6075   // For a trivial copy or move assignment, perform an APValue copy. This is
6076   // essential for unions, where the operations performed by the assignment
6077   // operator cannot be represented as statements.
6078   //
6079   // Skip this for non-union classes with no fields; in that case, the defaulted
6080   // copy/move does not actually read the object.
6081   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6082   if (MD && MD->isDefaulted() &&
6083       (MD->getParent()->isUnion() ||
6084        (MD->isTrivial() &&
6085         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6086     assert(This &&
6087            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6088     APValue RHSValue;
6089     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6090                            MD->getParent()->isUnion()))
6091       return false;
6092     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6093         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6094       return false;
6095     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6096                           RHSValue))
6097       return false;
6098     This->moveInto(Result);
6099     return true;
6100   } else if (MD && isLambdaCallOperator(MD)) {
6101     // We're in a lambda; determine the lambda capture field maps unless we're
6102     // just constexpr checking a lambda's call operator. constexpr checking is
6103     // done before the captures have been added to the closure object (unless
6104     // we're inferring constexpr-ness), so we don't have access to them in this
6105     // case. But since we don't need the captures to constexpr check, we can
6106     // just ignore them.
6107     if (!Info.checkingPotentialConstantExpression())
6108       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6109                                         Frame.LambdaThisCaptureField);
6110   }
6111 
6112   StmtResult Ret = {Result, ResultSlot};
6113   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6114   if (ESR == ESR_Succeeded) {
6115     if (Callee->getReturnType()->isVoidType())
6116       return true;
6117     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6118   }
6119   return ESR == ESR_Returned;
6120 }
6121 
6122 /// Evaluate a constructor call.
HandleConstructorCall(const Expr * E,const LValue & This,CallRef Call,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6123 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6124                                   CallRef Call,
6125                                   const CXXConstructorDecl *Definition,
6126                                   EvalInfo &Info, APValue &Result) {
6127   SourceLocation CallLoc = E->getExprLoc();
6128   if (!Info.CheckCallLimit(CallLoc))
6129     return false;
6130 
6131   const CXXRecordDecl *RD = Definition->getParent();
6132   if (RD->getNumVBases()) {
6133     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6134     return false;
6135   }
6136 
6137   EvalInfo::EvaluatingConstructorRAII EvalObj(
6138       Info,
6139       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6140       RD->getNumBases());
6141   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6142 
6143   // FIXME: Creating an APValue just to hold a nonexistent return value is
6144   // wasteful.
6145   APValue RetVal;
6146   StmtResult Ret = {RetVal, nullptr};
6147 
6148   // If it's a delegating constructor, delegate.
6149   if (Definition->isDelegatingConstructor()) {
6150     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6151     if ((*I)->getInit()->isValueDependent()) {
6152       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6153         return false;
6154     } else {
6155       FullExpressionRAII InitScope(Info);
6156       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6157           !InitScope.destroy())
6158         return false;
6159     }
6160     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6161   }
6162 
6163   // For a trivial copy or move constructor, perform an APValue copy. This is
6164   // essential for unions (or classes with anonymous union members), where the
6165   // operations performed by the constructor cannot be represented by
6166   // ctor-initializers.
6167   //
6168   // Skip this for empty non-union classes; we should not perform an
6169   // lvalue-to-rvalue conversion on them because their copy constructor does not
6170   // actually read them.
6171   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6172       (Definition->getParent()->isUnion() ||
6173        (Definition->isTrivial() &&
6174         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6175     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6176                              Definition->getParent()->isUnion());
6177   }
6178 
6179   // Reserve space for the struct members.
6180   if (!Result.hasValue()) {
6181     if (!RD->isUnion())
6182       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6183                        std::distance(RD->field_begin(), RD->field_end()));
6184     else
6185       // A union starts with no active member.
6186       Result = APValue((const FieldDecl*)nullptr);
6187   }
6188 
6189   if (RD->isInvalidDecl()) return false;
6190   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6191 
6192   // A scope for temporaries lifetime-extended by reference members.
6193   BlockScopeRAII LifetimeExtendedScope(Info);
6194 
6195   bool Success = true;
6196   unsigned BasesSeen = 0;
6197 #ifndef NDEBUG
6198   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6199 #endif
6200   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6201   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6202     // We might be initializing the same field again if this is an indirect
6203     // field initialization.
6204     if (FieldIt == RD->field_end() ||
6205         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6206       assert(Indirect && "fields out of order?");
6207       return;
6208     }
6209 
6210     // Default-initialize any fields with no explicit initializer.
6211     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6212       assert(FieldIt != RD->field_end() && "missing field?");
6213       if (!FieldIt->isUnnamedBitfield())
6214         Success &= getDefaultInitValue(
6215             FieldIt->getType(),
6216             Result.getStructField(FieldIt->getFieldIndex()));
6217     }
6218     ++FieldIt;
6219   };
6220   for (const auto *I : Definition->inits()) {
6221     LValue Subobject = This;
6222     LValue SubobjectParent = This;
6223     APValue *Value = &Result;
6224 
6225     // Determine the subobject to initialize.
6226     FieldDecl *FD = nullptr;
6227     if (I->isBaseInitializer()) {
6228       QualType BaseType(I->getBaseClass(), 0);
6229 #ifndef NDEBUG
6230       // Non-virtual base classes are initialized in the order in the class
6231       // definition. We have already checked for virtual base classes.
6232       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6233       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6234              "base class initializers not in expected order");
6235       ++BaseIt;
6236 #endif
6237       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6238                                   BaseType->getAsCXXRecordDecl(), &Layout))
6239         return false;
6240       Value = &Result.getStructBase(BasesSeen++);
6241     } else if ((FD = I->getMember())) {
6242       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6243         return false;
6244       if (RD->isUnion()) {
6245         Result = APValue(FD);
6246         Value = &Result.getUnionValue();
6247       } else {
6248         SkipToField(FD, false);
6249         Value = &Result.getStructField(FD->getFieldIndex());
6250       }
6251     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6252       // Walk the indirect field decl's chain to find the object to initialize,
6253       // and make sure we've initialized every step along it.
6254       auto IndirectFieldChain = IFD->chain();
6255       for (auto *C : IndirectFieldChain) {
6256         FD = cast<FieldDecl>(C);
6257         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6258         // Switch the union field if it differs. This happens if we had
6259         // preceding zero-initialization, and we're now initializing a union
6260         // subobject other than the first.
6261         // FIXME: In this case, the values of the other subobjects are
6262         // specified, since zero-initialization sets all padding bits to zero.
6263         if (!Value->hasValue() ||
6264             (Value->isUnion() && Value->getUnionField() != FD)) {
6265           if (CD->isUnion())
6266             *Value = APValue(FD);
6267           else
6268             // FIXME: This immediately starts the lifetime of all members of
6269             // an anonymous struct. It would be preferable to strictly start
6270             // member lifetime in initialization order.
6271             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6272         }
6273         // Store Subobject as its parent before updating it for the last element
6274         // in the chain.
6275         if (C == IndirectFieldChain.back())
6276           SubobjectParent = Subobject;
6277         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6278           return false;
6279         if (CD->isUnion())
6280           Value = &Value->getUnionValue();
6281         else {
6282           if (C == IndirectFieldChain.front() && !RD->isUnion())
6283             SkipToField(FD, true);
6284           Value = &Value->getStructField(FD->getFieldIndex());
6285         }
6286       }
6287     } else {
6288       llvm_unreachable("unknown base initializer kind");
6289     }
6290 
6291     // Need to override This for implicit field initializers as in this case
6292     // This refers to innermost anonymous struct/union containing initializer,
6293     // not to currently constructed class.
6294     const Expr *Init = I->getInit();
6295     if (Init->isValueDependent()) {
6296       if (!EvaluateDependentExpr(Init, Info))
6297         return false;
6298     } else {
6299       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6300                                     isa<CXXDefaultInitExpr>(Init));
6301       FullExpressionRAII InitScope(Info);
6302       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6303           (FD && FD->isBitField() &&
6304            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6305         // If we're checking for a potential constant expression, evaluate all
6306         // initializers even if some of them fail.
6307         if (!Info.noteFailure())
6308           return false;
6309         Success = false;
6310       }
6311     }
6312 
6313     // This is the point at which the dynamic type of the object becomes this
6314     // class type.
6315     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6316       EvalObj.finishedConstructingBases();
6317   }
6318 
6319   // Default-initialize any remaining fields.
6320   if (!RD->isUnion()) {
6321     for (; FieldIt != RD->field_end(); ++FieldIt) {
6322       if (!FieldIt->isUnnamedBitfield())
6323         Success &= getDefaultInitValue(
6324             FieldIt->getType(),
6325             Result.getStructField(FieldIt->getFieldIndex()));
6326     }
6327   }
6328 
6329   EvalObj.finishedConstructingFields();
6330 
6331   return Success &&
6332          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6333          LifetimeExtendedScope.destroy();
6334 }
6335 
HandleConstructorCall(const Expr * E,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6336 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6337                                   ArrayRef<const Expr*> Args,
6338                                   const CXXConstructorDecl *Definition,
6339                                   EvalInfo &Info, APValue &Result) {
6340   CallScopeRAII CallScope(Info);
6341   CallRef Call = Info.CurrentCall->createCall(Definition);
6342   if (!EvaluateArgs(Args, Call, Info, Definition))
6343     return false;
6344 
6345   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6346          CallScope.destroy();
6347 }
6348 
HandleDestructionImpl(EvalInfo & Info,SourceLocation CallLoc,const LValue & This,APValue & Value,QualType T)6349 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6350                                   const LValue &This, APValue &Value,
6351                                   QualType T) {
6352   // Objects can only be destroyed while they're within their lifetimes.
6353   // FIXME: We have no representation for whether an object of type nullptr_t
6354   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6355   // as indeterminate instead?
6356   if (Value.isAbsent() && !T->isNullPtrType()) {
6357     APValue Printable;
6358     This.moveInto(Printable);
6359     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6360       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6361     return false;
6362   }
6363 
6364   // Invent an expression for location purposes.
6365   // FIXME: We shouldn't need to do this.
6366   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6367 
6368   // For arrays, destroy elements right-to-left.
6369   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6370     uint64_t Size = CAT->getSize().getZExtValue();
6371     QualType ElemT = CAT->getElementType();
6372 
6373     LValue ElemLV = This;
6374     ElemLV.addArray(Info, &LocE, CAT);
6375     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6376       return false;
6377 
6378     // Ensure that we have actual array elements available to destroy; the
6379     // destructors might mutate the value, so we can't run them on the array
6380     // filler.
6381     if (Size && Size > Value.getArrayInitializedElts())
6382       expandArray(Value, Value.getArraySize() - 1);
6383 
6384     for (; Size != 0; --Size) {
6385       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6386       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6387           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6388         return false;
6389     }
6390 
6391     // End the lifetime of this array now.
6392     Value = APValue();
6393     return true;
6394   }
6395 
6396   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6397   if (!RD) {
6398     if (T.isDestructedType()) {
6399       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6400       return false;
6401     }
6402 
6403     Value = APValue();
6404     return true;
6405   }
6406 
6407   if (RD->getNumVBases()) {
6408     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6409     return false;
6410   }
6411 
6412   const CXXDestructorDecl *DD = RD->getDestructor();
6413   if (!DD && !RD->hasTrivialDestructor()) {
6414     Info.FFDiag(CallLoc);
6415     return false;
6416   }
6417 
6418   if (!DD || DD->isTrivial() ||
6419       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6420     // A trivial destructor just ends the lifetime of the object. Check for
6421     // this case before checking for a body, because we might not bother
6422     // building a body for a trivial destructor. Note that it doesn't matter
6423     // whether the destructor is constexpr in this case; all trivial
6424     // destructors are constexpr.
6425     //
6426     // If an anonymous union would be destroyed, some enclosing destructor must
6427     // have been explicitly defined, and the anonymous union destruction should
6428     // have no effect.
6429     Value = APValue();
6430     return true;
6431   }
6432 
6433   if (!Info.CheckCallLimit(CallLoc))
6434     return false;
6435 
6436   const FunctionDecl *Definition = nullptr;
6437   const Stmt *Body = DD->getBody(Definition);
6438 
6439   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6440     return false;
6441 
6442   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6443 
6444   // We're now in the period of destruction of this object.
6445   unsigned BasesLeft = RD->getNumBases();
6446   EvalInfo::EvaluatingDestructorRAII EvalObj(
6447       Info,
6448       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6449   if (!EvalObj.DidInsert) {
6450     // C++2a [class.dtor]p19:
6451     //   the behavior is undefined if the destructor is invoked for an object
6452     //   whose lifetime has ended
6453     // (Note that formally the lifetime ends when the period of destruction
6454     // begins, even though certain uses of the object remain valid until the
6455     // period of destruction ends.)
6456     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6457     return false;
6458   }
6459 
6460   // FIXME: Creating an APValue just to hold a nonexistent return value is
6461   // wasteful.
6462   APValue RetVal;
6463   StmtResult Ret = {RetVal, nullptr};
6464   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6465     return false;
6466 
6467   // A union destructor does not implicitly destroy its members.
6468   if (RD->isUnion())
6469     return true;
6470 
6471   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6472 
6473   // We don't have a good way to iterate fields in reverse, so collect all the
6474   // fields first and then walk them backwards.
6475   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6476   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6477     if (FD->isUnnamedBitfield())
6478       continue;
6479 
6480     LValue Subobject = This;
6481     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6482       return false;
6483 
6484     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6485     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6486                                FD->getType()))
6487       return false;
6488   }
6489 
6490   if (BasesLeft != 0)
6491     EvalObj.startedDestroyingBases();
6492 
6493   // Destroy base classes in reverse order.
6494   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6495     --BasesLeft;
6496 
6497     QualType BaseType = Base.getType();
6498     LValue Subobject = This;
6499     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6500                                 BaseType->getAsCXXRecordDecl(), &Layout))
6501       return false;
6502 
6503     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6504     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6505                                BaseType))
6506       return false;
6507   }
6508   assert(BasesLeft == 0 && "NumBases was wrong?");
6509 
6510   // The period of destruction ends now. The object is gone.
6511   Value = APValue();
6512   return true;
6513 }
6514 
6515 namespace {
6516 struct DestroyObjectHandler {
6517   EvalInfo &Info;
6518   const Expr *E;
6519   const LValue &This;
6520   const AccessKinds AccessKind;
6521 
6522   typedef bool result_type;
failed__anone93968c61411::DestroyObjectHandler6523   bool failed() { return false; }
found__anone93968c61411::DestroyObjectHandler6524   bool found(APValue &Subobj, QualType SubobjType) {
6525     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6526                                  SubobjType);
6527   }
found__anone93968c61411::DestroyObjectHandler6528   bool found(APSInt &Value, QualType SubobjType) {
6529     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6530     return false;
6531   }
found__anone93968c61411::DestroyObjectHandler6532   bool found(APFloat &Value, QualType SubobjType) {
6533     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6534     return false;
6535   }
6536 };
6537 }
6538 
6539 /// Perform a destructor or pseudo-destructor call on the given object, which
6540 /// might in general not be a complete object.
HandleDestruction(EvalInfo & Info,const Expr * E,const LValue & This,QualType ThisType)6541 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6542                               const LValue &This, QualType ThisType) {
6543   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6544   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6545   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6546 }
6547 
6548 /// Destroy and end the lifetime of the given complete object.
HandleDestruction(EvalInfo & Info,SourceLocation Loc,APValue::LValueBase LVBase,APValue & Value,QualType T)6549 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6550                               APValue::LValueBase LVBase, APValue &Value,
6551                               QualType T) {
6552   // If we've had an unmodeled side-effect, we can't rely on mutable state
6553   // (such as the object we're about to destroy) being correct.
6554   if (Info.EvalStatus.HasSideEffects)
6555     return false;
6556 
6557   LValue LV;
6558   LV.set({LVBase});
6559   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6560 }
6561 
6562 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
HandleOperatorNewCall(EvalInfo & Info,const CallExpr * E,LValue & Result)6563 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6564                                   LValue &Result) {
6565   if (Info.checkingPotentialConstantExpression() ||
6566       Info.SpeculativeEvaluationDepth)
6567     return false;
6568 
6569   // This is permitted only within a call to std::allocator<T>::allocate.
6570   auto Caller = Info.getStdAllocatorCaller("allocate");
6571   if (!Caller) {
6572     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6573                                      ? diag::note_constexpr_new_untyped
6574                                      : diag::note_constexpr_new);
6575     return false;
6576   }
6577 
6578   QualType ElemType = Caller.ElemType;
6579   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6580     Info.FFDiag(E->getExprLoc(),
6581                 diag::note_constexpr_new_not_complete_object_type)
6582         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6583     return false;
6584   }
6585 
6586   APSInt ByteSize;
6587   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6588     return false;
6589   bool IsNothrow = false;
6590   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6591     EvaluateIgnoredValue(Info, E->getArg(I));
6592     IsNothrow |= E->getType()->isNothrowT();
6593   }
6594 
6595   CharUnits ElemSize;
6596   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6597     return false;
6598   APInt Size, Remainder;
6599   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6600   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6601   if (Remainder != 0) {
6602     // This likely indicates a bug in the implementation of 'std::allocator'.
6603     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6604         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6605     return false;
6606   }
6607 
6608   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6609     if (IsNothrow) {
6610       Result.setNull(Info.Ctx, E->getType());
6611       return true;
6612     }
6613 
6614     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6615     return false;
6616   }
6617 
6618   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6619                                                      ArrayType::Normal, 0);
6620   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6621   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6622   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6623   return true;
6624 }
6625 
hasVirtualDestructor(QualType T)6626 static bool hasVirtualDestructor(QualType T) {
6627   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6628     if (CXXDestructorDecl *DD = RD->getDestructor())
6629       return DD->isVirtual();
6630   return false;
6631 }
6632 
getVirtualOperatorDelete(QualType T)6633 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6634   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6635     if (CXXDestructorDecl *DD = RD->getDestructor())
6636       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6637   return nullptr;
6638 }
6639 
6640 /// Check that the given object is a suitable pointer to a heap allocation that
6641 /// still exists and is of the right kind for the purpose of a deletion.
6642 ///
6643 /// On success, returns the heap allocation to deallocate. On failure, produces
6644 /// a diagnostic and returns None.
CheckDeleteKind(EvalInfo & Info,const Expr * E,const LValue & Pointer,DynAlloc::Kind DeallocKind)6645 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6646                                             const LValue &Pointer,
6647                                             DynAlloc::Kind DeallocKind) {
6648   auto PointerAsString = [&] {
6649     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6650   };
6651 
6652   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6653   if (!DA) {
6654     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6655         << PointerAsString();
6656     if (Pointer.Base)
6657       NoteLValueLocation(Info, Pointer.Base);
6658     return None;
6659   }
6660 
6661   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6662   if (!Alloc) {
6663     Info.FFDiag(E, diag::note_constexpr_double_delete);
6664     return None;
6665   }
6666 
6667   QualType AllocType = Pointer.Base.getDynamicAllocType();
6668   if (DeallocKind != (*Alloc)->getKind()) {
6669     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6670         << DeallocKind << (*Alloc)->getKind() << AllocType;
6671     NoteLValueLocation(Info, Pointer.Base);
6672     return None;
6673   }
6674 
6675   bool Subobject = false;
6676   if (DeallocKind == DynAlloc::New) {
6677     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6678                 Pointer.Designator.isOnePastTheEnd();
6679   } else {
6680     Subobject = Pointer.Designator.Entries.size() != 1 ||
6681                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6682   }
6683   if (Subobject) {
6684     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6685         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6686     return None;
6687   }
6688 
6689   return Alloc;
6690 }
6691 
6692 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
HandleOperatorDeleteCall(EvalInfo & Info,const CallExpr * E)6693 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6694   if (Info.checkingPotentialConstantExpression() ||
6695       Info.SpeculativeEvaluationDepth)
6696     return false;
6697 
6698   // This is permitted only within a call to std::allocator<T>::deallocate.
6699   if (!Info.getStdAllocatorCaller("deallocate")) {
6700     Info.FFDiag(E->getExprLoc());
6701     return true;
6702   }
6703 
6704   LValue Pointer;
6705   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6706     return false;
6707   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6708     EvaluateIgnoredValue(Info, E->getArg(I));
6709 
6710   if (Pointer.Designator.Invalid)
6711     return false;
6712 
6713   // Deleting a null pointer has no effect.
6714   if (Pointer.isNullPointer())
6715     return true;
6716 
6717   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6718     return false;
6719 
6720   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6721   return true;
6722 }
6723 
6724 //===----------------------------------------------------------------------===//
6725 // Generic Evaluation
6726 //===----------------------------------------------------------------------===//
6727 namespace {
6728 
6729 class BitCastBuffer {
6730   // FIXME: We're going to need bit-level granularity when we support
6731   // bit-fields.
6732   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6733   // we don't support a host or target where that is the case. Still, we should
6734   // use a more generic type in case we ever do.
6735   SmallVector<Optional<unsigned char>, 32> Bytes;
6736 
6737   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6738                 "Need at least 8 bit unsigned char");
6739 
6740   bool TargetIsLittleEndian;
6741 
6742 public:
BitCastBuffer(CharUnits Width,bool TargetIsLittleEndian)6743   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6744       : Bytes(Width.getQuantity()),
6745         TargetIsLittleEndian(TargetIsLittleEndian) {}
6746 
6747   LLVM_NODISCARD
readObject(CharUnits Offset,CharUnits Width,SmallVectorImpl<unsigned char> & Output) const6748   bool readObject(CharUnits Offset, CharUnits Width,
6749                   SmallVectorImpl<unsigned char> &Output) const {
6750     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6751       // If a byte of an integer is uninitialized, then the whole integer is
6752       // uninitalized.
6753       if (!Bytes[I.getQuantity()])
6754         return false;
6755       Output.push_back(*Bytes[I.getQuantity()]);
6756     }
6757     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6758       std::reverse(Output.begin(), Output.end());
6759     return true;
6760   }
6761 
writeObject(CharUnits Offset,SmallVectorImpl<unsigned char> & Input)6762   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6763     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6764       std::reverse(Input.begin(), Input.end());
6765 
6766     size_t Index = 0;
6767     for (unsigned char Byte : Input) {
6768       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6769       Bytes[Offset.getQuantity() + Index] = Byte;
6770       ++Index;
6771     }
6772   }
6773 
size()6774   size_t size() { return Bytes.size(); }
6775 };
6776 
6777 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6778 /// target would represent the value at runtime.
6779 class APValueToBufferConverter {
6780   EvalInfo &Info;
6781   BitCastBuffer Buffer;
6782   const CastExpr *BCE;
6783 
APValueToBufferConverter(EvalInfo & Info,CharUnits ObjectWidth,const CastExpr * BCE)6784   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6785                            const CastExpr *BCE)
6786       : Info(Info),
6787         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6788         BCE(BCE) {}
6789 
visit(const APValue & Val,QualType Ty)6790   bool visit(const APValue &Val, QualType Ty) {
6791     return visit(Val, Ty, CharUnits::fromQuantity(0));
6792   }
6793 
6794   // Write out Val with type Ty into Buffer starting at Offset.
visit(const APValue & Val,QualType Ty,CharUnits Offset)6795   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6796     assert((size_t)Offset.getQuantity() <= Buffer.size());
6797 
6798     // As a special case, nullptr_t has an indeterminate value.
6799     if (Ty->isNullPtrType())
6800       return true;
6801 
6802     // Dig through Src to find the byte at SrcOffset.
6803     switch (Val.getKind()) {
6804     case APValue::Indeterminate:
6805     case APValue::None:
6806       return true;
6807 
6808     case APValue::Int:
6809       return visitInt(Val.getInt(), Ty, Offset);
6810     case APValue::Float:
6811       return visitFloat(Val.getFloat(), Ty, Offset);
6812     case APValue::Array:
6813       return visitArray(Val, Ty, Offset);
6814     case APValue::Struct:
6815       return visitRecord(Val, Ty, Offset);
6816 
6817     case APValue::ComplexInt:
6818     case APValue::ComplexFloat:
6819     case APValue::Vector:
6820     case APValue::FixedPoint:
6821       // FIXME: We should support these.
6822 
6823     case APValue::Union:
6824     case APValue::MemberPointer:
6825     case APValue::AddrLabelDiff: {
6826       Info.FFDiag(BCE->getBeginLoc(),
6827                   diag::note_constexpr_bit_cast_unsupported_type)
6828           << Ty;
6829       return false;
6830     }
6831 
6832     case APValue::LValue:
6833       llvm_unreachable("LValue subobject in bit_cast?");
6834     }
6835     llvm_unreachable("Unhandled APValue::ValueKind");
6836   }
6837 
visitRecord(const APValue & Val,QualType Ty,CharUnits Offset)6838   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6839     const RecordDecl *RD = Ty->getAsRecordDecl();
6840     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6841 
6842     // Visit the base classes.
6843     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6844       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6845         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6846         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6847 
6848         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6849                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6850           return false;
6851       }
6852     }
6853 
6854     // Visit the fields.
6855     unsigned FieldIdx = 0;
6856     for (FieldDecl *FD : RD->fields()) {
6857       if (FD->isBitField()) {
6858         Info.FFDiag(BCE->getBeginLoc(),
6859                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6860         return false;
6861       }
6862 
6863       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6864 
6865       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6866              "only bit-fields can have sub-char alignment");
6867       CharUnits FieldOffset =
6868           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6869       QualType FieldTy = FD->getType();
6870       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6871         return false;
6872       ++FieldIdx;
6873     }
6874 
6875     return true;
6876   }
6877 
visitArray(const APValue & Val,QualType Ty,CharUnits Offset)6878   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6879     const auto *CAT =
6880         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6881     if (!CAT)
6882       return false;
6883 
6884     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6885     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6886     unsigned ArraySize = Val.getArraySize();
6887     // First, initialize the initialized elements.
6888     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6889       const APValue &SubObj = Val.getArrayInitializedElt(I);
6890       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6891         return false;
6892     }
6893 
6894     // Next, initialize the rest of the array using the filler.
6895     if (Val.hasArrayFiller()) {
6896       const APValue &Filler = Val.getArrayFiller();
6897       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6898         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6899           return false;
6900       }
6901     }
6902 
6903     return true;
6904   }
6905 
visitInt(const APSInt & Val,QualType Ty,CharUnits Offset)6906   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6907     APSInt AdjustedVal = Val;
6908     unsigned Width = AdjustedVal.getBitWidth();
6909     if (Ty->isBooleanType()) {
6910       Width = Info.Ctx.getTypeSize(Ty);
6911       AdjustedVal = AdjustedVal.extend(Width);
6912     }
6913 
6914     SmallVector<unsigned char, 8> Bytes(Width / 8);
6915     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6916     Buffer.writeObject(Offset, Bytes);
6917     return true;
6918   }
6919 
visitFloat(const APFloat & Val,QualType Ty,CharUnits Offset)6920   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6921     APSInt AsInt(Val.bitcastToAPInt());
6922     return visitInt(AsInt, Ty, Offset);
6923   }
6924 
6925 public:
convert(EvalInfo & Info,const APValue & Src,const CastExpr * BCE)6926   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6927                                          const CastExpr *BCE) {
6928     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6929     APValueToBufferConverter Converter(Info, DstSize, BCE);
6930     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6931       return None;
6932     return Converter.Buffer;
6933   }
6934 };
6935 
6936 /// Write an BitCastBuffer into an APValue.
6937 class BufferToAPValueConverter {
6938   EvalInfo &Info;
6939   const BitCastBuffer &Buffer;
6940   const CastExpr *BCE;
6941 
BufferToAPValueConverter(EvalInfo & Info,const BitCastBuffer & Buffer,const CastExpr * BCE)6942   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6943                            const CastExpr *BCE)
6944       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6945 
6946   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6947   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6948   // Ideally this will be unreachable.
unsupportedType(QualType Ty)6949   llvm::NoneType unsupportedType(QualType Ty) {
6950     Info.FFDiag(BCE->getBeginLoc(),
6951                 diag::note_constexpr_bit_cast_unsupported_type)
6952         << Ty;
6953     return None;
6954   }
6955 
unrepresentableValue(QualType Ty,const APSInt & Val)6956   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6957     Info.FFDiag(BCE->getBeginLoc(),
6958                 diag::note_constexpr_bit_cast_unrepresentable_value)
6959         << Ty << Val.toString(/*Radix=*/10);
6960     return None;
6961   }
6962 
visit(const BuiltinType * T,CharUnits Offset,const EnumType * EnumSugar=nullptr)6963   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6964                           const EnumType *EnumSugar = nullptr) {
6965     if (T->isNullPtrType()) {
6966       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6967       return APValue((Expr *)nullptr,
6968                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6969                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6970     }
6971 
6972     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6973 
6974     // Work around floating point types that contain unused padding bytes. This
6975     // is really just `long double` on x86, which is the only fundamental type
6976     // with padding bytes.
6977     if (T->isRealFloatingType()) {
6978       const llvm::fltSemantics &Semantics =
6979           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6980       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6981       assert(NumBits % 8 == 0);
6982       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6983       if (NumBytes != SizeOf)
6984         SizeOf = NumBytes;
6985     }
6986 
6987     SmallVector<uint8_t, 8> Bytes;
6988     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6989       // If this is std::byte or unsigned char, then its okay to store an
6990       // indeterminate value.
6991       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6992       bool IsUChar =
6993           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6994                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6995       if (!IsStdByte && !IsUChar) {
6996         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6997         Info.FFDiag(BCE->getExprLoc(),
6998                     diag::note_constexpr_bit_cast_indet_dest)
6999             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7000         return None;
7001       }
7002 
7003       return APValue::IndeterminateValue();
7004     }
7005 
7006     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7007     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7008 
7009     if (T->isIntegralOrEnumerationType()) {
7010       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7011 
7012       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7013       if (IntWidth != Val.getBitWidth()) {
7014         APSInt Truncated = Val.trunc(IntWidth);
7015         if (Truncated.extend(Val.getBitWidth()) != Val)
7016           return unrepresentableValue(QualType(T, 0), Val);
7017         Val = Truncated;
7018       }
7019 
7020       return APValue(Val);
7021     }
7022 
7023     if (T->isRealFloatingType()) {
7024       const llvm::fltSemantics &Semantics =
7025           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7026       return APValue(APFloat(Semantics, Val));
7027     }
7028 
7029     return unsupportedType(QualType(T, 0));
7030   }
7031 
visit(const RecordType * RTy,CharUnits Offset)7032   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7033     const RecordDecl *RD = RTy->getAsRecordDecl();
7034     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7035 
7036     unsigned NumBases = 0;
7037     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7038       NumBases = CXXRD->getNumBases();
7039 
7040     APValue ResultVal(APValue::UninitStruct(), NumBases,
7041                       std::distance(RD->field_begin(), RD->field_end()));
7042 
7043     // Visit the base classes.
7044     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7045       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7046         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7047         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7048         if (BaseDecl->isEmpty() ||
7049             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7050           continue;
7051 
7052         Optional<APValue> SubObj = visitType(
7053             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7054         if (!SubObj)
7055           return None;
7056         ResultVal.getStructBase(I) = *SubObj;
7057       }
7058     }
7059 
7060     // Visit the fields.
7061     unsigned FieldIdx = 0;
7062     for (FieldDecl *FD : RD->fields()) {
7063       // FIXME: We don't currently support bit-fields. A lot of the logic for
7064       // this is in CodeGen, so we need to factor it around.
7065       if (FD->isBitField()) {
7066         Info.FFDiag(BCE->getBeginLoc(),
7067                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7068         return None;
7069       }
7070 
7071       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7072       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7073 
7074       CharUnits FieldOffset =
7075           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7076           Offset;
7077       QualType FieldTy = FD->getType();
7078       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7079       if (!SubObj)
7080         return None;
7081       ResultVal.getStructField(FieldIdx) = *SubObj;
7082       ++FieldIdx;
7083     }
7084 
7085     return ResultVal;
7086   }
7087 
visit(const EnumType * Ty,CharUnits Offset)7088   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7089     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7090     assert(!RepresentationType.isNull() &&
7091            "enum forward decl should be caught by Sema");
7092     const auto *AsBuiltin =
7093         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7094     // Recurse into the underlying type. Treat std::byte transparently as
7095     // unsigned char.
7096     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7097   }
7098 
visit(const ConstantArrayType * Ty,CharUnits Offset)7099   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7100     size_t Size = Ty->getSize().getLimitedValue();
7101     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7102 
7103     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7104     for (size_t I = 0; I != Size; ++I) {
7105       Optional<APValue> ElementValue =
7106           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7107       if (!ElementValue)
7108         return None;
7109       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7110     }
7111 
7112     return ArrayValue;
7113   }
7114 
visit(const Type * Ty,CharUnits Offset)7115   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7116     return unsupportedType(QualType(Ty, 0));
7117   }
7118 
visitType(QualType Ty,CharUnits Offset)7119   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7120     QualType Can = Ty.getCanonicalType();
7121 
7122     switch (Can->getTypeClass()) {
7123 #define TYPE(Class, Base)                                                      \
7124   case Type::Class:                                                            \
7125     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7126 #define ABSTRACT_TYPE(Class, Base)
7127 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7128   case Type::Class:                                                            \
7129     llvm_unreachable("non-canonical type should be impossible!");
7130 #define DEPENDENT_TYPE(Class, Base)                                            \
7131   case Type::Class:                                                            \
7132     llvm_unreachable(                                                          \
7133         "dependent types aren't supported in the constant evaluator!");
7134 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7135   case Type::Class:                                                            \
7136     llvm_unreachable("either dependent or not canonical!");
7137 #include "clang/AST/TypeNodes.inc"
7138     }
7139     llvm_unreachable("Unhandled Type::TypeClass");
7140   }
7141 
7142 public:
7143   // Pull out a full value of type DstType.
convert(EvalInfo & Info,BitCastBuffer & Buffer,const CastExpr * BCE)7144   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7145                                    const CastExpr *BCE) {
7146     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7147     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7148   }
7149 };
7150 
checkBitCastConstexprEligibilityType(SourceLocation Loc,QualType Ty,EvalInfo * Info,const ASTContext & Ctx,bool CheckingDest)7151 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7152                                                  QualType Ty, EvalInfo *Info,
7153                                                  const ASTContext &Ctx,
7154                                                  bool CheckingDest) {
7155   Ty = Ty.getCanonicalType();
7156 
7157   auto diag = [&](int Reason) {
7158     if (Info)
7159       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7160           << CheckingDest << (Reason == 4) << Reason;
7161     return false;
7162   };
7163   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7164     if (Info)
7165       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7166           << NoteTy << Construct << Ty;
7167     return false;
7168   };
7169 
7170   if (Ty->isUnionType())
7171     return diag(0);
7172   if (Ty->isPointerType())
7173     return diag(1);
7174   if (Ty->isMemberPointerType())
7175     return diag(2);
7176   if (Ty.isVolatileQualified())
7177     return diag(3);
7178 
7179   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7180     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7181       for (CXXBaseSpecifier &BS : CXXRD->bases())
7182         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7183                                                   CheckingDest))
7184           return note(1, BS.getType(), BS.getBeginLoc());
7185     }
7186     for (FieldDecl *FD : Record->fields()) {
7187       if (FD->getType()->isReferenceType())
7188         return diag(4);
7189       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7190                                                 CheckingDest))
7191         return note(0, FD->getType(), FD->getBeginLoc());
7192     }
7193   }
7194 
7195   if (Ty->isArrayType() &&
7196       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7197                                             Info, Ctx, CheckingDest))
7198     return false;
7199 
7200   return true;
7201 }
7202 
checkBitCastConstexprEligibility(EvalInfo * Info,const ASTContext & Ctx,const CastExpr * BCE)7203 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7204                                              const ASTContext &Ctx,
7205                                              const CastExpr *BCE) {
7206   bool DestOK = checkBitCastConstexprEligibilityType(
7207       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7208   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7209                                 BCE->getBeginLoc(),
7210                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7211   return SourceOK;
7212 }
7213 
handleLValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,APValue & SourceValue,const CastExpr * BCE)7214 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7215                                         APValue &SourceValue,
7216                                         const CastExpr *BCE) {
7217   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7218          "no host or target supports non 8-bit chars");
7219   assert(SourceValue.isLValue() &&
7220          "LValueToRValueBitcast requires an lvalue operand!");
7221 
7222   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7223     return false;
7224 
7225   LValue SourceLValue;
7226   APValue SourceRValue;
7227   SourceLValue.setFrom(Info.Ctx, SourceValue);
7228   if (!handleLValueToRValueConversion(
7229           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7230           SourceRValue, /*WantObjectRepresentation=*/true))
7231     return false;
7232 
7233   // Read out SourceValue into a char buffer.
7234   Optional<BitCastBuffer> Buffer =
7235       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7236   if (!Buffer)
7237     return false;
7238 
7239   // Write out the buffer into a new APValue.
7240   Optional<APValue> MaybeDestValue =
7241       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7242   if (!MaybeDestValue)
7243     return false;
7244 
7245   DestValue = std::move(*MaybeDestValue);
7246   return true;
7247 }
7248 
7249 template <class Derived>
7250 class ExprEvaluatorBase
7251   : public ConstStmtVisitor<Derived, bool> {
7252 private:
getDerived()7253   Derived &getDerived() { return static_cast<Derived&>(*this); }
DerivedSuccess(const APValue & V,const Expr * E)7254   bool DerivedSuccess(const APValue &V, const Expr *E) {
7255     return getDerived().Success(V, E);
7256   }
DerivedZeroInitialization(const Expr * E)7257   bool DerivedZeroInitialization(const Expr *E) {
7258     return getDerived().ZeroInitialization(E);
7259   }
7260 
7261   // Check whether a conditional operator with a non-constant condition is a
7262   // potential constant expression. If neither arm is a potential constant
7263   // expression, then the conditional operator is not either.
7264   template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)7265   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7266     assert(Info.checkingPotentialConstantExpression());
7267 
7268     // Speculatively evaluate both arms.
7269     SmallVector<PartialDiagnosticAt, 8> Diag;
7270     {
7271       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7272       StmtVisitorTy::Visit(E->getFalseExpr());
7273       if (Diag.empty())
7274         return;
7275     }
7276 
7277     {
7278       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7279       Diag.clear();
7280       StmtVisitorTy::Visit(E->getTrueExpr());
7281       if (Diag.empty())
7282         return;
7283     }
7284 
7285     Error(E, diag::note_constexpr_conditional_never_const);
7286   }
7287 
7288 
7289   template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)7290   bool HandleConditionalOperator(const ConditionalOperator *E) {
7291     bool BoolResult;
7292     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7293       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7294         CheckPotentialConstantConditional(E);
7295         return false;
7296       }
7297       if (Info.noteFailure()) {
7298         StmtVisitorTy::Visit(E->getTrueExpr());
7299         StmtVisitorTy::Visit(E->getFalseExpr());
7300       }
7301       return false;
7302     }
7303 
7304     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7305     return StmtVisitorTy::Visit(EvalExpr);
7306   }
7307 
7308 protected:
7309   EvalInfo &Info;
7310   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7311   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7312 
CCEDiag(const Expr * E,diag::kind D)7313   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7314     return Info.CCEDiag(E, D);
7315   }
7316 
ZeroInitialization(const Expr * E)7317   bool ZeroInitialization(const Expr *E) { return Error(E); }
7318 
7319 public:
ExprEvaluatorBase(EvalInfo & Info)7320   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7321 
getEvalInfo()7322   EvalInfo &getEvalInfo() { return Info; }
7323 
7324   /// Report an evaluation error. This should only be called when an error is
7325   /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)7326   bool Error(const Expr *E, diag::kind D) {
7327     Info.FFDiag(E, D);
7328     return false;
7329   }
Error(const Expr * E)7330   bool Error(const Expr *E) {
7331     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7332   }
7333 
VisitStmt(const Stmt *)7334   bool VisitStmt(const Stmt *) {
7335     llvm_unreachable("Expression evaluator should not be called on stmts");
7336   }
VisitExpr(const Expr * E)7337   bool VisitExpr(const Expr *E) {
7338     return Error(E);
7339   }
7340 
VisitConstantExpr(const ConstantExpr * E)7341   bool VisitConstantExpr(const ConstantExpr *E) {
7342     if (E->hasAPValueResult())
7343       return DerivedSuccess(E->getAPValueResult(), E);
7344 
7345     return StmtVisitorTy::Visit(E->getSubExpr());
7346   }
7347 
VisitParenExpr(const ParenExpr * E)7348   bool VisitParenExpr(const ParenExpr *E)
7349     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)7350   bool VisitUnaryExtension(const UnaryOperator *E)
7351     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)7352   bool VisitUnaryPlus(const UnaryOperator *E)
7353     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)7354   bool VisitChooseExpr(const ChooseExpr *E)
7355     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)7356   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7357     { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)7358   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7359     { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)7360   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7361     TempVersionRAII RAII(*Info.CurrentCall);
7362     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7363     return StmtVisitorTy::Visit(E->getExpr());
7364   }
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * E)7365   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7366     TempVersionRAII RAII(*Info.CurrentCall);
7367     // The initializer may not have been parsed yet, or might be erroneous.
7368     if (!E->getExpr())
7369       return Error(E);
7370     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7371     return StmtVisitorTy::Visit(E->getExpr());
7372   }
7373 
VisitExprWithCleanups(const ExprWithCleanups * E)7374   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7375     FullExpressionRAII Scope(Info);
7376     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7377   }
7378 
7379   // Temporaries are registered when created, so we don't care about
7380   // CXXBindTemporaryExpr.
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)7381   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7382     return StmtVisitorTy::Visit(E->getSubExpr());
7383   }
7384 
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)7385   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7386     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7387     return static_cast<Derived*>(this)->VisitCastExpr(E);
7388   }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)7389   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7390     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7391       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7392     return static_cast<Derived*>(this)->VisitCastExpr(E);
7393   }
VisitBuiltinBitCastExpr(const BuiltinBitCastExpr * E)7394   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7395     return static_cast<Derived*>(this)->VisitCastExpr(E);
7396   }
7397 
VisitBinaryOperator(const BinaryOperator * E)7398   bool VisitBinaryOperator(const BinaryOperator *E) {
7399     switch (E->getOpcode()) {
7400     default:
7401       return Error(E);
7402 
7403     case BO_Comma:
7404       VisitIgnoredValue(E->getLHS());
7405       return StmtVisitorTy::Visit(E->getRHS());
7406 
7407     case BO_PtrMemD:
7408     case BO_PtrMemI: {
7409       LValue Obj;
7410       if (!HandleMemberPointerAccess(Info, E, Obj))
7411         return false;
7412       APValue Result;
7413       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7414         return false;
7415       return DerivedSuccess(Result, E);
7416     }
7417     }
7418   }
7419 
VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator * E)7420   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7421     return StmtVisitorTy::Visit(E->getSemanticForm());
7422   }
7423 
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)7424   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7425     // Evaluate and cache the common expression. We treat it as a temporary,
7426     // even though it's not quite the same thing.
7427     LValue CommonLV;
7428     if (!Evaluate(Info.CurrentCall->createTemporary(
7429                       E->getOpaqueValue(),
7430                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7431                       ScopeKind::FullExpression, CommonLV),
7432                   Info, E->getCommon()))
7433       return false;
7434 
7435     return HandleConditionalOperator(E);
7436   }
7437 
VisitConditionalOperator(const ConditionalOperator * E)7438   bool VisitConditionalOperator(const ConditionalOperator *E) {
7439     bool IsBcpCall = false;
7440     // If the condition (ignoring parens) is a __builtin_constant_p call,
7441     // the result is a constant expression if it can be folded without
7442     // side-effects. This is an important GNU extension. See GCC PR38377
7443     // for discussion.
7444     if (const CallExpr *CallCE =
7445           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7446       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7447         IsBcpCall = true;
7448 
7449     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7450     // constant expression; we can't check whether it's potentially foldable.
7451     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7452     // it would return 'false' in this mode.
7453     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7454       return false;
7455 
7456     FoldConstant Fold(Info, IsBcpCall);
7457     if (!HandleConditionalOperator(E)) {
7458       Fold.keepDiagnostics();
7459       return false;
7460     }
7461 
7462     return true;
7463   }
7464 
VisitOpaqueValueExpr(const OpaqueValueExpr * E)7465   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7466     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7467       return DerivedSuccess(*Value, E);
7468 
7469     const Expr *Source = E->getSourceExpr();
7470     if (!Source)
7471       return Error(E);
7472     if (Source == E) { // sanity checking.
7473       assert(0 && "OpaqueValueExpr recursively refers to itself");
7474       return Error(E);
7475     }
7476     return StmtVisitorTy::Visit(Source);
7477   }
7478 
VisitPseudoObjectExpr(const PseudoObjectExpr * E)7479   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7480     for (const Expr *SemE : E->semantics()) {
7481       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7482         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7483         // result expression: there could be two different LValues that would
7484         // refer to the same object in that case, and we can't model that.
7485         if (SemE == E->getResultExpr())
7486           return Error(E);
7487 
7488         // Unique OVEs get evaluated if and when we encounter them when
7489         // emitting the rest of the semantic form, rather than eagerly.
7490         if (OVE->isUnique())
7491           continue;
7492 
7493         LValue LV;
7494         if (!Evaluate(Info.CurrentCall->createTemporary(
7495                           OVE, getStorageType(Info.Ctx, OVE),
7496                           ScopeKind::FullExpression, LV),
7497                       Info, OVE->getSourceExpr()))
7498           return false;
7499       } else if (SemE == E->getResultExpr()) {
7500         if (!StmtVisitorTy::Visit(SemE))
7501           return false;
7502       } else {
7503         if (!EvaluateIgnoredValue(Info, SemE))
7504           return false;
7505       }
7506     }
7507     return true;
7508   }
7509 
VisitCallExpr(const CallExpr * E)7510   bool VisitCallExpr(const CallExpr *E) {
7511     APValue Result;
7512     if (!handleCallExpr(E, Result, nullptr))
7513       return false;
7514     return DerivedSuccess(Result, E);
7515   }
7516 
handleCallExpr(const CallExpr * E,APValue & Result,const LValue * ResultSlot)7517   bool handleCallExpr(const CallExpr *E, APValue &Result,
7518                      const LValue *ResultSlot) {
7519     CallScopeRAII CallScope(Info);
7520 
7521     const Expr *Callee = E->getCallee()->IgnoreParens();
7522     QualType CalleeType = Callee->getType();
7523 
7524     const FunctionDecl *FD = nullptr;
7525     LValue *This = nullptr, ThisVal;
7526     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7527     bool HasQualifier = false;
7528 
7529     CallRef Call;
7530 
7531     // Extract function decl and 'this' pointer from the callee.
7532     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7533       const CXXMethodDecl *Member = nullptr;
7534       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7535         // Explicit bound member calls, such as x.f() or p->g();
7536         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7537           return false;
7538         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7539         if (!Member)
7540           return Error(Callee);
7541         This = &ThisVal;
7542         HasQualifier = ME->hasQualifier();
7543       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7544         // Indirect bound member calls ('.*' or '->*').
7545         const ValueDecl *D =
7546             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7547         if (!D)
7548           return false;
7549         Member = dyn_cast<CXXMethodDecl>(D);
7550         if (!Member)
7551           return Error(Callee);
7552         This = &ThisVal;
7553       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7554         if (!Info.getLangOpts().CPlusPlus20)
7555           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7556         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7557                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7558       } else
7559         return Error(Callee);
7560       FD = Member;
7561     } else if (CalleeType->isFunctionPointerType()) {
7562       LValue CalleeLV;
7563       if (!EvaluatePointer(Callee, CalleeLV, Info))
7564         return false;
7565 
7566       if (!CalleeLV.getLValueOffset().isZero())
7567         return Error(Callee);
7568       FD = dyn_cast_or_null<FunctionDecl>(
7569           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7570       if (!FD)
7571         return Error(Callee);
7572       // Don't call function pointers which have been cast to some other type.
7573       // Per DR (no number yet), the caller and callee can differ in noexcept.
7574       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7575         CalleeType->getPointeeType(), FD->getType())) {
7576         return Error(E);
7577       }
7578 
7579       // For an (overloaded) assignment expression, evaluate the RHS before the
7580       // LHS.
7581       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7582       if (OCE && OCE->isAssignmentOp()) {
7583         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7584         Call = Info.CurrentCall->createCall(FD);
7585         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7586                           Info, FD, /*RightToLeft=*/true))
7587           return false;
7588       }
7589 
7590       // Overloaded operator calls to member functions are represented as normal
7591       // calls with '*this' as the first argument.
7592       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7593       if (MD && !MD->isStatic()) {
7594         // FIXME: When selecting an implicit conversion for an overloaded
7595         // operator delete, we sometimes try to evaluate calls to conversion
7596         // operators without a 'this' parameter!
7597         if (Args.empty())
7598           return Error(E);
7599 
7600         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7601           return false;
7602         This = &ThisVal;
7603         Args = Args.slice(1);
7604       } else if (MD && MD->isLambdaStaticInvoker()) {
7605         // Map the static invoker for the lambda back to the call operator.
7606         // Conveniently, we don't have to slice out the 'this' argument (as is
7607         // being done for the non-static case), since a static member function
7608         // doesn't have an implicit argument passed in.
7609         const CXXRecordDecl *ClosureClass = MD->getParent();
7610         assert(
7611             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7612             "Number of captures must be zero for conversion to function-ptr");
7613 
7614         const CXXMethodDecl *LambdaCallOp =
7615             ClosureClass->getLambdaCallOperator();
7616 
7617         // Set 'FD', the function that will be called below, to the call
7618         // operator.  If the closure object represents a generic lambda, find
7619         // the corresponding specialization of the call operator.
7620 
7621         if (ClosureClass->isGenericLambda()) {
7622           assert(MD->isFunctionTemplateSpecialization() &&
7623                  "A generic lambda's static-invoker function must be a "
7624                  "template specialization");
7625           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7626           FunctionTemplateDecl *CallOpTemplate =
7627               LambdaCallOp->getDescribedFunctionTemplate();
7628           void *InsertPos = nullptr;
7629           FunctionDecl *CorrespondingCallOpSpecialization =
7630               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7631           assert(CorrespondingCallOpSpecialization &&
7632                  "We must always have a function call operator specialization "
7633                  "that corresponds to our static invoker specialization");
7634           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7635         } else
7636           FD = LambdaCallOp;
7637       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7638         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7639             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7640           LValue Ptr;
7641           if (!HandleOperatorNewCall(Info, E, Ptr))
7642             return false;
7643           Ptr.moveInto(Result);
7644           return CallScope.destroy();
7645         } else {
7646           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7647         }
7648       }
7649     } else
7650       return Error(E);
7651 
7652     // Evaluate the arguments now if we've not already done so.
7653     if (!Call) {
7654       Call = Info.CurrentCall->createCall(FD);
7655       if (!EvaluateArgs(Args, Call, Info, FD))
7656         return false;
7657     }
7658 
7659     SmallVector<QualType, 4> CovariantAdjustmentPath;
7660     if (This) {
7661       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7662       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7663         // Perform virtual dispatch, if necessary.
7664         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7665                                    CovariantAdjustmentPath);
7666         if (!FD)
7667           return false;
7668       } else {
7669         // Check that the 'this' pointer points to an object of the right type.
7670         // FIXME: If this is an assignment operator call, we may need to change
7671         // the active union member before we check this.
7672         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7673           return false;
7674       }
7675     }
7676 
7677     // Destructor calls are different enough that they have their own codepath.
7678     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7679       assert(This && "no 'this' pointer for destructor call");
7680       return HandleDestruction(Info, E, *This,
7681                                Info.Ctx.getRecordType(DD->getParent())) &&
7682              CallScope.destroy();
7683     }
7684 
7685     const FunctionDecl *Definition = nullptr;
7686     Stmt *Body = FD->getBody(Definition);
7687 
7688     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7689         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7690                             Body, Info, Result, ResultSlot))
7691       return false;
7692 
7693     if (!CovariantAdjustmentPath.empty() &&
7694         !HandleCovariantReturnAdjustment(Info, E, Result,
7695                                          CovariantAdjustmentPath))
7696       return false;
7697 
7698     return CallScope.destroy();
7699   }
7700 
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)7701   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7702     return StmtVisitorTy::Visit(E->getInitializer());
7703   }
VisitInitListExpr(const InitListExpr * E)7704   bool VisitInitListExpr(const InitListExpr *E) {
7705     if (E->getNumInits() == 0)
7706       return DerivedZeroInitialization(E);
7707     if (E->getNumInits() == 1)
7708       return StmtVisitorTy::Visit(E->getInit(0));
7709     return Error(E);
7710   }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)7711   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7712     return DerivedZeroInitialization(E);
7713   }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)7714   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7715     return DerivedZeroInitialization(E);
7716   }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)7717   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7718     return DerivedZeroInitialization(E);
7719   }
7720 
7721   /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)7722   bool VisitMemberExpr(const MemberExpr *E) {
7723     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7724            "missing temporary materialization conversion");
7725     assert(!E->isArrow() && "missing call to bound member function?");
7726 
7727     APValue Val;
7728     if (!Evaluate(Val, Info, E->getBase()))
7729       return false;
7730 
7731     QualType BaseTy = E->getBase()->getType();
7732 
7733     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7734     if (!FD) return Error(E);
7735     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7736     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7737            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7738 
7739     // Note: there is no lvalue base here. But this case should only ever
7740     // happen in C or in C++98, where we cannot be evaluating a constexpr
7741     // constructor, which is the only case the base matters.
7742     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7743     SubobjectDesignator Designator(BaseTy);
7744     Designator.addDeclUnchecked(FD);
7745 
7746     APValue Result;
7747     return extractSubobject(Info, E, Obj, Designator, Result) &&
7748            DerivedSuccess(Result, E);
7749   }
7750 
VisitExtVectorElementExpr(const ExtVectorElementExpr * E)7751   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7752     APValue Val;
7753     if (!Evaluate(Val, Info, E->getBase()))
7754       return false;
7755 
7756     if (Val.isVector()) {
7757       SmallVector<uint32_t, 4> Indices;
7758       E->getEncodedElementAccess(Indices);
7759       if (Indices.size() == 1) {
7760         // Return scalar.
7761         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7762       } else {
7763         // Construct new APValue vector.
7764         SmallVector<APValue, 4> Elts;
7765         for (unsigned I = 0; I < Indices.size(); ++I) {
7766           Elts.push_back(Val.getVectorElt(Indices[I]));
7767         }
7768         APValue VecResult(Elts.data(), Indices.size());
7769         return DerivedSuccess(VecResult, E);
7770       }
7771     }
7772 
7773     return false;
7774   }
7775 
VisitCastExpr(const CastExpr * E)7776   bool VisitCastExpr(const CastExpr *E) {
7777     switch (E->getCastKind()) {
7778     default:
7779       break;
7780 
7781     case CK_AtomicToNonAtomic: {
7782       APValue AtomicVal;
7783       // This does not need to be done in place even for class/array types:
7784       // atomic-to-non-atomic conversion implies copying the object
7785       // representation.
7786       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7787         return false;
7788       return DerivedSuccess(AtomicVal, E);
7789     }
7790 
7791     case CK_NoOp:
7792     case CK_UserDefinedConversion:
7793       return StmtVisitorTy::Visit(E->getSubExpr());
7794 
7795     case CK_LValueToRValue: {
7796       LValue LVal;
7797       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7798         return false;
7799       APValue RVal;
7800       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7801       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7802                                           LVal, RVal))
7803         return false;
7804       return DerivedSuccess(RVal, E);
7805     }
7806     case CK_LValueToRValueBitCast: {
7807       APValue DestValue, SourceValue;
7808       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7809         return false;
7810       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7811         return false;
7812       return DerivedSuccess(DestValue, E);
7813     }
7814 
7815     case CK_AddressSpaceConversion: {
7816       APValue Value;
7817       if (!Evaluate(Value, Info, E->getSubExpr()))
7818         return false;
7819       return DerivedSuccess(Value, E);
7820     }
7821     }
7822 
7823     return Error(E);
7824   }
7825 
VisitUnaryPostInc(const UnaryOperator * UO)7826   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7827     return VisitUnaryPostIncDec(UO);
7828   }
VisitUnaryPostDec(const UnaryOperator * UO)7829   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7830     return VisitUnaryPostIncDec(UO);
7831   }
VisitUnaryPostIncDec(const UnaryOperator * UO)7832   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7833     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7834       return Error(UO);
7835 
7836     LValue LVal;
7837     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7838       return false;
7839     APValue RVal;
7840     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7841                       UO->isIncrementOp(), &RVal))
7842       return false;
7843     return DerivedSuccess(RVal, UO);
7844   }
7845 
VisitStmtExpr(const StmtExpr * E)7846   bool VisitStmtExpr(const StmtExpr *E) {
7847     // We will have checked the full-expressions inside the statement expression
7848     // when they were completed, and don't need to check them again now.
7849     if (Info.checkingForUndefinedBehavior())
7850       return Error(E);
7851 
7852     const CompoundStmt *CS = E->getSubStmt();
7853     if (CS->body_empty())
7854       return true;
7855 
7856     BlockScopeRAII Scope(Info);
7857     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7858                                            BE = CS->body_end();
7859          /**/; ++BI) {
7860       if (BI + 1 == BE) {
7861         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7862         if (!FinalExpr) {
7863           Info.FFDiag((*BI)->getBeginLoc(),
7864                       diag::note_constexpr_stmt_expr_unsupported);
7865           return false;
7866         }
7867         return this->Visit(FinalExpr) && Scope.destroy();
7868       }
7869 
7870       APValue ReturnValue;
7871       StmtResult Result = { ReturnValue, nullptr };
7872       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7873       if (ESR != ESR_Succeeded) {
7874         // FIXME: If the statement-expression terminated due to 'return',
7875         // 'break', or 'continue', it would be nice to propagate that to
7876         // the outer statement evaluation rather than bailing out.
7877         if (ESR != ESR_Failed)
7878           Info.FFDiag((*BI)->getBeginLoc(),
7879                       diag::note_constexpr_stmt_expr_unsupported);
7880         return false;
7881       }
7882     }
7883 
7884     llvm_unreachable("Return from function from the loop above.");
7885   }
7886 
7887   /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)7888   void VisitIgnoredValue(const Expr *E) {
7889     EvaluateIgnoredValue(Info, E);
7890   }
7891 
7892   /// Potentially visit a MemberExpr's base expression.
VisitIgnoredBaseExpression(const Expr * E)7893   void VisitIgnoredBaseExpression(const Expr *E) {
7894     // While MSVC doesn't evaluate the base expression, it does diagnose the
7895     // presence of side-effecting behavior.
7896     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7897       return;
7898     VisitIgnoredValue(E);
7899   }
7900 };
7901 
7902 } // namespace
7903 
7904 //===----------------------------------------------------------------------===//
7905 // Common base class for lvalue and temporary evaluation.
7906 //===----------------------------------------------------------------------===//
7907 namespace {
7908 template<class Derived>
7909 class LValueExprEvaluatorBase
7910   : public ExprEvaluatorBase<Derived> {
7911 protected:
7912   LValue &Result;
7913   bool InvalidBaseOK;
7914   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7915   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7916 
Success(APValue::LValueBase B)7917   bool Success(APValue::LValueBase B) {
7918     Result.set(B);
7919     return true;
7920   }
7921 
evaluatePointer(const Expr * E,LValue & Result)7922   bool evaluatePointer(const Expr *E, LValue &Result) {
7923     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7924   }
7925 
7926 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)7927   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7928       : ExprEvaluatorBaseTy(Info), Result(Result),
7929         InvalidBaseOK(InvalidBaseOK) {}
7930 
Success(const APValue & V,const Expr * E)7931   bool Success(const APValue &V, const Expr *E) {
7932     Result.setFrom(this->Info.Ctx, V);
7933     return true;
7934   }
7935 
VisitMemberExpr(const MemberExpr * E)7936   bool VisitMemberExpr(const MemberExpr *E) {
7937     // Handle non-static data members.
7938     QualType BaseTy;
7939     bool EvalOK;
7940     if (E->isArrow()) {
7941       EvalOK = evaluatePointer(E->getBase(), Result);
7942       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7943     } else if (E->getBase()->isRValue()) {
7944       assert(E->getBase()->getType()->isRecordType());
7945       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7946       BaseTy = E->getBase()->getType();
7947     } else {
7948       EvalOK = this->Visit(E->getBase());
7949       BaseTy = E->getBase()->getType();
7950     }
7951     if (!EvalOK) {
7952       if (!InvalidBaseOK)
7953         return false;
7954       Result.setInvalid(E);
7955       return true;
7956     }
7957 
7958     const ValueDecl *MD = E->getMemberDecl();
7959     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7960       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7961              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7962       (void)BaseTy;
7963       if (!HandleLValueMember(this->Info, E, Result, FD))
7964         return false;
7965     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7966       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7967         return false;
7968     } else
7969       return this->Error(E);
7970 
7971     if (MD->getType()->isReferenceType()) {
7972       APValue RefValue;
7973       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7974                                           RefValue))
7975         return false;
7976       return Success(RefValue, E);
7977     }
7978     return true;
7979   }
7980 
VisitBinaryOperator(const BinaryOperator * E)7981   bool VisitBinaryOperator(const BinaryOperator *E) {
7982     switch (E->getOpcode()) {
7983     default:
7984       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7985 
7986     case BO_PtrMemD:
7987     case BO_PtrMemI:
7988       return HandleMemberPointerAccess(this->Info, E, Result);
7989     }
7990   }
7991 
VisitCastExpr(const CastExpr * E)7992   bool VisitCastExpr(const CastExpr *E) {
7993     switch (E->getCastKind()) {
7994     default:
7995       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7996 
7997     case CK_DerivedToBase:
7998     case CK_UncheckedDerivedToBase:
7999       if (!this->Visit(E->getSubExpr()))
8000         return false;
8001 
8002       // Now figure out the necessary offset to add to the base LV to get from
8003       // the derived class to the base class.
8004       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8005                                   Result);
8006     }
8007   }
8008 };
8009 }
8010 
8011 //===----------------------------------------------------------------------===//
8012 // LValue Evaluation
8013 //
8014 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8015 // function designators (in C), decl references to void objects (in C), and
8016 // temporaries (if building with -Wno-address-of-temporary).
8017 //
8018 // LValue evaluation produces values comprising a base expression of one of the
8019 // following types:
8020 // - Declarations
8021 //  * VarDecl
8022 //  * FunctionDecl
8023 // - Literals
8024 //  * CompoundLiteralExpr in C (and in global scope in C++)
8025 //  * StringLiteral
8026 //  * PredefinedExpr
8027 //  * ObjCStringLiteralExpr
8028 //  * ObjCEncodeExpr
8029 //  * AddrLabelExpr
8030 //  * BlockExpr
8031 //  * CallExpr for a MakeStringConstant builtin
8032 // - typeid(T) expressions, as TypeInfoLValues
8033 // - Locals and temporaries
8034 //  * MaterializeTemporaryExpr
8035 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8036 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8037 //    from the AST (FIXME).
8038 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8039 //    CallIndex, for a lifetime-extended temporary.
8040 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8041 //    immediate invocation.
8042 // plus an offset in bytes.
8043 //===----------------------------------------------------------------------===//
8044 namespace {
8045 class LValueExprEvaluator
8046   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8047 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8048   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8049     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8050 
8051   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8052   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8053 
8054   bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)8055   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8056   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8057   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8058   bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)8059   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)8060   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8061   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8062   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8063   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8064   bool VisitUnaryDeref(const UnaryOperator *E);
8065   bool VisitUnaryReal(const UnaryOperator *E);
8066   bool VisitUnaryImag(const UnaryOperator *E);
VisitUnaryPreInc(const UnaryOperator * UO)8067   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8068     return VisitUnaryPreIncDec(UO);
8069   }
VisitUnaryPreDec(const UnaryOperator * UO)8070   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8071     return VisitUnaryPreIncDec(UO);
8072   }
8073   bool VisitBinAssign(const BinaryOperator *BO);
8074   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8075 
VisitCastExpr(const CastExpr * E)8076   bool VisitCastExpr(const CastExpr *E) {
8077     switch (E->getCastKind()) {
8078     default:
8079       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8080 
8081     case CK_LValueBitCast:
8082       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8083       if (!Visit(E->getSubExpr()))
8084         return false;
8085       Result.Designator.setInvalid();
8086       return true;
8087 
8088     case CK_BaseToDerived:
8089       if (!Visit(E->getSubExpr()))
8090         return false;
8091       return HandleBaseToDerivedCast(Info, E, Result);
8092 
8093     case CK_Dynamic:
8094       if (!Visit(E->getSubExpr()))
8095         return false;
8096       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8097     }
8098   }
8099 };
8100 } // end anonymous namespace
8101 
8102 /// Evaluate an expression as an lvalue. This can be legitimately called on
8103 /// expressions which are not glvalues, in three cases:
8104 ///  * function designators in C, and
8105 ///  * "extern void" objects
8106 ///  * @selector() expressions in Objective-C
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8107 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8108                            bool InvalidBaseOK) {
8109   assert(!E->isValueDependent());
8110   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8111          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8112   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8113 }
8114 
VisitDeclRefExpr(const DeclRefExpr * E)8115 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8116   const NamedDecl *D = E->getDecl();
8117   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8118     return Success(cast<ValueDecl>(D));
8119   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8120     return VisitVarDecl(E, VD);
8121   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8122     return Visit(BD->getBinding());
8123   return Error(E);
8124 }
8125 
8126 
VisitVarDecl(const Expr * E,const VarDecl * VD)8127 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8128 
8129   // If we are within a lambda's call operator, check whether the 'VD' referred
8130   // to within 'E' actually represents a lambda-capture that maps to a
8131   // data-member/field within the closure object, and if so, evaluate to the
8132   // field or what the field refers to.
8133   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8134       isa<DeclRefExpr>(E) &&
8135       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8136     // We don't always have a complete capture-map when checking or inferring if
8137     // the function call operator meets the requirements of a constexpr function
8138     // - but we don't need to evaluate the captures to determine constexprness
8139     // (dcl.constexpr C++17).
8140     if (Info.checkingPotentialConstantExpression())
8141       return false;
8142 
8143     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8144       // Start with 'Result' referring to the complete closure object...
8145       Result = *Info.CurrentCall->This;
8146       // ... then update it to refer to the field of the closure object
8147       // that represents the capture.
8148       if (!HandleLValueMember(Info, E, Result, FD))
8149         return false;
8150       // And if the field is of reference type, update 'Result' to refer to what
8151       // the field refers to.
8152       if (FD->getType()->isReferenceType()) {
8153         APValue RVal;
8154         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8155                                             RVal))
8156           return false;
8157         Result.setFrom(Info.Ctx, RVal);
8158       }
8159       return true;
8160     }
8161   }
8162 
8163   CallStackFrame *Frame = nullptr;
8164   unsigned Version = 0;
8165   if (VD->hasLocalStorage()) {
8166     // Only if a local variable was declared in the function currently being
8167     // evaluated, do we expect to be able to find its value in the current
8168     // frame. (Otherwise it was likely declared in an enclosing context and
8169     // could either have a valid evaluatable value (for e.g. a constexpr
8170     // variable) or be ill-formed (and trigger an appropriate evaluation
8171     // diagnostic)).
8172     CallStackFrame *CurrFrame = Info.CurrentCall;
8173     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8174       // Function parameters are stored in some caller's frame. (Usually the
8175       // immediate caller, but for an inherited constructor they may be more
8176       // distant.)
8177       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8178         if (CurrFrame->Arguments) {
8179           VD = CurrFrame->Arguments.getOrigParam(PVD);
8180           Frame =
8181               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8182           Version = CurrFrame->Arguments.Version;
8183         }
8184       } else {
8185         Frame = CurrFrame;
8186         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8187       }
8188     }
8189   }
8190 
8191   if (!VD->getType()->isReferenceType()) {
8192     if (Frame) {
8193       Result.set({VD, Frame->Index, Version});
8194       return true;
8195     }
8196     return Success(VD);
8197   }
8198 
8199   if (!Info.getLangOpts().CPlusPlus11) {
8200     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8201         << VD << VD->getType();
8202     Info.Note(VD->getLocation(), diag::note_declared_at);
8203   }
8204 
8205   APValue *V;
8206   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8207     return false;
8208   if (!V->hasValue()) {
8209     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8210     // adjust the diagnostic to say that.
8211     if (!Info.checkingPotentialConstantExpression())
8212       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8213     return false;
8214   }
8215   return Success(*V, E);
8216 }
8217 
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)8218 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8219     const MaterializeTemporaryExpr *E) {
8220   // Walk through the expression to find the materialized temporary itself.
8221   SmallVector<const Expr *, 2> CommaLHSs;
8222   SmallVector<SubobjectAdjustment, 2> Adjustments;
8223   const Expr *Inner =
8224       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8225 
8226   // If we passed any comma operators, evaluate their LHSs.
8227   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8228     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8229       return false;
8230 
8231   // A materialized temporary with static storage duration can appear within the
8232   // result of a constant expression evaluation, so we need to preserve its
8233   // value for use outside this evaluation.
8234   APValue *Value;
8235   if (E->getStorageDuration() == SD_Static) {
8236     // FIXME: What about SD_Thread?
8237     Value = E->getOrCreateValue(true);
8238     *Value = APValue();
8239     Result.set(E);
8240   } else {
8241     Value = &Info.CurrentCall->createTemporary(
8242         E, E->getType(),
8243         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8244                                                      : ScopeKind::Block,
8245         Result);
8246   }
8247 
8248   QualType Type = Inner->getType();
8249 
8250   // Materialize the temporary itself.
8251   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8252     *Value = APValue();
8253     return false;
8254   }
8255 
8256   // Adjust our lvalue to refer to the desired subobject.
8257   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8258     --I;
8259     switch (Adjustments[I].Kind) {
8260     case SubobjectAdjustment::DerivedToBaseAdjustment:
8261       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8262                                 Type, Result))
8263         return false;
8264       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8265       break;
8266 
8267     case SubobjectAdjustment::FieldAdjustment:
8268       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8269         return false;
8270       Type = Adjustments[I].Field->getType();
8271       break;
8272 
8273     case SubobjectAdjustment::MemberPointerAdjustment:
8274       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8275                                      Adjustments[I].Ptr.RHS))
8276         return false;
8277       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8278       break;
8279     }
8280   }
8281 
8282   return true;
8283 }
8284 
8285 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)8286 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8287   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8288          "lvalue compound literal in c++?");
8289   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8290   // only see this when folding in C, so there's no standard to follow here.
8291   return Success(E);
8292 }
8293 
VisitCXXTypeidExpr(const CXXTypeidExpr * E)8294 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8295   TypeInfoLValue TypeInfo;
8296 
8297   if (!E->isPotentiallyEvaluated()) {
8298     if (E->isTypeOperand())
8299       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8300     else
8301       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8302   } else {
8303     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8304       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8305         << E->getExprOperand()->getType()
8306         << E->getExprOperand()->getSourceRange();
8307     }
8308 
8309     if (!Visit(E->getExprOperand()))
8310       return false;
8311 
8312     Optional<DynamicType> DynType =
8313         ComputeDynamicType(Info, E, Result, AK_TypeId);
8314     if (!DynType)
8315       return false;
8316 
8317     TypeInfo =
8318         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8319   }
8320 
8321   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8322 }
8323 
VisitCXXUuidofExpr(const CXXUuidofExpr * E)8324 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8325   return Success(E->getGuidDecl());
8326 }
8327 
VisitMemberExpr(const MemberExpr * E)8328 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8329   // Handle static data members.
8330   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8331     VisitIgnoredBaseExpression(E->getBase());
8332     return VisitVarDecl(E, VD);
8333   }
8334 
8335   // Handle static member functions.
8336   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8337     if (MD->isStatic()) {
8338       VisitIgnoredBaseExpression(E->getBase());
8339       return Success(MD);
8340     }
8341   }
8342 
8343   // Handle non-static data members.
8344   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8345 }
8346 
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)8347 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8348   // FIXME: Deal with vectors as array subscript bases.
8349   if (E->getBase()->getType()->isVectorType())
8350     return Error(E);
8351 
8352   APSInt Index;
8353   bool Success = true;
8354 
8355   // C++17's rules require us to evaluate the LHS first, regardless of which
8356   // side is the base.
8357   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8358     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8359                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8360       if (!Info.noteFailure())
8361         return false;
8362       Success = false;
8363     }
8364   }
8365 
8366   return Success &&
8367          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8368 }
8369 
VisitUnaryDeref(const UnaryOperator * E)8370 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8371   return evaluatePointer(E->getSubExpr(), Result);
8372 }
8373 
VisitUnaryReal(const UnaryOperator * E)8374 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8375   if (!Visit(E->getSubExpr()))
8376     return false;
8377   // __real is a no-op on scalar lvalues.
8378   if (E->getSubExpr()->getType()->isAnyComplexType())
8379     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8380   return true;
8381 }
8382 
VisitUnaryImag(const UnaryOperator * E)8383 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8384   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8385          "lvalue __imag__ on scalar?");
8386   if (!Visit(E->getSubExpr()))
8387     return false;
8388   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8389   return true;
8390 }
8391 
VisitUnaryPreIncDec(const UnaryOperator * UO)8392 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8393   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8394     return Error(UO);
8395 
8396   if (!this->Visit(UO->getSubExpr()))
8397     return false;
8398 
8399   return handleIncDec(
8400       this->Info, UO, Result, UO->getSubExpr()->getType(),
8401       UO->isIncrementOp(), nullptr);
8402 }
8403 
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)8404 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8405     const CompoundAssignOperator *CAO) {
8406   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8407     return Error(CAO);
8408 
8409   bool Success = true;
8410 
8411   // C++17 onwards require that we evaluate the RHS first.
8412   APValue RHS;
8413   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8414     if (!Info.noteFailure())
8415       return false;
8416     Success = false;
8417   }
8418 
8419   // The overall lvalue result is the result of evaluating the LHS.
8420   if (!this->Visit(CAO->getLHS()) || !Success)
8421     return false;
8422 
8423   return handleCompoundAssignment(
8424       this->Info, CAO,
8425       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8426       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8427 }
8428 
VisitBinAssign(const BinaryOperator * E)8429 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8430   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8431     return Error(E);
8432 
8433   bool Success = true;
8434 
8435   // C++17 onwards require that we evaluate the RHS first.
8436   APValue NewVal;
8437   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8438     if (!Info.noteFailure())
8439       return false;
8440     Success = false;
8441   }
8442 
8443   if (!this->Visit(E->getLHS()) || !Success)
8444     return false;
8445 
8446   if (Info.getLangOpts().CPlusPlus20 &&
8447       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8448     return false;
8449 
8450   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8451                           NewVal);
8452 }
8453 
8454 //===----------------------------------------------------------------------===//
8455 // Pointer Evaluation
8456 //===----------------------------------------------------------------------===//
8457 
8458 /// Attempts to compute the number of bytes available at the pointer
8459 /// returned by a function with the alloc_size attribute. Returns true if we
8460 /// were successful. Places an unsigned number into `Result`.
8461 ///
8462 /// This expects the given CallExpr to be a call to a function with an
8463 /// alloc_size attribute.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const CallExpr * Call,llvm::APInt & Result)8464 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8465                                             const CallExpr *Call,
8466                                             llvm::APInt &Result) {
8467   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8468 
8469   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8470   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8471   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8472   if (Call->getNumArgs() <= SizeArgNo)
8473     return false;
8474 
8475   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8476     Expr::EvalResult ExprResult;
8477     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8478       return false;
8479     Into = ExprResult.Val.getInt();
8480     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8481       return false;
8482     Into = Into.zextOrSelf(BitsInSizeT);
8483     return true;
8484   };
8485 
8486   APSInt SizeOfElem;
8487   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8488     return false;
8489 
8490   if (!AllocSize->getNumElemsParam().isValid()) {
8491     Result = std::move(SizeOfElem);
8492     return true;
8493   }
8494 
8495   APSInt NumberOfElems;
8496   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8497   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8498     return false;
8499 
8500   bool Overflow;
8501   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8502   if (Overflow)
8503     return false;
8504 
8505   Result = std::move(BytesAvailable);
8506   return true;
8507 }
8508 
8509 /// Convenience function. LVal's base must be a call to an alloc_size
8510 /// function.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const LValue & LVal,llvm::APInt & Result)8511 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8512                                             const LValue &LVal,
8513                                             llvm::APInt &Result) {
8514   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8515          "Can't get the size of a non alloc_size function");
8516   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8517   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8518   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8519 }
8520 
8521 /// Attempts to evaluate the given LValueBase as the result of a call to
8522 /// a function with the alloc_size attribute. If it was possible to do so, this
8523 /// function will return true, make Result's Base point to said function call,
8524 /// and mark Result's Base as invalid.
evaluateLValueAsAllocSize(EvalInfo & Info,APValue::LValueBase Base,LValue & Result)8525 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8526                                       LValue &Result) {
8527   if (Base.isNull())
8528     return false;
8529 
8530   // Because we do no form of static analysis, we only support const variables.
8531   //
8532   // Additionally, we can't support parameters, nor can we support static
8533   // variables (in the latter case, use-before-assign isn't UB; in the former,
8534   // we have no clue what they'll be assigned to).
8535   const auto *VD =
8536       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8537   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8538     return false;
8539 
8540   const Expr *Init = VD->getAnyInitializer();
8541   if (!Init)
8542     return false;
8543 
8544   const Expr *E = Init->IgnoreParens();
8545   if (!tryUnwrapAllocSizeCall(E))
8546     return false;
8547 
8548   // Store E instead of E unwrapped so that the type of the LValue's base is
8549   // what the user wanted.
8550   Result.setInvalid(E);
8551 
8552   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8553   Result.addUnsizedArray(Info, E, Pointee);
8554   return true;
8555 }
8556 
8557 namespace {
8558 class PointerExprEvaluator
8559   : public ExprEvaluatorBase<PointerExprEvaluator> {
8560   LValue &Result;
8561   bool InvalidBaseOK;
8562 
Success(const Expr * E)8563   bool Success(const Expr *E) {
8564     Result.set(E);
8565     return true;
8566   }
8567 
evaluateLValue(const Expr * E,LValue & Result)8568   bool evaluateLValue(const Expr *E, LValue &Result) {
8569     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8570   }
8571 
evaluatePointer(const Expr * E,LValue & Result)8572   bool evaluatePointer(const Expr *E, LValue &Result) {
8573     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8574   }
8575 
8576   bool visitNonBuiltinCallExpr(const CallExpr *E);
8577 public:
8578 
PointerExprEvaluator(EvalInfo & info,LValue & Result,bool InvalidBaseOK)8579   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8580       : ExprEvaluatorBaseTy(info), Result(Result),
8581         InvalidBaseOK(InvalidBaseOK) {}
8582 
Success(const APValue & V,const Expr * E)8583   bool Success(const APValue &V, const Expr *E) {
8584     Result.setFrom(Info.Ctx, V);
8585     return true;
8586   }
ZeroInitialization(const Expr * E)8587   bool ZeroInitialization(const Expr *E) {
8588     Result.setNull(Info.Ctx, E->getType());
8589     return true;
8590   }
8591 
8592   bool VisitBinaryOperator(const BinaryOperator *E);
8593   bool VisitCastExpr(const CastExpr* E);
8594   bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)8595   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8596       { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)8597   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8598     if (E->isExpressibleAsConstantInitializer())
8599       return Success(E);
8600     if (Info.noteFailure())
8601       EvaluateIgnoredValue(Info, E->getSubExpr());
8602     return Error(E);
8603   }
VisitAddrLabelExpr(const AddrLabelExpr * E)8604   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8605       { return Success(E); }
8606   bool VisitCallExpr(const CallExpr *E);
8607   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
VisitBlockExpr(const BlockExpr * E)8608   bool VisitBlockExpr(const BlockExpr *E) {
8609     if (!E->getBlockDecl()->hasCaptures())
8610       return Success(E);
8611     return Error(E);
8612   }
VisitCXXThisExpr(const CXXThisExpr * E)8613   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8614     // Can't look at 'this' when checking a potential constant expression.
8615     if (Info.checkingPotentialConstantExpression())
8616       return false;
8617     if (!Info.CurrentCall->This) {
8618       if (Info.getLangOpts().CPlusPlus11)
8619         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8620       else
8621         Info.FFDiag(E);
8622       return false;
8623     }
8624     Result = *Info.CurrentCall->This;
8625     // If we are inside a lambda's call operator, the 'this' expression refers
8626     // to the enclosing '*this' object (either by value or reference) which is
8627     // either copied into the closure object's field that represents the '*this'
8628     // or refers to '*this'.
8629     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8630       // Ensure we actually have captured 'this'. (an error will have
8631       // been previously reported if not).
8632       if (!Info.CurrentCall->LambdaThisCaptureField)
8633         return false;
8634 
8635       // Update 'Result' to refer to the data member/field of the closure object
8636       // that represents the '*this' capture.
8637       if (!HandleLValueMember(Info, E, Result,
8638                              Info.CurrentCall->LambdaThisCaptureField))
8639         return false;
8640       // If we captured '*this' by reference, replace the field with its referent.
8641       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8642               ->isPointerType()) {
8643         APValue RVal;
8644         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8645                                             RVal))
8646           return false;
8647 
8648         Result.setFrom(Info.Ctx, RVal);
8649       }
8650     }
8651     return true;
8652   }
8653 
8654   bool VisitCXXNewExpr(const CXXNewExpr *E);
8655 
VisitSourceLocExpr(const SourceLocExpr * E)8656   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8657     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8658     APValue LValResult = E->EvaluateInContext(
8659         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8660     Result.setFrom(Info.Ctx, LValResult);
8661     return true;
8662   }
8663 
8664   // FIXME: Missing: @protocol, @selector
8665 };
8666 } // end anonymous namespace
8667 
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8668 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8669                             bool InvalidBaseOK) {
8670   assert(!E->isValueDependent());
8671   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8672   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8673 }
8674 
VisitBinaryOperator(const BinaryOperator * E)8675 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8676   if (E->getOpcode() != BO_Add &&
8677       E->getOpcode() != BO_Sub)
8678     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8679 
8680   const Expr *PExp = E->getLHS();
8681   const Expr *IExp = E->getRHS();
8682   if (IExp->getType()->isPointerType())
8683     std::swap(PExp, IExp);
8684 
8685   bool EvalPtrOK = evaluatePointer(PExp, Result);
8686   if (!EvalPtrOK && !Info.noteFailure())
8687     return false;
8688 
8689   llvm::APSInt Offset;
8690   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8691     return false;
8692 
8693   if (E->getOpcode() == BO_Sub)
8694     negateAsSigned(Offset);
8695 
8696   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8697   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8698 }
8699 
VisitUnaryAddrOf(const UnaryOperator * E)8700 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8701   return evaluateLValue(E->getSubExpr(), Result);
8702 }
8703 
VisitCastExpr(const CastExpr * E)8704 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8705   const Expr *SubExpr = E->getSubExpr();
8706 
8707   switch (E->getCastKind()) {
8708   default:
8709     break;
8710   case CK_BitCast:
8711   case CK_CPointerToObjCPointerCast:
8712   case CK_BlockPointerToObjCPointerCast:
8713   case CK_AnyPointerToBlockPointerCast:
8714   case CK_AddressSpaceConversion:
8715     if (!Visit(SubExpr))
8716       return false;
8717     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8718     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8719     // also static_casts, but we disallow them as a resolution to DR1312.
8720     if (!E->getType()->isVoidPointerType()) {
8721       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8722           !Result.IsNullPtr &&
8723           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8724                                           E->getType()->getPointeeType()) &&
8725           Info.getStdAllocatorCaller("allocate")) {
8726         // Inside a call to std::allocator::allocate and friends, we permit
8727         // casting from void* back to cv1 T* for a pointer that points to a
8728         // cv2 T.
8729       } else {
8730         Result.Designator.setInvalid();
8731         if (SubExpr->getType()->isVoidPointerType())
8732           CCEDiag(E, diag::note_constexpr_invalid_cast)
8733             << 3 << SubExpr->getType();
8734         else
8735           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8736       }
8737     }
8738     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8739       ZeroInitialization(E);
8740     return true;
8741 
8742   case CK_DerivedToBase:
8743   case CK_UncheckedDerivedToBase:
8744     if (!evaluatePointer(E->getSubExpr(), Result))
8745       return false;
8746     if (!Result.Base && Result.Offset.isZero())
8747       return true;
8748 
8749     // Now figure out the necessary offset to add to the base LV to get from
8750     // the derived class to the base class.
8751     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8752                                   castAs<PointerType>()->getPointeeType(),
8753                                 Result);
8754 
8755   case CK_BaseToDerived:
8756     if (!Visit(E->getSubExpr()))
8757       return false;
8758     if (!Result.Base && Result.Offset.isZero())
8759       return true;
8760     return HandleBaseToDerivedCast(Info, E, Result);
8761 
8762   case CK_Dynamic:
8763     if (!Visit(E->getSubExpr()))
8764       return false;
8765     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8766 
8767   case CK_NullToPointer:
8768     VisitIgnoredValue(E->getSubExpr());
8769     return ZeroInitialization(E);
8770 
8771   case CK_IntegralToPointer: {
8772     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8773 
8774     APValue Value;
8775     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8776       break;
8777 
8778     if (Value.isInt()) {
8779       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8780       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8781       Result.Base = (Expr*)nullptr;
8782       Result.InvalidBase = false;
8783       Result.Offset = CharUnits::fromQuantity(N);
8784       Result.Designator.setInvalid();
8785       Result.IsNullPtr = false;
8786       return true;
8787     } else {
8788       // Cast is of an lvalue, no need to change value.
8789       Result.setFrom(Info.Ctx, Value);
8790       return true;
8791     }
8792   }
8793 
8794   case CK_ArrayToPointerDecay: {
8795     if (SubExpr->isGLValue()) {
8796       if (!evaluateLValue(SubExpr, Result))
8797         return false;
8798     } else {
8799       APValue &Value = Info.CurrentCall->createTemporary(
8800           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8801       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8802         return false;
8803     }
8804     // The result is a pointer to the first element of the array.
8805     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8806     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8807       Result.addArray(Info, E, CAT);
8808     else
8809       Result.addUnsizedArray(Info, E, AT->getElementType());
8810     return true;
8811   }
8812 
8813   case CK_FunctionToPointerDecay:
8814     return evaluateLValue(SubExpr, Result);
8815 
8816   case CK_LValueToRValue: {
8817     LValue LVal;
8818     if (!evaluateLValue(E->getSubExpr(), LVal))
8819       return false;
8820 
8821     APValue RVal;
8822     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8823     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8824                                         LVal, RVal))
8825       return InvalidBaseOK &&
8826              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8827     return Success(RVal, E);
8828   }
8829   }
8830 
8831   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8832 }
8833 
GetAlignOfType(EvalInfo & Info,QualType T,UnaryExprOrTypeTrait ExprKind)8834 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8835                                 UnaryExprOrTypeTrait ExprKind) {
8836   // C++ [expr.alignof]p3:
8837   //     When alignof is applied to a reference type, the result is the
8838   //     alignment of the referenced type.
8839   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8840     T = Ref->getPointeeType();
8841 
8842   if (T.getQualifiers().hasUnaligned())
8843     return CharUnits::One();
8844 
8845   const bool AlignOfReturnsPreferred =
8846       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8847 
8848   // __alignof is defined to return the preferred alignment.
8849   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8850   // as well.
8851   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8852     return Info.Ctx.toCharUnitsFromBits(
8853       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8854   // alignof and _Alignof are defined to return the ABI alignment.
8855   else if (ExprKind == UETT_AlignOf)
8856     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8857   else
8858     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8859 }
8860 
GetAlignOfExpr(EvalInfo & Info,const Expr * E,UnaryExprOrTypeTrait ExprKind)8861 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8862                                 UnaryExprOrTypeTrait ExprKind) {
8863   E = E->IgnoreParens();
8864 
8865   // The kinds of expressions that we have special-case logic here for
8866   // should be kept up to date with the special checks for those
8867   // expressions in Sema.
8868 
8869   // alignof decl is always accepted, even if it doesn't make sense: we default
8870   // to 1 in those cases.
8871   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8872     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8873                                  /*RefAsPointee*/true);
8874 
8875   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8876     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8877                                  /*RefAsPointee*/true);
8878 
8879   return GetAlignOfType(Info, E->getType(), ExprKind);
8880 }
8881 
getBaseAlignment(EvalInfo & Info,const LValue & Value)8882 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8883   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8884     return Info.Ctx.getDeclAlign(VD);
8885   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8886     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8887   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8888 }
8889 
8890 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8891 /// __builtin_is_aligned and __builtin_assume_aligned.
getAlignmentArgument(const Expr * E,QualType ForType,EvalInfo & Info,APSInt & Alignment)8892 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8893                                  EvalInfo &Info, APSInt &Alignment) {
8894   if (!EvaluateInteger(E, Alignment, Info))
8895     return false;
8896   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8897     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8898     return false;
8899   }
8900   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8901   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8902   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8903     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8904         << MaxValue << ForType << Alignment;
8905     return false;
8906   }
8907   // Ensure both alignment and source value have the same bit width so that we
8908   // don't assert when computing the resulting value.
8909   APSInt ExtAlignment =
8910       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8911   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8912          "Alignment should not be changed by ext/trunc");
8913   Alignment = ExtAlignment;
8914   assert(Alignment.getBitWidth() == SrcWidth);
8915   return true;
8916 }
8917 
8918 // To be clear: this happily visits unsupported builtins. Better name welcomed.
visitNonBuiltinCallExpr(const CallExpr * E)8919 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8920   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8921     return true;
8922 
8923   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8924     return false;
8925 
8926   Result.setInvalid(E);
8927   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8928   Result.addUnsizedArray(Info, E, PointeeTy);
8929   return true;
8930 }
8931 
VisitCallExpr(const CallExpr * E)8932 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8933   if (IsStringLiteralCall(E))
8934     return Success(E);
8935 
8936   if (unsigned BuiltinOp = E->getBuiltinCallee())
8937     return VisitBuiltinCallExpr(E, BuiltinOp);
8938 
8939   return visitNonBuiltinCallExpr(E);
8940 }
8941 
8942 // Determine if T is a character type for which we guarantee that
8943 // sizeof(T) == 1.
isOneByteCharacterType(QualType T)8944 static bool isOneByteCharacterType(QualType T) {
8945   return T->isCharType() || T->isChar8Type();
8946 }
8947 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)8948 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8949                                                 unsigned BuiltinOp) {
8950   switch (BuiltinOp) {
8951   case Builtin::BI__builtin_addressof:
8952     return evaluateLValue(E->getArg(0), Result);
8953   case Builtin::BI__builtin_assume_aligned: {
8954     // We need to be very careful here because: if the pointer does not have the
8955     // asserted alignment, then the behavior is undefined, and undefined
8956     // behavior is non-constant.
8957     if (!evaluatePointer(E->getArg(0), Result))
8958       return false;
8959 
8960     LValue OffsetResult(Result);
8961     APSInt Alignment;
8962     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8963                               Alignment))
8964       return false;
8965     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8966 
8967     if (E->getNumArgs() > 2) {
8968       APSInt Offset;
8969       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8970         return false;
8971 
8972       int64_t AdditionalOffset = -Offset.getZExtValue();
8973       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8974     }
8975 
8976     // If there is a base object, then it must have the correct alignment.
8977     if (OffsetResult.Base) {
8978       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8979 
8980       if (BaseAlignment < Align) {
8981         Result.Designator.setInvalid();
8982         // FIXME: Add support to Diagnostic for long / long long.
8983         CCEDiag(E->getArg(0),
8984                 diag::note_constexpr_baa_insufficient_alignment) << 0
8985           << (unsigned)BaseAlignment.getQuantity()
8986           << (unsigned)Align.getQuantity();
8987         return false;
8988       }
8989     }
8990 
8991     // The offset must also have the correct alignment.
8992     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8993       Result.Designator.setInvalid();
8994 
8995       (OffsetResult.Base
8996            ? CCEDiag(E->getArg(0),
8997                      diag::note_constexpr_baa_insufficient_alignment) << 1
8998            : CCEDiag(E->getArg(0),
8999                      diag::note_constexpr_baa_value_insufficient_alignment))
9000         << (int)OffsetResult.Offset.getQuantity()
9001         << (unsigned)Align.getQuantity();
9002       return false;
9003     }
9004 
9005     return true;
9006   }
9007   case Builtin::BI__builtin_align_up:
9008   case Builtin::BI__builtin_align_down: {
9009     if (!evaluatePointer(E->getArg(0), Result))
9010       return false;
9011     APSInt Alignment;
9012     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9013                               Alignment))
9014       return false;
9015     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9016     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9017     // For align_up/align_down, we can return the same value if the alignment
9018     // is known to be greater or equal to the requested value.
9019     if (PtrAlign.getQuantity() >= Alignment)
9020       return true;
9021 
9022     // The alignment could be greater than the minimum at run-time, so we cannot
9023     // infer much about the resulting pointer value. One case is possible:
9024     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9025     // can infer the correct index if the requested alignment is smaller than
9026     // the base alignment so we can perform the computation on the offset.
9027     if (BaseAlignment.getQuantity() >= Alignment) {
9028       assert(Alignment.getBitWidth() <= 64 &&
9029              "Cannot handle > 64-bit address-space");
9030       uint64_t Alignment64 = Alignment.getZExtValue();
9031       CharUnits NewOffset = CharUnits::fromQuantity(
9032           BuiltinOp == Builtin::BI__builtin_align_down
9033               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9034               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9035       Result.adjustOffset(NewOffset - Result.Offset);
9036       // TODO: diagnose out-of-bounds values/only allow for arrays?
9037       return true;
9038     }
9039     // Otherwise, we cannot constant-evaluate the result.
9040     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9041         << Alignment;
9042     return false;
9043   }
9044   case Builtin::BI__builtin_operator_new:
9045     return HandleOperatorNewCall(Info, E, Result);
9046   case Builtin::BI__builtin_launder:
9047     return evaluatePointer(E->getArg(0), Result);
9048   case Builtin::BIstrchr:
9049   case Builtin::BIwcschr:
9050   case Builtin::BImemchr:
9051   case Builtin::BIwmemchr:
9052     if (Info.getLangOpts().CPlusPlus11)
9053       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9054         << /*isConstexpr*/0 << /*isConstructor*/0
9055         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9056     else
9057       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9058     LLVM_FALLTHROUGH;
9059   case Builtin::BI__builtin_strchr:
9060   case Builtin::BI__builtin_wcschr:
9061   case Builtin::BI__builtin_memchr:
9062   case Builtin::BI__builtin_char_memchr:
9063   case Builtin::BI__builtin_wmemchr: {
9064     if (!Visit(E->getArg(0)))
9065       return false;
9066     APSInt Desired;
9067     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9068       return false;
9069     uint64_t MaxLength = uint64_t(-1);
9070     if (BuiltinOp != Builtin::BIstrchr &&
9071         BuiltinOp != Builtin::BIwcschr &&
9072         BuiltinOp != Builtin::BI__builtin_strchr &&
9073         BuiltinOp != Builtin::BI__builtin_wcschr) {
9074       APSInt N;
9075       if (!EvaluateInteger(E->getArg(2), N, Info))
9076         return false;
9077       MaxLength = N.getExtValue();
9078     }
9079     // We cannot find the value if there are no candidates to match against.
9080     if (MaxLength == 0u)
9081       return ZeroInitialization(E);
9082     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9083         Result.Designator.Invalid)
9084       return false;
9085     QualType CharTy = Result.Designator.getType(Info.Ctx);
9086     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9087                      BuiltinOp == Builtin::BI__builtin_memchr;
9088     assert(IsRawByte ||
9089            Info.Ctx.hasSameUnqualifiedType(
9090                CharTy, E->getArg(0)->getType()->getPointeeType()));
9091     // Pointers to const void may point to objects of incomplete type.
9092     if (IsRawByte && CharTy->isIncompleteType()) {
9093       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9094       return false;
9095     }
9096     // Give up on byte-oriented matching against multibyte elements.
9097     // FIXME: We can compare the bytes in the correct order.
9098     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9099       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9100           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9101           << CharTy;
9102       return false;
9103     }
9104     // Figure out what value we're actually looking for (after converting to
9105     // the corresponding unsigned type if necessary).
9106     uint64_t DesiredVal;
9107     bool StopAtNull = false;
9108     switch (BuiltinOp) {
9109     case Builtin::BIstrchr:
9110     case Builtin::BI__builtin_strchr:
9111       // strchr compares directly to the passed integer, and therefore
9112       // always fails if given an int that is not a char.
9113       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9114                                                   E->getArg(1)->getType(),
9115                                                   Desired),
9116                                Desired))
9117         return ZeroInitialization(E);
9118       StopAtNull = true;
9119       LLVM_FALLTHROUGH;
9120     case Builtin::BImemchr:
9121     case Builtin::BI__builtin_memchr:
9122     case Builtin::BI__builtin_char_memchr:
9123       // memchr compares by converting both sides to unsigned char. That's also
9124       // correct for strchr if we get this far (to cope with plain char being
9125       // unsigned in the strchr case).
9126       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9127       break;
9128 
9129     case Builtin::BIwcschr:
9130     case Builtin::BI__builtin_wcschr:
9131       StopAtNull = true;
9132       LLVM_FALLTHROUGH;
9133     case Builtin::BIwmemchr:
9134     case Builtin::BI__builtin_wmemchr:
9135       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9136       DesiredVal = Desired.getZExtValue();
9137       break;
9138     }
9139 
9140     for (; MaxLength; --MaxLength) {
9141       APValue Char;
9142       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9143           !Char.isInt())
9144         return false;
9145       if (Char.getInt().getZExtValue() == DesiredVal)
9146         return true;
9147       if (StopAtNull && !Char.getInt())
9148         break;
9149       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9150         return false;
9151     }
9152     // Not found: return nullptr.
9153     return ZeroInitialization(E);
9154   }
9155 
9156   case Builtin::BImemcpy:
9157   case Builtin::BImemmove:
9158   case Builtin::BIwmemcpy:
9159   case Builtin::BIwmemmove:
9160     if (Info.getLangOpts().CPlusPlus11)
9161       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9162         << /*isConstexpr*/0 << /*isConstructor*/0
9163         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9164     else
9165       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9166     LLVM_FALLTHROUGH;
9167   case Builtin::BI__builtin_memcpy:
9168   case Builtin::BI__builtin_memmove:
9169   case Builtin::BI__builtin_wmemcpy:
9170   case Builtin::BI__builtin_wmemmove: {
9171     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9172                  BuiltinOp == Builtin::BIwmemmove ||
9173                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9174                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9175     bool Move = BuiltinOp == Builtin::BImemmove ||
9176                 BuiltinOp == Builtin::BIwmemmove ||
9177                 BuiltinOp == Builtin::BI__builtin_memmove ||
9178                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9179 
9180     // The result of mem* is the first argument.
9181     if (!Visit(E->getArg(0)))
9182       return false;
9183     LValue Dest = Result;
9184 
9185     LValue Src;
9186     if (!EvaluatePointer(E->getArg(1), Src, Info))
9187       return false;
9188 
9189     APSInt N;
9190     if (!EvaluateInteger(E->getArg(2), N, Info))
9191       return false;
9192     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9193 
9194     // If the size is zero, we treat this as always being a valid no-op.
9195     // (Even if one of the src and dest pointers is null.)
9196     if (!N)
9197       return true;
9198 
9199     // Otherwise, if either of the operands is null, we can't proceed. Don't
9200     // try to determine the type of the copied objects, because there aren't
9201     // any.
9202     if (!Src.Base || !Dest.Base) {
9203       APValue Val;
9204       (!Src.Base ? Src : Dest).moveInto(Val);
9205       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9206           << Move << WChar << !!Src.Base
9207           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9208       return false;
9209     }
9210     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9211       return false;
9212 
9213     // We require that Src and Dest are both pointers to arrays of
9214     // trivially-copyable type. (For the wide version, the designator will be
9215     // invalid if the designated object is not a wchar_t.)
9216     QualType T = Dest.Designator.getType(Info.Ctx);
9217     QualType SrcT = Src.Designator.getType(Info.Ctx);
9218     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9219       // FIXME: Consider using our bit_cast implementation to support this.
9220       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9221       return false;
9222     }
9223     if (T->isIncompleteType()) {
9224       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9225       return false;
9226     }
9227     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9228       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9229       return false;
9230     }
9231 
9232     // Figure out how many T's we're copying.
9233     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9234     if (!WChar) {
9235       uint64_t Remainder;
9236       llvm::APInt OrigN = N;
9237       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9238       if (Remainder) {
9239         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9240             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
9241             << (unsigned)TSize;
9242         return false;
9243       }
9244     }
9245 
9246     // Check that the copying will remain within the arrays, just so that we
9247     // can give a more meaningful diagnostic. This implicitly also checks that
9248     // N fits into 64 bits.
9249     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9250     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9251     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9252       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9253           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9254           << N.toString(10, /*Signed*/false);
9255       return false;
9256     }
9257     uint64_t NElems = N.getZExtValue();
9258     uint64_t NBytes = NElems * TSize;
9259 
9260     // Check for overlap.
9261     int Direction = 1;
9262     if (HasSameBase(Src, Dest)) {
9263       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9264       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9265       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9266         // Dest is inside the source region.
9267         if (!Move) {
9268           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9269           return false;
9270         }
9271         // For memmove and friends, copy backwards.
9272         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9273             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9274           return false;
9275         Direction = -1;
9276       } else if (!Move && SrcOffset >= DestOffset &&
9277                  SrcOffset - DestOffset < NBytes) {
9278         // Src is inside the destination region for memcpy: invalid.
9279         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9280         return false;
9281       }
9282     }
9283 
9284     while (true) {
9285       APValue Val;
9286       // FIXME: Set WantObjectRepresentation to true if we're copying a
9287       // char-like type?
9288       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9289           !handleAssignment(Info, E, Dest, T, Val))
9290         return false;
9291       // Do not iterate past the last element; if we're copying backwards, that
9292       // might take us off the start of the array.
9293       if (--NElems == 0)
9294         return true;
9295       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9296           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9297         return false;
9298     }
9299   }
9300 
9301   default:
9302     break;
9303   }
9304 
9305   return visitNonBuiltinCallExpr(E);
9306 }
9307 
9308 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9309                                      APValue &Result, const InitListExpr *ILE,
9310                                      QualType AllocType);
9311 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9312                                           APValue &Result,
9313                                           const CXXConstructExpr *CCE,
9314                                           QualType AllocType);
9315 
VisitCXXNewExpr(const CXXNewExpr * E)9316 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9317   if (!Info.getLangOpts().CPlusPlus20)
9318     Info.CCEDiag(E, diag::note_constexpr_new);
9319 
9320   // We cannot speculatively evaluate a delete expression.
9321   if (Info.SpeculativeEvaluationDepth)
9322     return false;
9323 
9324   FunctionDecl *OperatorNew = E->getOperatorNew();
9325 
9326   bool IsNothrow = false;
9327   bool IsPlacement = false;
9328   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9329       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9330     // FIXME Support array placement new.
9331     assert(E->getNumPlacementArgs() == 1);
9332     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9333       return false;
9334     if (Result.Designator.Invalid)
9335       return false;
9336     IsPlacement = true;
9337   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9338     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9339         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9340     return false;
9341   } else if (E->getNumPlacementArgs()) {
9342     // The only new-placement list we support is of the form (std::nothrow).
9343     //
9344     // FIXME: There is no restriction on this, but it's not clear that any
9345     // other form makes any sense. We get here for cases such as:
9346     //
9347     //   new (std::align_val_t{N}) X(int)
9348     //
9349     // (which should presumably be valid only if N is a multiple of
9350     // alignof(int), and in any case can't be deallocated unless N is
9351     // alignof(X) and X has new-extended alignment).
9352     if (E->getNumPlacementArgs() != 1 ||
9353         !E->getPlacementArg(0)->getType()->isNothrowT())
9354       return Error(E, diag::note_constexpr_new_placement);
9355 
9356     LValue Nothrow;
9357     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9358       return false;
9359     IsNothrow = true;
9360   }
9361 
9362   const Expr *Init = E->getInitializer();
9363   const InitListExpr *ResizedArrayILE = nullptr;
9364   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9365   bool ValueInit = false;
9366 
9367   QualType AllocType = E->getAllocatedType();
9368   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9369     const Expr *Stripped = *ArraySize;
9370     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9371          Stripped = ICE->getSubExpr())
9372       if (ICE->getCastKind() != CK_NoOp &&
9373           ICE->getCastKind() != CK_IntegralCast)
9374         break;
9375 
9376     llvm::APSInt ArrayBound;
9377     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9378       return false;
9379 
9380     // C++ [expr.new]p9:
9381     //   The expression is erroneous if:
9382     //   -- [...] its value before converting to size_t [or] applying the
9383     //      second standard conversion sequence is less than zero
9384     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9385       if (IsNothrow)
9386         return ZeroInitialization(E);
9387 
9388       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9389           << ArrayBound << (*ArraySize)->getSourceRange();
9390       return false;
9391     }
9392 
9393     //   -- its value is such that the size of the allocated object would
9394     //      exceed the implementation-defined limit
9395     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9396                                                 ArrayBound) >
9397         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9398       if (IsNothrow)
9399         return ZeroInitialization(E);
9400 
9401       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9402         << ArrayBound << (*ArraySize)->getSourceRange();
9403       return false;
9404     }
9405 
9406     //   -- the new-initializer is a braced-init-list and the number of
9407     //      array elements for which initializers are provided [...]
9408     //      exceeds the number of elements to initialize
9409     if (!Init) {
9410       // No initialization is performed.
9411     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9412                isa<ImplicitValueInitExpr>(Init)) {
9413       ValueInit = true;
9414     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9415       ResizedArrayCCE = CCE;
9416     } else {
9417       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9418       assert(CAT && "unexpected type for array initializer");
9419 
9420       unsigned Bits =
9421           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9422       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9423       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9424       if (InitBound.ugt(AllocBound)) {
9425         if (IsNothrow)
9426           return ZeroInitialization(E);
9427 
9428         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9429             << AllocBound.toString(10, /*Signed=*/false)
9430             << InitBound.toString(10, /*Signed=*/false)
9431             << (*ArraySize)->getSourceRange();
9432         return false;
9433       }
9434 
9435       // If the sizes differ, we must have an initializer list, and we need
9436       // special handling for this case when we initialize.
9437       if (InitBound != AllocBound)
9438         ResizedArrayILE = cast<InitListExpr>(Init);
9439     }
9440 
9441     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9442                                               ArrayType::Normal, 0);
9443   } else {
9444     assert(!AllocType->isArrayType() &&
9445            "array allocation with non-array new");
9446   }
9447 
9448   APValue *Val;
9449   if (IsPlacement) {
9450     AccessKinds AK = AK_Construct;
9451     struct FindObjectHandler {
9452       EvalInfo &Info;
9453       const Expr *E;
9454       QualType AllocType;
9455       const AccessKinds AccessKind;
9456       APValue *Value;
9457 
9458       typedef bool result_type;
9459       bool failed() { return false; }
9460       bool found(APValue &Subobj, QualType SubobjType) {
9461         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9462         // old name of the object to be used to name the new object.
9463         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9464           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9465             SubobjType << AllocType;
9466           return false;
9467         }
9468         Value = &Subobj;
9469         return true;
9470       }
9471       bool found(APSInt &Value, QualType SubobjType) {
9472         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9473         return false;
9474       }
9475       bool found(APFloat &Value, QualType SubobjType) {
9476         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9477         return false;
9478       }
9479     } Handler = {Info, E, AllocType, AK, nullptr};
9480 
9481     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9482     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9483       return false;
9484 
9485     Val = Handler.Value;
9486 
9487     // [basic.life]p1:
9488     //   The lifetime of an object o of type T ends when [...] the storage
9489     //   which the object occupies is [...] reused by an object that is not
9490     //   nested within o (6.6.2).
9491     *Val = APValue();
9492   } else {
9493     // Perform the allocation and obtain a pointer to the resulting object.
9494     Val = Info.createHeapAlloc(E, AllocType, Result);
9495     if (!Val)
9496       return false;
9497   }
9498 
9499   if (ValueInit) {
9500     ImplicitValueInitExpr VIE(AllocType);
9501     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9502       return false;
9503   } else if (ResizedArrayILE) {
9504     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9505                                   AllocType))
9506       return false;
9507   } else if (ResizedArrayCCE) {
9508     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9509                                        AllocType))
9510       return false;
9511   } else if (Init) {
9512     if (!EvaluateInPlace(*Val, Info, Result, Init))
9513       return false;
9514   } else if (!getDefaultInitValue(AllocType, *Val)) {
9515     return false;
9516   }
9517 
9518   // Array new returns a pointer to the first element, not a pointer to the
9519   // array.
9520   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9521     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9522 
9523   return true;
9524 }
9525 //===----------------------------------------------------------------------===//
9526 // Member Pointer Evaluation
9527 //===----------------------------------------------------------------------===//
9528 
9529 namespace {
9530 class MemberPointerExprEvaluator
9531   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9532   MemberPtr &Result;
9533 
Success(const ValueDecl * D)9534   bool Success(const ValueDecl *D) {
9535     Result = MemberPtr(D);
9536     return true;
9537   }
9538 public:
9539 
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)9540   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9541     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9542 
Success(const APValue & V,const Expr * E)9543   bool Success(const APValue &V, const Expr *E) {
9544     Result.setFrom(V);
9545     return true;
9546   }
ZeroInitialization(const Expr * E)9547   bool ZeroInitialization(const Expr *E) {
9548     return Success((const ValueDecl*)nullptr);
9549   }
9550 
9551   bool VisitCastExpr(const CastExpr *E);
9552   bool VisitUnaryAddrOf(const UnaryOperator *E);
9553 };
9554 } // end anonymous namespace
9555 
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)9556 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9557                                   EvalInfo &Info) {
9558   assert(!E->isValueDependent());
9559   assert(E->isRValue() && E->getType()->isMemberPointerType());
9560   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9561 }
9562 
VisitCastExpr(const CastExpr * E)9563 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9564   switch (E->getCastKind()) {
9565   default:
9566     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9567 
9568   case CK_NullToMemberPointer:
9569     VisitIgnoredValue(E->getSubExpr());
9570     return ZeroInitialization(E);
9571 
9572   case CK_BaseToDerivedMemberPointer: {
9573     if (!Visit(E->getSubExpr()))
9574       return false;
9575     if (E->path_empty())
9576       return true;
9577     // Base-to-derived member pointer casts store the path in derived-to-base
9578     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9579     // the wrong end of the derived->base arc, so stagger the path by one class.
9580     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9581     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9582          PathI != PathE; ++PathI) {
9583       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9584       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9585       if (!Result.castToDerived(Derived))
9586         return Error(E);
9587     }
9588     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9589     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9590       return Error(E);
9591     return true;
9592   }
9593 
9594   case CK_DerivedToBaseMemberPointer:
9595     if (!Visit(E->getSubExpr()))
9596       return false;
9597     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9598          PathE = E->path_end(); PathI != PathE; ++PathI) {
9599       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9600       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9601       if (!Result.castToBase(Base))
9602         return Error(E);
9603     }
9604     return true;
9605   }
9606 }
9607 
VisitUnaryAddrOf(const UnaryOperator * E)9608 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9609   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9610   // member can be formed.
9611   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9612 }
9613 
9614 //===----------------------------------------------------------------------===//
9615 // Record Evaluation
9616 //===----------------------------------------------------------------------===//
9617 
9618 namespace {
9619   class RecordExprEvaluator
9620   : public ExprEvaluatorBase<RecordExprEvaluator> {
9621     const LValue &This;
9622     APValue &Result;
9623   public:
9624 
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)9625     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9626       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9627 
Success(const APValue & V,const Expr * E)9628     bool Success(const APValue &V, const Expr *E) {
9629       Result = V;
9630       return true;
9631     }
ZeroInitialization(const Expr * E)9632     bool ZeroInitialization(const Expr *E) {
9633       return ZeroInitialization(E, E->getType());
9634     }
9635     bool ZeroInitialization(const Expr *E, QualType T);
9636 
VisitCallExpr(const CallExpr * E)9637     bool VisitCallExpr(const CallExpr *E) {
9638       return handleCallExpr(E, Result, &This);
9639     }
9640     bool VisitCastExpr(const CastExpr *E);
9641     bool VisitInitListExpr(const InitListExpr *E);
VisitCXXConstructExpr(const CXXConstructExpr * E)9642     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9643       return VisitCXXConstructExpr(E, E->getType());
9644     }
9645     bool VisitLambdaExpr(const LambdaExpr *E);
9646     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9647     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9648     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9649     bool VisitBinCmp(const BinaryOperator *E);
9650   };
9651 }
9652 
9653 /// Perform zero-initialization on an object of non-union class type.
9654 /// C++11 [dcl.init]p5:
9655 ///  To zero-initialize an object or reference of type T means:
9656 ///    [...]
9657 ///    -- if T is a (possibly cv-qualified) non-union class type,
9658 ///       each non-static data member and each base-class subobject is
9659 ///       zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)9660 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9661                                           const RecordDecl *RD,
9662                                           const LValue &This, APValue &Result) {
9663   assert(!RD->isUnion() && "Expected non-union class type");
9664   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9665   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9666                    std::distance(RD->field_begin(), RD->field_end()));
9667 
9668   if (RD->isInvalidDecl()) return false;
9669   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9670 
9671   if (CD) {
9672     unsigned Index = 0;
9673     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9674            End = CD->bases_end(); I != End; ++I, ++Index) {
9675       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9676       LValue Subobject = This;
9677       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9678         return false;
9679       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9680                                          Result.getStructBase(Index)))
9681         return false;
9682     }
9683   }
9684 
9685   for (const auto *I : RD->fields()) {
9686     // -- if T is a reference type, no initialization is performed.
9687     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9688       continue;
9689 
9690     LValue Subobject = This;
9691     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9692       return false;
9693 
9694     ImplicitValueInitExpr VIE(I->getType());
9695     if (!EvaluateInPlace(
9696           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9697       return false;
9698   }
9699 
9700   return true;
9701 }
9702 
ZeroInitialization(const Expr * E,QualType T)9703 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9704   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9705   if (RD->isInvalidDecl()) return false;
9706   if (RD->isUnion()) {
9707     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9708     // object's first non-static named data member is zero-initialized
9709     RecordDecl::field_iterator I = RD->field_begin();
9710     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9711       ++I;
9712     if (I == RD->field_end()) {
9713       Result = APValue((const FieldDecl*)nullptr);
9714       return true;
9715     }
9716 
9717     LValue Subobject = This;
9718     if (!HandleLValueMember(Info, E, Subobject, *I))
9719       return false;
9720     Result = APValue(*I);
9721     ImplicitValueInitExpr VIE(I->getType());
9722     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9723   }
9724 
9725   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9726     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9727     return false;
9728   }
9729 
9730   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9731 }
9732 
VisitCastExpr(const CastExpr * E)9733 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9734   switch (E->getCastKind()) {
9735   default:
9736     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9737 
9738   case CK_ConstructorConversion:
9739     return Visit(E->getSubExpr());
9740 
9741   case CK_DerivedToBase:
9742   case CK_UncheckedDerivedToBase: {
9743     APValue DerivedObject;
9744     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9745       return false;
9746     if (!DerivedObject.isStruct())
9747       return Error(E->getSubExpr());
9748 
9749     // Derived-to-base rvalue conversion: just slice off the derived part.
9750     APValue *Value = &DerivedObject;
9751     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9752     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9753          PathE = E->path_end(); PathI != PathE; ++PathI) {
9754       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9755       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9756       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9757       RD = Base;
9758     }
9759     Result = *Value;
9760     return true;
9761   }
9762   }
9763 }
9764 
VisitInitListExpr(const InitListExpr * E)9765 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9766   if (E->isTransparent())
9767     return Visit(E->getInit(0));
9768 
9769   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9770   if (RD->isInvalidDecl()) return false;
9771   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9772   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9773 
9774   EvalInfo::EvaluatingConstructorRAII EvalObj(
9775       Info,
9776       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9777       CXXRD && CXXRD->getNumBases());
9778 
9779   if (RD->isUnion()) {
9780     const FieldDecl *Field = E->getInitializedFieldInUnion();
9781     Result = APValue(Field);
9782     if (!Field)
9783       return true;
9784 
9785     // If the initializer list for a union does not contain any elements, the
9786     // first element of the union is value-initialized.
9787     // FIXME: The element should be initialized from an initializer list.
9788     //        Is this difference ever observable for initializer lists which
9789     //        we don't build?
9790     ImplicitValueInitExpr VIE(Field->getType());
9791     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9792 
9793     LValue Subobject = This;
9794     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9795       return false;
9796 
9797     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9798     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9799                                   isa<CXXDefaultInitExpr>(InitExpr));
9800 
9801     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9802   }
9803 
9804   if (!Result.hasValue())
9805     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9806                      std::distance(RD->field_begin(), RD->field_end()));
9807   unsigned ElementNo = 0;
9808   bool Success = true;
9809 
9810   // Initialize base classes.
9811   if (CXXRD && CXXRD->getNumBases()) {
9812     for (const auto &Base : CXXRD->bases()) {
9813       assert(ElementNo < E->getNumInits() && "missing init for base class");
9814       const Expr *Init = E->getInit(ElementNo);
9815 
9816       LValue Subobject = This;
9817       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9818         return false;
9819 
9820       APValue &FieldVal = Result.getStructBase(ElementNo);
9821       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9822         if (!Info.noteFailure())
9823           return false;
9824         Success = false;
9825       }
9826       ++ElementNo;
9827     }
9828 
9829     EvalObj.finishedConstructingBases();
9830   }
9831 
9832   // Initialize members.
9833   for (const auto *Field : RD->fields()) {
9834     // Anonymous bit-fields are not considered members of the class for
9835     // purposes of aggregate initialization.
9836     if (Field->isUnnamedBitfield())
9837       continue;
9838 
9839     LValue Subobject = This;
9840 
9841     bool HaveInit = ElementNo < E->getNumInits();
9842 
9843     // FIXME: Diagnostics here should point to the end of the initializer
9844     // list, not the start.
9845     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9846                             Subobject, Field, &Layout))
9847       return false;
9848 
9849     // Perform an implicit value-initialization for members beyond the end of
9850     // the initializer list.
9851     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9852     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9853 
9854     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9855     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9856                                   isa<CXXDefaultInitExpr>(Init));
9857 
9858     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9859     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9860         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9861                                                        FieldVal, Field))) {
9862       if (!Info.noteFailure())
9863         return false;
9864       Success = false;
9865     }
9866   }
9867 
9868   EvalObj.finishedConstructingFields();
9869 
9870   return Success;
9871 }
9872 
VisitCXXConstructExpr(const CXXConstructExpr * E,QualType T)9873 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9874                                                 QualType T) {
9875   // Note that E's type is not necessarily the type of our class here; we might
9876   // be initializing an array element instead.
9877   const CXXConstructorDecl *FD = E->getConstructor();
9878   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9879 
9880   bool ZeroInit = E->requiresZeroInitialization();
9881   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9882     // If we've already performed zero-initialization, we're already done.
9883     if (Result.hasValue())
9884       return true;
9885 
9886     if (ZeroInit)
9887       return ZeroInitialization(E, T);
9888 
9889     return getDefaultInitValue(T, Result);
9890   }
9891 
9892   const FunctionDecl *Definition = nullptr;
9893   auto Body = FD->getBody(Definition);
9894 
9895   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9896     return false;
9897 
9898   // Avoid materializing a temporary for an elidable copy/move constructor.
9899   if (E->isElidable() && !ZeroInit)
9900     if (const MaterializeTemporaryExpr *ME
9901           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9902       return Visit(ME->getSubExpr());
9903 
9904   if (ZeroInit && !ZeroInitialization(E, T))
9905     return false;
9906 
9907   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9908   return HandleConstructorCall(E, This, Args,
9909                                cast<CXXConstructorDecl>(Definition), Info,
9910                                Result);
9911 }
9912 
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * E)9913 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9914     const CXXInheritedCtorInitExpr *E) {
9915   if (!Info.CurrentCall) {
9916     assert(Info.checkingPotentialConstantExpression());
9917     return false;
9918   }
9919 
9920   const CXXConstructorDecl *FD = E->getConstructor();
9921   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9922     return false;
9923 
9924   const FunctionDecl *Definition = nullptr;
9925   auto Body = FD->getBody(Definition);
9926 
9927   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9928     return false;
9929 
9930   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9931                                cast<CXXConstructorDecl>(Definition), Info,
9932                                Result);
9933 }
9934 
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)9935 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9936     const CXXStdInitializerListExpr *E) {
9937   const ConstantArrayType *ArrayType =
9938       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9939 
9940   LValue Array;
9941   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9942     return false;
9943 
9944   // Get a pointer to the first element of the array.
9945   Array.addArray(Info, E, ArrayType);
9946 
9947   auto InvalidType = [&] {
9948     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9949       << E->getType();
9950     return false;
9951   };
9952 
9953   // FIXME: Perform the checks on the field types in SemaInit.
9954   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9955   RecordDecl::field_iterator Field = Record->field_begin();
9956   if (Field == Record->field_end())
9957     return InvalidType();
9958 
9959   // Start pointer.
9960   if (!Field->getType()->isPointerType() ||
9961       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9962                             ArrayType->getElementType()))
9963     return InvalidType();
9964 
9965   // FIXME: What if the initializer_list type has base classes, etc?
9966   Result = APValue(APValue::UninitStruct(), 0, 2);
9967   Array.moveInto(Result.getStructField(0));
9968 
9969   if (++Field == Record->field_end())
9970     return InvalidType();
9971 
9972   if (Field->getType()->isPointerType() &&
9973       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9974                            ArrayType->getElementType())) {
9975     // End pointer.
9976     if (!HandleLValueArrayAdjustment(Info, E, Array,
9977                                      ArrayType->getElementType(),
9978                                      ArrayType->getSize().getZExtValue()))
9979       return false;
9980     Array.moveInto(Result.getStructField(1));
9981   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9982     // Length.
9983     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9984   else
9985     return InvalidType();
9986 
9987   if (++Field != Record->field_end())
9988     return InvalidType();
9989 
9990   return true;
9991 }
9992 
VisitLambdaExpr(const LambdaExpr * E)9993 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9994   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9995   if (ClosureClass->isInvalidDecl())
9996     return false;
9997 
9998   const size_t NumFields =
9999       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10000 
10001   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10002                                             E->capture_init_end()) &&
10003          "The number of lambda capture initializers should equal the number of "
10004          "fields within the closure type");
10005 
10006   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10007   // Iterate through all the lambda's closure object's fields and initialize
10008   // them.
10009   auto *CaptureInitIt = E->capture_init_begin();
10010   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10011   bool Success = true;
10012   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10013   for (const auto *Field : ClosureClass->fields()) {
10014     assert(CaptureInitIt != E->capture_init_end());
10015     // Get the initializer for this field
10016     Expr *const CurFieldInit = *CaptureInitIt++;
10017 
10018     // If there is no initializer, either this is a VLA or an error has
10019     // occurred.
10020     if (!CurFieldInit)
10021       return Error(E);
10022 
10023     LValue Subobject = This;
10024 
10025     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10026       return false;
10027 
10028     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10029     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10030       if (!Info.keepEvaluatingAfterFailure())
10031         return false;
10032       Success = false;
10033     }
10034     ++CaptureIt;
10035   }
10036   return Success;
10037 }
10038 
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10039 static bool EvaluateRecord(const Expr *E, const LValue &This,
10040                            APValue &Result, EvalInfo &Info) {
10041   assert(!E->isValueDependent());
10042   assert(E->isRValue() && E->getType()->isRecordType() &&
10043          "can't evaluate expression as a record rvalue");
10044   return RecordExprEvaluator(Info, This, Result).Visit(E);
10045 }
10046 
10047 //===----------------------------------------------------------------------===//
10048 // Temporary Evaluation
10049 //
10050 // Temporaries are represented in the AST as rvalues, but generally behave like
10051 // lvalues. The full-object of which the temporary is a subobject is implicitly
10052 // materialized so that a reference can bind to it.
10053 //===----------------------------------------------------------------------===//
10054 namespace {
10055 class TemporaryExprEvaluator
10056   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10057 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)10058   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10059     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10060 
10061   /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)10062   bool VisitConstructExpr(const Expr *E) {
10063     APValue &Value = Info.CurrentCall->createTemporary(
10064         E, E->getType(), ScopeKind::FullExpression, Result);
10065     return EvaluateInPlace(Value, Info, Result, E);
10066   }
10067 
VisitCastExpr(const CastExpr * E)10068   bool VisitCastExpr(const CastExpr *E) {
10069     switch (E->getCastKind()) {
10070     default:
10071       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10072 
10073     case CK_ConstructorConversion:
10074       return VisitConstructExpr(E->getSubExpr());
10075     }
10076   }
VisitInitListExpr(const InitListExpr * E)10077   bool VisitInitListExpr(const InitListExpr *E) {
10078     return VisitConstructExpr(E);
10079   }
VisitCXXConstructExpr(const CXXConstructExpr * E)10080   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10081     return VisitConstructExpr(E);
10082   }
VisitCallExpr(const CallExpr * E)10083   bool VisitCallExpr(const CallExpr *E) {
10084     return VisitConstructExpr(E);
10085   }
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10086   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10087     return VisitConstructExpr(E);
10088   }
VisitLambdaExpr(const LambdaExpr * E)10089   bool VisitLambdaExpr(const LambdaExpr *E) {
10090     return VisitConstructExpr(E);
10091   }
10092 };
10093 } // end anonymous namespace
10094 
10095 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)10096 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10097   assert(!E->isValueDependent());
10098   assert(E->isRValue() && E->getType()->isRecordType());
10099   return TemporaryExprEvaluator(Info, Result).Visit(E);
10100 }
10101 
10102 //===----------------------------------------------------------------------===//
10103 // Vector Evaluation
10104 //===----------------------------------------------------------------------===//
10105 
10106 namespace {
10107   class VectorExprEvaluator
10108   : public ExprEvaluatorBase<VectorExprEvaluator> {
10109     APValue &Result;
10110   public:
10111 
VectorExprEvaluator(EvalInfo & info,APValue & Result)10112     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10113       : ExprEvaluatorBaseTy(info), Result(Result) {}
10114 
Success(ArrayRef<APValue> V,const Expr * E)10115     bool Success(ArrayRef<APValue> V, const Expr *E) {
10116       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10117       // FIXME: remove this APValue copy.
10118       Result = APValue(V.data(), V.size());
10119       return true;
10120     }
Success(const APValue & V,const Expr * E)10121     bool Success(const APValue &V, const Expr *E) {
10122       assert(V.isVector());
10123       Result = V;
10124       return true;
10125     }
10126     bool ZeroInitialization(const Expr *E);
10127 
VisitUnaryReal(const UnaryOperator * E)10128     bool VisitUnaryReal(const UnaryOperator *E)
10129       { return Visit(E->getSubExpr()); }
10130     bool VisitCastExpr(const CastExpr* E);
10131     bool VisitInitListExpr(const InitListExpr *E);
10132     bool VisitUnaryImag(const UnaryOperator *E);
10133     bool VisitBinaryOperator(const BinaryOperator *E);
10134     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10135     //                 conditional select), shufflevector, ExtVectorElementExpr
10136   };
10137 } // end anonymous namespace
10138 
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)10139 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10140   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
10141   return VectorExprEvaluator(Info, Result).Visit(E);
10142 }
10143 
VisitCastExpr(const CastExpr * E)10144 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10145   const VectorType *VTy = E->getType()->castAs<VectorType>();
10146   unsigned NElts = VTy->getNumElements();
10147 
10148   const Expr *SE = E->getSubExpr();
10149   QualType SETy = SE->getType();
10150 
10151   switch (E->getCastKind()) {
10152   case CK_VectorSplat: {
10153     APValue Val = APValue();
10154     if (SETy->isIntegerType()) {
10155       APSInt IntResult;
10156       if (!EvaluateInteger(SE, IntResult, Info))
10157         return false;
10158       Val = APValue(std::move(IntResult));
10159     } else if (SETy->isRealFloatingType()) {
10160       APFloat FloatResult(0.0);
10161       if (!EvaluateFloat(SE, FloatResult, Info))
10162         return false;
10163       Val = APValue(std::move(FloatResult));
10164     } else {
10165       return Error(E);
10166     }
10167 
10168     // Splat and create vector APValue.
10169     SmallVector<APValue, 4> Elts(NElts, Val);
10170     return Success(Elts, E);
10171   }
10172   case CK_BitCast: {
10173     // Evaluate the operand into an APInt we can extract from.
10174     llvm::APInt SValInt;
10175     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10176       return false;
10177     // Extract the elements
10178     QualType EltTy = VTy->getElementType();
10179     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10180     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10181     SmallVector<APValue, 4> Elts;
10182     if (EltTy->isRealFloatingType()) {
10183       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10184       unsigned FloatEltSize = EltSize;
10185       if (&Sem == &APFloat::x87DoubleExtended())
10186         FloatEltSize = 80;
10187       for (unsigned i = 0; i < NElts; i++) {
10188         llvm::APInt Elt;
10189         if (BigEndian)
10190           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10191         else
10192           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10193         Elts.push_back(APValue(APFloat(Sem, Elt)));
10194       }
10195     } else if (EltTy->isIntegerType()) {
10196       for (unsigned i = 0; i < NElts; i++) {
10197         llvm::APInt Elt;
10198         if (BigEndian)
10199           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10200         else
10201           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10202         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
10203       }
10204     } else {
10205       return Error(E);
10206     }
10207     return Success(Elts, E);
10208   }
10209   default:
10210     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10211   }
10212 }
10213 
10214 bool
VisitInitListExpr(const InitListExpr * E)10215 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10216   const VectorType *VT = E->getType()->castAs<VectorType>();
10217   unsigned NumInits = E->getNumInits();
10218   unsigned NumElements = VT->getNumElements();
10219 
10220   QualType EltTy = VT->getElementType();
10221   SmallVector<APValue, 4> Elements;
10222 
10223   // The number of initializers can be less than the number of
10224   // vector elements. For OpenCL, this can be due to nested vector
10225   // initialization. For GCC compatibility, missing trailing elements
10226   // should be initialized with zeroes.
10227   unsigned CountInits = 0, CountElts = 0;
10228   while (CountElts < NumElements) {
10229     // Handle nested vector initialization.
10230     if (CountInits < NumInits
10231         && E->getInit(CountInits)->getType()->isVectorType()) {
10232       APValue v;
10233       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10234         return Error(E);
10235       unsigned vlen = v.getVectorLength();
10236       for (unsigned j = 0; j < vlen; j++)
10237         Elements.push_back(v.getVectorElt(j));
10238       CountElts += vlen;
10239     } else if (EltTy->isIntegerType()) {
10240       llvm::APSInt sInt(32);
10241       if (CountInits < NumInits) {
10242         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10243           return false;
10244       } else // trailing integer zero.
10245         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10246       Elements.push_back(APValue(sInt));
10247       CountElts++;
10248     } else {
10249       llvm::APFloat f(0.0);
10250       if (CountInits < NumInits) {
10251         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10252           return false;
10253       } else // trailing float zero.
10254         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10255       Elements.push_back(APValue(f));
10256       CountElts++;
10257     }
10258     CountInits++;
10259   }
10260   return Success(Elements, E);
10261 }
10262 
10263 bool
ZeroInitialization(const Expr * E)10264 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10265   const auto *VT = E->getType()->castAs<VectorType>();
10266   QualType EltTy = VT->getElementType();
10267   APValue ZeroElement;
10268   if (EltTy->isIntegerType())
10269     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10270   else
10271     ZeroElement =
10272         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10273 
10274   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10275   return Success(Elements, E);
10276 }
10277 
VisitUnaryImag(const UnaryOperator * E)10278 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10279   VisitIgnoredValue(E->getSubExpr());
10280   return ZeroInitialization(E);
10281 }
10282 
VisitBinaryOperator(const BinaryOperator * E)10283 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10284   BinaryOperatorKind Op = E->getOpcode();
10285   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10286          "Operation not supported on vector types");
10287 
10288   if (Op == BO_Comma)
10289     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10290 
10291   Expr *LHS = E->getLHS();
10292   Expr *RHS = E->getRHS();
10293 
10294   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10295          "Must both be vector types");
10296   // Checking JUST the types are the same would be fine, except shifts don't
10297   // need to have their types be the same (since you always shift by an int).
10298   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
10299              E->getType()->getAs<VectorType>()->getNumElements() &&
10300          RHS->getType()->getAs<VectorType>()->getNumElements() ==
10301              E->getType()->getAs<VectorType>()->getNumElements() &&
10302          "All operands must be the same size.");
10303 
10304   APValue LHSValue;
10305   APValue RHSValue;
10306   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10307   if (!LHSOK && !Info.noteFailure())
10308     return false;
10309   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10310     return false;
10311 
10312   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10313     return false;
10314 
10315   return Success(LHSValue, E);
10316 }
10317 
10318 //===----------------------------------------------------------------------===//
10319 // Array Evaluation
10320 //===----------------------------------------------------------------------===//
10321 
10322 namespace {
10323   class ArrayExprEvaluator
10324   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10325     const LValue &This;
10326     APValue &Result;
10327   public:
10328 
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)10329     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10330       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10331 
Success(const APValue & V,const Expr * E)10332     bool Success(const APValue &V, const Expr *E) {
10333       assert(V.isArray() && "expected array");
10334       Result = V;
10335       return true;
10336     }
10337 
ZeroInitialization(const Expr * E)10338     bool ZeroInitialization(const Expr *E) {
10339       const ConstantArrayType *CAT =
10340           Info.Ctx.getAsConstantArrayType(E->getType());
10341       if (!CAT) {
10342         if (E->getType()->isIncompleteArrayType()) {
10343           // We can be asked to zero-initialize a flexible array member; this
10344           // is represented as an ImplicitValueInitExpr of incomplete array
10345           // type. In this case, the array has zero elements.
10346           Result = APValue(APValue::UninitArray(), 0, 0);
10347           return true;
10348         }
10349         // FIXME: We could handle VLAs here.
10350         return Error(E);
10351       }
10352 
10353       Result = APValue(APValue::UninitArray(), 0,
10354                        CAT->getSize().getZExtValue());
10355       if (!Result.hasArrayFiller()) return true;
10356 
10357       // Zero-initialize all elements.
10358       LValue Subobject = This;
10359       Subobject.addArray(Info, E, CAT);
10360       ImplicitValueInitExpr VIE(CAT->getElementType());
10361       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10362     }
10363 
VisitCallExpr(const CallExpr * E)10364     bool VisitCallExpr(const CallExpr *E) {
10365       return handleCallExpr(E, Result, &This);
10366     }
10367     bool VisitInitListExpr(const InitListExpr *E,
10368                            QualType AllocType = QualType());
10369     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10370     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10371     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10372                                const LValue &Subobject,
10373                                APValue *Value, QualType Type);
VisitStringLiteral(const StringLiteral * E,QualType AllocType=QualType ())10374     bool VisitStringLiteral(const StringLiteral *E,
10375                             QualType AllocType = QualType()) {
10376       expandStringLiteral(Info, E, Result, AllocType);
10377       return true;
10378     }
10379   };
10380 } // end anonymous namespace
10381 
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10382 static bool EvaluateArray(const Expr *E, const LValue &This,
10383                           APValue &Result, EvalInfo &Info) {
10384   assert(!E->isValueDependent());
10385   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10386   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10387 }
10388 
EvaluateArrayNewInitList(EvalInfo & Info,LValue & This,APValue & Result,const InitListExpr * ILE,QualType AllocType)10389 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10390                                      APValue &Result, const InitListExpr *ILE,
10391                                      QualType AllocType) {
10392   assert(!ILE->isValueDependent());
10393   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10394          "not an array rvalue");
10395   return ArrayExprEvaluator(Info, This, Result)
10396       .VisitInitListExpr(ILE, AllocType);
10397 }
10398 
EvaluateArrayNewConstructExpr(EvalInfo & Info,LValue & This,APValue & Result,const CXXConstructExpr * CCE,QualType AllocType)10399 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10400                                           APValue &Result,
10401                                           const CXXConstructExpr *CCE,
10402                                           QualType AllocType) {
10403   assert(!CCE->isValueDependent());
10404   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10405          "not an array rvalue");
10406   return ArrayExprEvaluator(Info, This, Result)
10407       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10408 }
10409 
10410 // Return true iff the given array filler may depend on the element index.
MaybeElementDependentArrayFiller(const Expr * FillerExpr)10411 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10412   // For now, just allow non-class value-initialization and initialization
10413   // lists comprised of them.
10414   if (isa<ImplicitValueInitExpr>(FillerExpr))
10415     return false;
10416   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10417     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10418       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10419         return true;
10420     }
10421     return false;
10422   }
10423   return true;
10424 }
10425 
VisitInitListExpr(const InitListExpr * E,QualType AllocType)10426 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10427                                            QualType AllocType) {
10428   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10429       AllocType.isNull() ? E->getType() : AllocType);
10430   if (!CAT)
10431     return Error(E);
10432 
10433   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10434   // an appropriately-typed string literal enclosed in braces.
10435   if (E->isStringLiteralInit()) {
10436     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10437     // FIXME: Support ObjCEncodeExpr here once we support it in
10438     // ArrayExprEvaluator generally.
10439     if (!SL)
10440       return Error(E);
10441     return VisitStringLiteral(SL, AllocType);
10442   }
10443 
10444   bool Success = true;
10445 
10446   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10447          "zero-initialized array shouldn't have any initialized elts");
10448   APValue Filler;
10449   if (Result.isArray() && Result.hasArrayFiller())
10450     Filler = Result.getArrayFiller();
10451 
10452   unsigned NumEltsToInit = E->getNumInits();
10453   unsigned NumElts = CAT->getSize().getZExtValue();
10454   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10455 
10456   // If the initializer might depend on the array index, run it for each
10457   // array element.
10458   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10459     NumEltsToInit = NumElts;
10460 
10461   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10462                           << NumEltsToInit << ".\n");
10463 
10464   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10465 
10466   // If the array was previously zero-initialized, preserve the
10467   // zero-initialized values.
10468   if (Filler.hasValue()) {
10469     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10470       Result.getArrayInitializedElt(I) = Filler;
10471     if (Result.hasArrayFiller())
10472       Result.getArrayFiller() = Filler;
10473   }
10474 
10475   LValue Subobject = This;
10476   Subobject.addArray(Info, E, CAT);
10477   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10478     const Expr *Init =
10479         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10480     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10481                          Info, Subobject, Init) ||
10482         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10483                                      CAT->getElementType(), 1)) {
10484       if (!Info.noteFailure())
10485         return false;
10486       Success = false;
10487     }
10488   }
10489 
10490   if (!Result.hasArrayFiller())
10491     return Success;
10492 
10493   // If we get here, we have a trivial filler, which we can just evaluate
10494   // once and splat over the rest of the array elements.
10495   assert(FillerExpr && "no array filler for incomplete init list");
10496   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10497                          FillerExpr) && Success;
10498 }
10499 
VisitArrayInitLoopExpr(const ArrayInitLoopExpr * E)10500 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10501   LValue CommonLV;
10502   if (E->getCommonExpr() &&
10503       !Evaluate(Info.CurrentCall->createTemporary(
10504                     E->getCommonExpr(),
10505                     getStorageType(Info.Ctx, E->getCommonExpr()),
10506                     ScopeKind::FullExpression, CommonLV),
10507                 Info, E->getCommonExpr()->getSourceExpr()))
10508     return false;
10509 
10510   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10511 
10512   uint64_t Elements = CAT->getSize().getZExtValue();
10513   Result = APValue(APValue::UninitArray(), Elements, Elements);
10514 
10515   LValue Subobject = This;
10516   Subobject.addArray(Info, E, CAT);
10517 
10518   bool Success = true;
10519   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10520     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10521                          Info, Subobject, E->getSubExpr()) ||
10522         !HandleLValueArrayAdjustment(Info, E, Subobject,
10523                                      CAT->getElementType(), 1)) {
10524       if (!Info.noteFailure())
10525         return false;
10526       Success = false;
10527     }
10528   }
10529 
10530   return Success;
10531 }
10532 
VisitCXXConstructExpr(const CXXConstructExpr * E)10533 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10534   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10535 }
10536 
VisitCXXConstructExpr(const CXXConstructExpr * E,const LValue & Subobject,APValue * Value,QualType Type)10537 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10538                                                const LValue &Subobject,
10539                                                APValue *Value,
10540                                                QualType Type) {
10541   bool HadZeroInit = Value->hasValue();
10542 
10543   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10544     unsigned N = CAT->getSize().getZExtValue();
10545 
10546     // Preserve the array filler if we had prior zero-initialization.
10547     APValue Filler =
10548       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10549                                              : APValue();
10550 
10551     *Value = APValue(APValue::UninitArray(), N, N);
10552 
10553     if (HadZeroInit)
10554       for (unsigned I = 0; I != N; ++I)
10555         Value->getArrayInitializedElt(I) = Filler;
10556 
10557     // Initialize the elements.
10558     LValue ArrayElt = Subobject;
10559     ArrayElt.addArray(Info, E, CAT);
10560     for (unsigned I = 0; I != N; ++I)
10561       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10562                                  CAT->getElementType()) ||
10563           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10564                                        CAT->getElementType(), 1))
10565         return false;
10566 
10567     return true;
10568   }
10569 
10570   if (!Type->isRecordType())
10571     return Error(E);
10572 
10573   return RecordExprEvaluator(Info, Subobject, *Value)
10574              .VisitCXXConstructExpr(E, Type);
10575 }
10576 
10577 //===----------------------------------------------------------------------===//
10578 // Integer Evaluation
10579 //
10580 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10581 // types and back in constant folding. Integer values are thus represented
10582 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10583 //===----------------------------------------------------------------------===//
10584 
10585 namespace {
10586 class IntExprEvaluator
10587         : public ExprEvaluatorBase<IntExprEvaluator> {
10588   APValue &Result;
10589 public:
IntExprEvaluator(EvalInfo & info,APValue & result)10590   IntExprEvaluator(EvalInfo &info, APValue &result)
10591       : ExprEvaluatorBaseTy(info), Result(result) {}
10592 
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)10593   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10594     assert(E->getType()->isIntegralOrEnumerationType() &&
10595            "Invalid evaluation result.");
10596     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10597            "Invalid evaluation result.");
10598     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10599            "Invalid evaluation result.");
10600     Result = APValue(SI);
10601     return true;
10602   }
Success(const llvm::APSInt & SI,const Expr * E)10603   bool Success(const llvm::APSInt &SI, const Expr *E) {
10604     return Success(SI, E, Result);
10605   }
10606 
Success(const llvm::APInt & I,const Expr * E,APValue & Result)10607   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10608     assert(E->getType()->isIntegralOrEnumerationType() &&
10609            "Invalid evaluation result.");
10610     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10611            "Invalid evaluation result.");
10612     Result = APValue(APSInt(I));
10613     Result.getInt().setIsUnsigned(
10614                             E->getType()->isUnsignedIntegerOrEnumerationType());
10615     return true;
10616   }
Success(const llvm::APInt & I,const Expr * E)10617   bool Success(const llvm::APInt &I, const Expr *E) {
10618     return Success(I, E, Result);
10619   }
10620 
Success(uint64_t Value,const Expr * E,APValue & Result)10621   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10622     assert(E->getType()->isIntegralOrEnumerationType() &&
10623            "Invalid evaluation result.");
10624     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10625     return true;
10626   }
Success(uint64_t Value,const Expr * E)10627   bool Success(uint64_t Value, const Expr *E) {
10628     return Success(Value, E, Result);
10629   }
10630 
Success(CharUnits Size,const Expr * E)10631   bool Success(CharUnits Size, const Expr *E) {
10632     return Success(Size.getQuantity(), E);
10633   }
10634 
Success(const APValue & V,const Expr * E)10635   bool Success(const APValue &V, const Expr *E) {
10636     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10637       Result = V;
10638       return true;
10639     }
10640     return Success(V.getInt(), E);
10641   }
10642 
ZeroInitialization(const Expr * E)10643   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10644 
10645   //===--------------------------------------------------------------------===//
10646   //                            Visitor Methods
10647   //===--------------------------------------------------------------------===//
10648 
VisitIntegerLiteral(const IntegerLiteral * E)10649   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10650     return Success(E->getValue(), E);
10651   }
VisitCharacterLiteral(const CharacterLiteral * E)10652   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10653     return Success(E->getValue(), E);
10654   }
10655 
10656   bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)10657   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10658     if (CheckReferencedDecl(E, E->getDecl()))
10659       return true;
10660 
10661     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10662   }
VisitMemberExpr(const MemberExpr * E)10663   bool VisitMemberExpr(const MemberExpr *E) {
10664     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10665       VisitIgnoredBaseExpression(E->getBase());
10666       return true;
10667     }
10668 
10669     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10670   }
10671 
10672   bool VisitCallExpr(const CallExpr *E);
10673   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10674   bool VisitBinaryOperator(const BinaryOperator *E);
10675   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10676   bool VisitUnaryOperator(const UnaryOperator *E);
10677 
10678   bool VisitCastExpr(const CastExpr* E);
10679   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10680 
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)10681   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10682     return Success(E->getValue(), E);
10683   }
10684 
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)10685   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10686     return Success(E->getValue(), E);
10687   }
10688 
VisitArrayInitIndexExpr(const ArrayInitIndexExpr * E)10689   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10690     if (Info.ArrayInitIndex == uint64_t(-1)) {
10691       // We were asked to evaluate this subexpression independent of the
10692       // enclosing ArrayInitLoopExpr. We can't do that.
10693       Info.FFDiag(E);
10694       return false;
10695     }
10696     return Success(Info.ArrayInitIndex, E);
10697   }
10698 
10699   // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)10700   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10701     return ZeroInitialization(E);
10702   }
10703 
VisitTypeTraitExpr(const TypeTraitExpr * E)10704   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10705     return Success(E->getValue(), E);
10706   }
10707 
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)10708   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10709     return Success(E->getValue(), E);
10710   }
10711 
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)10712   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10713     return Success(E->getValue(), E);
10714   }
10715 
10716   bool VisitUnaryReal(const UnaryOperator *E);
10717   bool VisitUnaryImag(const UnaryOperator *E);
10718 
10719   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10720   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10721   bool VisitSourceLocExpr(const SourceLocExpr *E);
10722   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10723   bool VisitRequiresExpr(const RequiresExpr *E);
10724   // FIXME: Missing: array subscript of vector, member of vector
10725 };
10726 
10727 class FixedPointExprEvaluator
10728     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10729   APValue &Result;
10730 
10731  public:
FixedPointExprEvaluator(EvalInfo & info,APValue & result)10732   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10733       : ExprEvaluatorBaseTy(info), Result(result) {}
10734 
Success(const llvm::APInt & I,const Expr * E)10735   bool Success(const llvm::APInt &I, const Expr *E) {
10736     return Success(
10737         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10738   }
10739 
Success(uint64_t Value,const Expr * E)10740   bool Success(uint64_t Value, const Expr *E) {
10741     return Success(
10742         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10743   }
10744 
Success(const APValue & V,const Expr * E)10745   bool Success(const APValue &V, const Expr *E) {
10746     return Success(V.getFixedPoint(), E);
10747   }
10748 
Success(const APFixedPoint & V,const Expr * E)10749   bool Success(const APFixedPoint &V, const Expr *E) {
10750     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10751     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10752            "Invalid evaluation result.");
10753     Result = APValue(V);
10754     return true;
10755   }
10756 
10757   //===--------------------------------------------------------------------===//
10758   //                            Visitor Methods
10759   //===--------------------------------------------------------------------===//
10760 
VisitFixedPointLiteral(const FixedPointLiteral * E)10761   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10762     return Success(E->getValue(), E);
10763   }
10764 
10765   bool VisitCastExpr(const CastExpr *E);
10766   bool VisitUnaryOperator(const UnaryOperator *E);
10767   bool VisitBinaryOperator(const BinaryOperator *E);
10768 };
10769 } // end anonymous namespace
10770 
10771 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10772 /// produce either the integer value or a pointer.
10773 ///
10774 /// GCC has a heinous extension which folds casts between pointer types and
10775 /// pointer-sized integral types. We support this by allowing the evaluation of
10776 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10777 /// Some simple arithmetic on such values is supported (they are treated much
10778 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)10779 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10780                                     EvalInfo &Info) {
10781   assert(!E->isValueDependent());
10782   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10783   return IntExprEvaluator(Info, Result).Visit(E);
10784 }
10785 
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)10786 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10787   assert(!E->isValueDependent());
10788   APValue Val;
10789   if (!EvaluateIntegerOrLValue(E, Val, Info))
10790     return false;
10791   if (!Val.isInt()) {
10792     // FIXME: It would be better to produce the diagnostic for casting
10793     //        a pointer to an integer.
10794     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10795     return false;
10796   }
10797   Result = Val.getInt();
10798   return true;
10799 }
10800 
VisitSourceLocExpr(const SourceLocExpr * E)10801 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10802   APValue Evaluated = E->EvaluateInContext(
10803       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10804   return Success(Evaluated, E);
10805 }
10806 
EvaluateFixedPoint(const Expr * E,APFixedPoint & Result,EvalInfo & Info)10807 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10808                                EvalInfo &Info) {
10809   assert(!E->isValueDependent());
10810   if (E->getType()->isFixedPointType()) {
10811     APValue Val;
10812     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10813       return false;
10814     if (!Val.isFixedPoint())
10815       return false;
10816 
10817     Result = Val.getFixedPoint();
10818     return true;
10819   }
10820   return false;
10821 }
10822 
EvaluateFixedPointOrInteger(const Expr * E,APFixedPoint & Result,EvalInfo & Info)10823 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10824                                         EvalInfo &Info) {
10825   assert(!E->isValueDependent());
10826   if (E->getType()->isIntegerType()) {
10827     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10828     APSInt Val;
10829     if (!EvaluateInteger(E, Val, Info))
10830       return false;
10831     Result = APFixedPoint(Val, FXSema);
10832     return true;
10833   } else if (E->getType()->isFixedPointType()) {
10834     return EvaluateFixedPoint(E, Result, Info);
10835   }
10836   return false;
10837 }
10838 
10839 /// Check whether the given declaration can be directly converted to an integral
10840 /// rvalue. If not, no diagnostic is produced; there are other things we can
10841 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)10842 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10843   // Enums are integer constant exprs.
10844   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10845     // Check for signedness/width mismatches between E type and ECD value.
10846     bool SameSign = (ECD->getInitVal().isSigned()
10847                      == E->getType()->isSignedIntegerOrEnumerationType());
10848     bool SameWidth = (ECD->getInitVal().getBitWidth()
10849                       == Info.Ctx.getIntWidth(E->getType()));
10850     if (SameSign && SameWidth)
10851       return Success(ECD->getInitVal(), E);
10852     else {
10853       // Get rid of mismatch (otherwise Success assertions will fail)
10854       // by computing a new value matching the type of E.
10855       llvm::APSInt Val = ECD->getInitVal();
10856       if (!SameSign)
10857         Val.setIsSigned(!ECD->getInitVal().isSigned());
10858       if (!SameWidth)
10859         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10860       return Success(Val, E);
10861     }
10862   }
10863   return false;
10864 }
10865 
10866 /// Values returned by __builtin_classify_type, chosen to match the values
10867 /// produced by GCC's builtin.
10868 enum class GCCTypeClass {
10869   None = -1,
10870   Void = 0,
10871   Integer = 1,
10872   // GCC reserves 2 for character types, but instead classifies them as
10873   // integers.
10874   Enum = 3,
10875   Bool = 4,
10876   Pointer = 5,
10877   // GCC reserves 6 for references, but appears to never use it (because
10878   // expressions never have reference type, presumably).
10879   PointerToDataMember = 7,
10880   RealFloat = 8,
10881   Complex = 9,
10882   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10883   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10884   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10885   // uses 12 for that purpose, same as for a class or struct. Maybe it
10886   // internally implements a pointer to member as a struct?  Who knows.
10887   PointerToMemberFunction = 12, // Not a bug, see above.
10888   ClassOrStruct = 12,
10889   Union = 13,
10890   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10891   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10892   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10893   // literals.
10894 };
10895 
10896 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10897 /// as GCC.
10898 static GCCTypeClass
EvaluateBuiltinClassifyType(QualType T,const LangOptions & LangOpts)10899 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10900   assert(!T->isDependentType() && "unexpected dependent type");
10901 
10902   QualType CanTy = T.getCanonicalType();
10903   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10904 
10905   switch (CanTy->getTypeClass()) {
10906 #define TYPE(ID, BASE)
10907 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10908 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10909 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10910 #include "clang/AST/TypeNodes.inc"
10911   case Type::Auto:
10912   case Type::DeducedTemplateSpecialization:
10913       llvm_unreachable("unexpected non-canonical or dependent type");
10914 
10915   case Type::Builtin:
10916     switch (BT->getKind()) {
10917 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10918 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10919     case BuiltinType::ID: return GCCTypeClass::Integer;
10920 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10921     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10922 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10923     case BuiltinType::ID: break;
10924 #include "clang/AST/BuiltinTypes.def"
10925     case BuiltinType::Void:
10926       return GCCTypeClass::Void;
10927 
10928     case BuiltinType::Bool:
10929       return GCCTypeClass::Bool;
10930 
10931     case BuiltinType::Char_U:
10932     case BuiltinType::UChar:
10933     case BuiltinType::WChar_U:
10934     case BuiltinType::Char8:
10935     case BuiltinType::Char16:
10936     case BuiltinType::Char32:
10937     case BuiltinType::UShort:
10938     case BuiltinType::UInt:
10939     case BuiltinType::ULong:
10940     case BuiltinType::ULongLong:
10941     case BuiltinType::UInt128:
10942       return GCCTypeClass::Integer;
10943 
10944     case BuiltinType::UShortAccum:
10945     case BuiltinType::UAccum:
10946     case BuiltinType::ULongAccum:
10947     case BuiltinType::UShortFract:
10948     case BuiltinType::UFract:
10949     case BuiltinType::ULongFract:
10950     case BuiltinType::SatUShortAccum:
10951     case BuiltinType::SatUAccum:
10952     case BuiltinType::SatULongAccum:
10953     case BuiltinType::SatUShortFract:
10954     case BuiltinType::SatUFract:
10955     case BuiltinType::SatULongFract:
10956       return GCCTypeClass::None;
10957 
10958     case BuiltinType::NullPtr:
10959 
10960     case BuiltinType::ObjCId:
10961     case BuiltinType::ObjCClass:
10962     case BuiltinType::ObjCSel:
10963 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10964     case BuiltinType::Id:
10965 #include "clang/Basic/OpenCLImageTypes.def"
10966 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10967     case BuiltinType::Id:
10968 #include "clang/Basic/OpenCLExtensionTypes.def"
10969     case BuiltinType::OCLSampler:
10970     case BuiltinType::OCLEvent:
10971     case BuiltinType::OCLClkEvent:
10972     case BuiltinType::OCLQueue:
10973     case BuiltinType::OCLReserveID:
10974 #define SVE_TYPE(Name, Id, SingletonId) \
10975     case BuiltinType::Id:
10976 #include "clang/Basic/AArch64SVEACLETypes.def"
10977 #define PPC_VECTOR_TYPE(Name, Id, Size) \
10978     case BuiltinType::Id:
10979 #include "clang/Basic/PPCTypes.def"
10980       return GCCTypeClass::None;
10981 
10982     case BuiltinType::Dependent:
10983       llvm_unreachable("unexpected dependent type");
10984     };
10985     llvm_unreachable("unexpected placeholder type");
10986 
10987   case Type::Enum:
10988     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10989 
10990   case Type::Pointer:
10991   case Type::ConstantArray:
10992   case Type::VariableArray:
10993   case Type::IncompleteArray:
10994   case Type::FunctionNoProto:
10995   case Type::FunctionProto:
10996     return GCCTypeClass::Pointer;
10997 
10998   case Type::MemberPointer:
10999     return CanTy->isMemberDataPointerType()
11000                ? GCCTypeClass::PointerToDataMember
11001                : GCCTypeClass::PointerToMemberFunction;
11002 
11003   case Type::Complex:
11004     return GCCTypeClass::Complex;
11005 
11006   case Type::Record:
11007     return CanTy->isUnionType() ? GCCTypeClass::Union
11008                                 : GCCTypeClass::ClassOrStruct;
11009 
11010   case Type::Atomic:
11011     // GCC classifies _Atomic T the same as T.
11012     return EvaluateBuiltinClassifyType(
11013         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11014 
11015   case Type::BlockPointer:
11016   case Type::Vector:
11017   case Type::ExtVector:
11018   case Type::ConstantMatrix:
11019   case Type::ObjCObject:
11020   case Type::ObjCInterface:
11021   case Type::ObjCObjectPointer:
11022   case Type::Pipe:
11023   case Type::ExtInt:
11024     // GCC classifies vectors as None. We follow its lead and classify all
11025     // other types that don't fit into the regular classification the same way.
11026     return GCCTypeClass::None;
11027 
11028   case Type::LValueReference:
11029   case Type::RValueReference:
11030     llvm_unreachable("invalid type for expression");
11031   }
11032 
11033   llvm_unreachable("unexpected type class");
11034 }
11035 
11036 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11037 /// as GCC.
11038 static GCCTypeClass
EvaluateBuiltinClassifyType(const CallExpr * E,const LangOptions & LangOpts)11039 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11040   // If no argument was supplied, default to None. This isn't
11041   // ideal, however it is what gcc does.
11042   if (E->getNumArgs() == 0)
11043     return GCCTypeClass::None;
11044 
11045   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11046   // being an ICE, but still folds it to a constant using the type of the first
11047   // argument.
11048   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11049 }
11050 
11051 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11052 /// __builtin_constant_p when applied to the given pointer.
11053 ///
11054 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11055 /// or it points to the first character of a string literal.
EvaluateBuiltinConstantPForLValue(const APValue & LV)11056 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11057   APValue::LValueBase Base = LV.getLValueBase();
11058   if (Base.isNull()) {
11059     // A null base is acceptable.
11060     return true;
11061   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11062     if (!isa<StringLiteral>(E))
11063       return false;
11064     return LV.getLValueOffset().isZero();
11065   } else if (Base.is<TypeInfoLValue>()) {
11066     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11067     // evaluate to true.
11068     return true;
11069   } else {
11070     // Any other base is not constant enough for GCC.
11071     return false;
11072   }
11073 }
11074 
11075 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11076 /// GCC as we can manage.
EvaluateBuiltinConstantP(EvalInfo & Info,const Expr * Arg)11077 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11078   // This evaluation is not permitted to have side-effects, so evaluate it in
11079   // a speculative evaluation context.
11080   SpeculativeEvaluationRAII SpeculativeEval(Info);
11081 
11082   // Constant-folding is always enabled for the operand of __builtin_constant_p
11083   // (even when the enclosing evaluation context otherwise requires a strict
11084   // language-specific constant expression).
11085   FoldConstant Fold(Info, true);
11086 
11087   QualType ArgType = Arg->getType();
11088 
11089   // __builtin_constant_p always has one operand. The rules which gcc follows
11090   // are not precisely documented, but are as follows:
11091   //
11092   //  - If the operand is of integral, floating, complex or enumeration type,
11093   //    and can be folded to a known value of that type, it returns 1.
11094   //  - If the operand can be folded to a pointer to the first character
11095   //    of a string literal (or such a pointer cast to an integral type)
11096   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11097   //
11098   // Otherwise, it returns 0.
11099   //
11100   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11101   // its support for this did not work prior to GCC 9 and is not yet well
11102   // understood.
11103   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11104       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11105       ArgType->isNullPtrType()) {
11106     APValue V;
11107     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11108       Fold.keepDiagnostics();
11109       return false;
11110     }
11111 
11112     // For a pointer (possibly cast to integer), there are special rules.
11113     if (V.getKind() == APValue::LValue)
11114       return EvaluateBuiltinConstantPForLValue(V);
11115 
11116     // Otherwise, any constant value is good enough.
11117     return V.hasValue();
11118   }
11119 
11120   // Anything else isn't considered to be sufficiently constant.
11121   return false;
11122 }
11123 
11124 /// Retrieves the "underlying object type" of the given expression,
11125 /// as used by __builtin_object_size.
getObjectType(APValue::LValueBase B)11126 static QualType getObjectType(APValue::LValueBase B) {
11127   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11128     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11129       return VD->getType();
11130   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11131     if (isa<CompoundLiteralExpr>(E))
11132       return E->getType();
11133   } else if (B.is<TypeInfoLValue>()) {
11134     return B.getTypeInfoType();
11135   } else if (B.is<DynamicAllocLValue>()) {
11136     return B.getDynamicAllocType();
11137   }
11138 
11139   return QualType();
11140 }
11141 
11142 /// A more selective version of E->IgnoreParenCasts for
11143 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11144 /// to change the type of E.
11145 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11146 ///
11147 /// Always returns an RValue with a pointer representation.
ignorePointerCastsAndParens(const Expr * E)11148 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11149   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
11150 
11151   auto *NoParens = E->IgnoreParens();
11152   auto *Cast = dyn_cast<CastExpr>(NoParens);
11153   if (Cast == nullptr)
11154     return NoParens;
11155 
11156   // We only conservatively allow a few kinds of casts, because this code is
11157   // inherently a simple solution that seeks to support the common case.
11158   auto CastKind = Cast->getCastKind();
11159   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11160       CastKind != CK_AddressSpaceConversion)
11161     return NoParens;
11162 
11163   auto *SubExpr = Cast->getSubExpr();
11164   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
11165     return NoParens;
11166   return ignorePointerCastsAndParens(SubExpr);
11167 }
11168 
11169 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11170 /// record layout. e.g.
11171 ///   struct { struct { int a, b; } fst, snd; } obj;
11172 ///   obj.fst   // no
11173 ///   obj.snd   // yes
11174 ///   obj.fst.a // no
11175 ///   obj.fst.b // no
11176 ///   obj.snd.a // no
11177 ///   obj.snd.b // yes
11178 ///
11179 /// Please note: this function is specialized for how __builtin_object_size
11180 /// views "objects".
11181 ///
11182 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11183 /// correct result, it will always return true.
isDesignatorAtObjectEnd(const ASTContext & Ctx,const LValue & LVal)11184 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11185   assert(!LVal.Designator.Invalid);
11186 
11187   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11188     const RecordDecl *Parent = FD->getParent();
11189     Invalid = Parent->isInvalidDecl();
11190     if (Invalid || Parent->isUnion())
11191       return true;
11192     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11193     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11194   };
11195 
11196   auto &Base = LVal.getLValueBase();
11197   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11198     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11199       bool Invalid;
11200       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11201         return Invalid;
11202     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11203       for (auto *FD : IFD->chain()) {
11204         bool Invalid;
11205         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11206           return Invalid;
11207       }
11208     }
11209   }
11210 
11211   unsigned I = 0;
11212   QualType BaseType = getType(Base);
11213   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11214     // If we don't know the array bound, conservatively assume we're looking at
11215     // the final array element.
11216     ++I;
11217     if (BaseType->isIncompleteArrayType())
11218       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11219     else
11220       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11221   }
11222 
11223   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11224     const auto &Entry = LVal.Designator.Entries[I];
11225     if (BaseType->isArrayType()) {
11226       // Because __builtin_object_size treats arrays as objects, we can ignore
11227       // the index iff this is the last array in the Designator.
11228       if (I + 1 == E)
11229         return true;
11230       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11231       uint64_t Index = Entry.getAsArrayIndex();
11232       if (Index + 1 != CAT->getSize())
11233         return false;
11234       BaseType = CAT->getElementType();
11235     } else if (BaseType->isAnyComplexType()) {
11236       const auto *CT = BaseType->castAs<ComplexType>();
11237       uint64_t Index = Entry.getAsArrayIndex();
11238       if (Index != 1)
11239         return false;
11240       BaseType = CT->getElementType();
11241     } else if (auto *FD = getAsField(Entry)) {
11242       bool Invalid;
11243       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11244         return Invalid;
11245       BaseType = FD->getType();
11246     } else {
11247       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11248       return false;
11249     }
11250   }
11251   return true;
11252 }
11253 
11254 /// Tests to see if the LValue has a user-specified designator (that isn't
11255 /// necessarily valid). Note that this always returns 'true' if the LValue has
11256 /// an unsized array as its first designator entry, because there's currently no
11257 /// way to tell if the user typed *foo or foo[0].
refersToCompleteObject(const LValue & LVal)11258 static bool refersToCompleteObject(const LValue &LVal) {
11259   if (LVal.Designator.Invalid)
11260     return false;
11261 
11262   if (!LVal.Designator.Entries.empty())
11263     return LVal.Designator.isMostDerivedAnUnsizedArray();
11264 
11265   if (!LVal.InvalidBase)
11266     return true;
11267 
11268   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11269   // the LValueBase.
11270   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11271   return !E || !isa<MemberExpr>(E);
11272 }
11273 
11274 /// Attempts to detect a user writing into a piece of memory that's impossible
11275 /// to figure out the size of by just using types.
isUserWritingOffTheEnd(const ASTContext & Ctx,const LValue & LVal)11276 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11277   const SubobjectDesignator &Designator = LVal.Designator;
11278   // Notes:
11279   // - Users can only write off of the end when we have an invalid base. Invalid
11280   //   bases imply we don't know where the memory came from.
11281   // - We used to be a bit more aggressive here; we'd only be conservative if
11282   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11283   //   broke some common standard library extensions (PR30346), but was
11284   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11285   //   with some sort of list. OTOH, it seems that GCC is always
11286   //   conservative with the last element in structs (if it's an array), so our
11287   //   current behavior is more compatible than an explicit list approach would
11288   //   be.
11289   return LVal.InvalidBase &&
11290          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11291          Designator.MostDerivedIsArrayElement &&
11292          isDesignatorAtObjectEnd(Ctx, LVal);
11293 }
11294 
11295 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11296 /// Fails if the conversion would cause loss of precision.
convertUnsignedAPIntToCharUnits(const llvm::APInt & Int,CharUnits & Result)11297 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11298                                             CharUnits &Result) {
11299   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11300   if (Int.ugt(CharUnitsMax))
11301     return false;
11302   Result = CharUnits::fromQuantity(Int.getZExtValue());
11303   return true;
11304 }
11305 
11306 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11307 /// determine how many bytes exist from the beginning of the object to either
11308 /// the end of the current subobject, or the end of the object itself, depending
11309 /// on what the LValue looks like + the value of Type.
11310 ///
11311 /// If this returns false, the value of Result is undefined.
determineEndOffset(EvalInfo & Info,SourceLocation ExprLoc,unsigned Type,const LValue & LVal,CharUnits & EndOffset)11312 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11313                                unsigned Type, const LValue &LVal,
11314                                CharUnits &EndOffset) {
11315   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11316 
11317   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11318     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11319       return false;
11320     return HandleSizeof(Info, ExprLoc, Ty, Result);
11321   };
11322 
11323   // We want to evaluate the size of the entire object. This is a valid fallback
11324   // for when Type=1 and the designator is invalid, because we're asked for an
11325   // upper-bound.
11326   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11327     // Type=3 wants a lower bound, so we can't fall back to this.
11328     if (Type == 3 && !DetermineForCompleteObject)
11329       return false;
11330 
11331     llvm::APInt APEndOffset;
11332     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11333         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11334       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11335 
11336     if (LVal.InvalidBase)
11337       return false;
11338 
11339     QualType BaseTy = getObjectType(LVal.getLValueBase());
11340     return CheckedHandleSizeof(BaseTy, EndOffset);
11341   }
11342 
11343   // We want to evaluate the size of a subobject.
11344   const SubobjectDesignator &Designator = LVal.Designator;
11345 
11346   // The following is a moderately common idiom in C:
11347   //
11348   // struct Foo { int a; char c[1]; };
11349   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11350   // strcpy(&F->c[0], Bar);
11351   //
11352   // In order to not break too much legacy code, we need to support it.
11353   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11354     // If we can resolve this to an alloc_size call, we can hand that back,
11355     // because we know for certain how many bytes there are to write to.
11356     llvm::APInt APEndOffset;
11357     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11358         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11359       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11360 
11361     // If we cannot determine the size of the initial allocation, then we can't
11362     // given an accurate upper-bound. However, we are still able to give
11363     // conservative lower-bounds for Type=3.
11364     if (Type == 1)
11365       return false;
11366   }
11367 
11368   CharUnits BytesPerElem;
11369   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11370     return false;
11371 
11372   // According to the GCC documentation, we want the size of the subobject
11373   // denoted by the pointer. But that's not quite right -- what we actually
11374   // want is the size of the immediately-enclosing array, if there is one.
11375   int64_t ElemsRemaining;
11376   if (Designator.MostDerivedIsArrayElement &&
11377       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11378     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11379     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11380     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11381   } else {
11382     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11383   }
11384 
11385   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11386   return true;
11387 }
11388 
11389 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11390 /// returns true and stores the result in @p Size.
11391 ///
11392 /// If @p WasError is non-null, this will report whether the failure to evaluate
11393 /// is to be treated as an Error in IntExprEvaluator.
tryEvaluateBuiltinObjectSize(const Expr * E,unsigned Type,EvalInfo & Info,uint64_t & Size)11394 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11395                                          EvalInfo &Info, uint64_t &Size) {
11396   // Determine the denoted object.
11397   LValue LVal;
11398   {
11399     // The operand of __builtin_object_size is never evaluated for side-effects.
11400     // If there are any, but we can determine the pointed-to object anyway, then
11401     // ignore the side-effects.
11402     SpeculativeEvaluationRAII SpeculativeEval(Info);
11403     IgnoreSideEffectsRAII Fold(Info);
11404 
11405     if (E->isGLValue()) {
11406       // It's possible for us to be given GLValues if we're called via
11407       // Expr::tryEvaluateObjectSize.
11408       APValue RVal;
11409       if (!EvaluateAsRValue(Info, E, RVal))
11410         return false;
11411       LVal.setFrom(Info.Ctx, RVal);
11412     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11413                                 /*InvalidBaseOK=*/true))
11414       return false;
11415   }
11416 
11417   // If we point to before the start of the object, there are no accessible
11418   // bytes.
11419   if (LVal.getLValueOffset().isNegative()) {
11420     Size = 0;
11421     return true;
11422   }
11423 
11424   CharUnits EndOffset;
11425   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11426     return false;
11427 
11428   // If we've fallen outside of the end offset, just pretend there's nothing to
11429   // write to/read from.
11430   if (EndOffset <= LVal.getLValueOffset())
11431     Size = 0;
11432   else
11433     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11434   return true;
11435 }
11436 
VisitCallExpr(const CallExpr * E)11437 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11438   if (unsigned BuiltinOp = E->getBuiltinCallee())
11439     return VisitBuiltinCallExpr(E, BuiltinOp);
11440 
11441   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11442 }
11443 
getBuiltinAlignArguments(const CallExpr * E,EvalInfo & Info,APValue & Val,APSInt & Alignment)11444 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11445                                      APValue &Val, APSInt &Alignment) {
11446   QualType SrcTy = E->getArg(0)->getType();
11447   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11448     return false;
11449   // Even though we are evaluating integer expressions we could get a pointer
11450   // argument for the __builtin_is_aligned() case.
11451   if (SrcTy->isPointerType()) {
11452     LValue Ptr;
11453     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11454       return false;
11455     Ptr.moveInto(Val);
11456   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11457     Info.FFDiag(E->getArg(0));
11458     return false;
11459   } else {
11460     APSInt SrcInt;
11461     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11462       return false;
11463     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11464            "Bit widths must be the same");
11465     Val = APValue(SrcInt);
11466   }
11467   assert(Val.hasValue());
11468   return true;
11469 }
11470 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)11471 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11472                                             unsigned BuiltinOp) {
11473   switch (BuiltinOp) {
11474   default:
11475     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11476 
11477   case Builtin::BI__builtin_dynamic_object_size:
11478   case Builtin::BI__builtin_object_size: {
11479     // The type was checked when we built the expression.
11480     unsigned Type =
11481         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11482     assert(Type <= 3 && "unexpected type");
11483 
11484     uint64_t Size;
11485     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11486       return Success(Size, E);
11487 
11488     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11489       return Success((Type & 2) ? 0 : -1, E);
11490 
11491     // Expression had no side effects, but we couldn't statically determine the
11492     // size of the referenced object.
11493     switch (Info.EvalMode) {
11494     case EvalInfo::EM_ConstantExpression:
11495     case EvalInfo::EM_ConstantFold:
11496     case EvalInfo::EM_IgnoreSideEffects:
11497       // Leave it to IR generation.
11498       return Error(E);
11499     case EvalInfo::EM_ConstantExpressionUnevaluated:
11500       // Reduce it to a constant now.
11501       return Success((Type & 2) ? 0 : -1, E);
11502     }
11503 
11504     llvm_unreachable("unexpected EvalMode");
11505   }
11506 
11507   case Builtin::BI__builtin_os_log_format_buffer_size: {
11508     analyze_os_log::OSLogBufferLayout Layout;
11509     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11510     return Success(Layout.size().getQuantity(), E);
11511   }
11512 
11513   case Builtin::BI__builtin_is_aligned: {
11514     APValue Src;
11515     APSInt Alignment;
11516     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11517       return false;
11518     if (Src.isLValue()) {
11519       // If we evaluated a pointer, check the minimum known alignment.
11520       LValue Ptr;
11521       Ptr.setFrom(Info.Ctx, Src);
11522       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11523       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11524       // We can return true if the known alignment at the computed offset is
11525       // greater than the requested alignment.
11526       assert(PtrAlign.isPowerOfTwo());
11527       assert(Alignment.isPowerOf2());
11528       if (PtrAlign.getQuantity() >= Alignment)
11529         return Success(1, E);
11530       // If the alignment is not known to be sufficient, some cases could still
11531       // be aligned at run time. However, if the requested alignment is less or
11532       // equal to the base alignment and the offset is not aligned, we know that
11533       // the run-time value can never be aligned.
11534       if (BaseAlignment.getQuantity() >= Alignment &&
11535           PtrAlign.getQuantity() < Alignment)
11536         return Success(0, E);
11537       // Otherwise we can't infer whether the value is sufficiently aligned.
11538       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11539       //  in cases where we can't fully evaluate the pointer.
11540       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11541           << Alignment;
11542       return false;
11543     }
11544     assert(Src.isInt());
11545     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11546   }
11547   case Builtin::BI__builtin_align_up: {
11548     APValue Src;
11549     APSInt Alignment;
11550     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11551       return false;
11552     if (!Src.isInt())
11553       return Error(E);
11554     APSInt AlignedVal =
11555         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11556                Src.getInt().isUnsigned());
11557     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11558     return Success(AlignedVal, E);
11559   }
11560   case Builtin::BI__builtin_align_down: {
11561     APValue Src;
11562     APSInt Alignment;
11563     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11564       return false;
11565     if (!Src.isInt())
11566       return Error(E);
11567     APSInt AlignedVal =
11568         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11569     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11570     return Success(AlignedVal, E);
11571   }
11572 
11573   case Builtin::BI__builtin_bitreverse8:
11574   case Builtin::BI__builtin_bitreverse16:
11575   case Builtin::BI__builtin_bitreverse32:
11576   case Builtin::BI__builtin_bitreverse64: {
11577     APSInt Val;
11578     if (!EvaluateInteger(E->getArg(0), Val, Info))
11579       return false;
11580 
11581     return Success(Val.reverseBits(), E);
11582   }
11583 
11584   case Builtin::BI__builtin_bswap16:
11585   case Builtin::BI__builtin_bswap32:
11586   case Builtin::BI__builtin_bswap64: {
11587     APSInt Val;
11588     if (!EvaluateInteger(E->getArg(0), Val, Info))
11589       return false;
11590 
11591     return Success(Val.byteSwap(), E);
11592   }
11593 
11594   case Builtin::BI__builtin_classify_type:
11595     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11596 
11597   case Builtin::BI__builtin_clrsb:
11598   case Builtin::BI__builtin_clrsbl:
11599   case Builtin::BI__builtin_clrsbll: {
11600     APSInt Val;
11601     if (!EvaluateInteger(E->getArg(0), Val, Info))
11602       return false;
11603 
11604     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11605   }
11606 
11607   case Builtin::BI__builtin_clz:
11608   case Builtin::BI__builtin_clzl:
11609   case Builtin::BI__builtin_clzll:
11610   case Builtin::BI__builtin_clzs: {
11611     APSInt Val;
11612     if (!EvaluateInteger(E->getArg(0), Val, Info))
11613       return false;
11614     if (!Val)
11615       return Error(E);
11616 
11617     return Success(Val.countLeadingZeros(), E);
11618   }
11619 
11620   case Builtin::BI__builtin_constant_p: {
11621     const Expr *Arg = E->getArg(0);
11622     if (EvaluateBuiltinConstantP(Info, Arg))
11623       return Success(true, E);
11624     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11625       // Outside a constant context, eagerly evaluate to false in the presence
11626       // of side-effects in order to avoid -Wunsequenced false-positives in
11627       // a branch on __builtin_constant_p(expr).
11628       return Success(false, E);
11629     }
11630     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11631     return false;
11632   }
11633 
11634   case Builtin::BI__builtin_is_constant_evaluated: {
11635     const auto *Callee = Info.CurrentCall->getCallee();
11636     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11637         (Info.CallStackDepth == 1 ||
11638          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11639           Callee->getIdentifier() &&
11640           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11641       // FIXME: Find a better way to avoid duplicated diagnostics.
11642       if (Info.EvalStatus.Diag)
11643         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11644                                                : Info.CurrentCall->CallLoc,
11645                     diag::warn_is_constant_evaluated_always_true_constexpr)
11646             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11647                                          : "std::is_constant_evaluated");
11648     }
11649 
11650     return Success(Info.InConstantContext, E);
11651   }
11652 
11653   case Builtin::BI__builtin_ctz:
11654   case Builtin::BI__builtin_ctzl:
11655   case Builtin::BI__builtin_ctzll:
11656   case Builtin::BI__builtin_ctzs: {
11657     APSInt Val;
11658     if (!EvaluateInteger(E->getArg(0), Val, Info))
11659       return false;
11660     if (!Val)
11661       return Error(E);
11662 
11663     return Success(Val.countTrailingZeros(), E);
11664   }
11665 
11666   case Builtin::BI__builtin_eh_return_data_regno: {
11667     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11668     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11669     return Success(Operand, E);
11670   }
11671 
11672   case Builtin::BI__builtin_expect:
11673   case Builtin::BI__builtin_expect_with_probability:
11674     return Visit(E->getArg(0));
11675 
11676   case Builtin::BI__builtin_ffs:
11677   case Builtin::BI__builtin_ffsl:
11678   case Builtin::BI__builtin_ffsll: {
11679     APSInt Val;
11680     if (!EvaluateInteger(E->getArg(0), Val, Info))
11681       return false;
11682 
11683     unsigned N = Val.countTrailingZeros();
11684     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11685   }
11686 
11687   case Builtin::BI__builtin_fpclassify: {
11688     APFloat Val(0.0);
11689     if (!EvaluateFloat(E->getArg(5), Val, Info))
11690       return false;
11691     unsigned Arg;
11692     switch (Val.getCategory()) {
11693     case APFloat::fcNaN: Arg = 0; break;
11694     case APFloat::fcInfinity: Arg = 1; break;
11695     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11696     case APFloat::fcZero: Arg = 4; break;
11697     }
11698     return Visit(E->getArg(Arg));
11699   }
11700 
11701   case Builtin::BI__builtin_isinf_sign: {
11702     APFloat Val(0.0);
11703     return EvaluateFloat(E->getArg(0), Val, Info) &&
11704            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11705   }
11706 
11707   case Builtin::BI__builtin_isinf: {
11708     APFloat Val(0.0);
11709     return EvaluateFloat(E->getArg(0), Val, Info) &&
11710            Success(Val.isInfinity() ? 1 : 0, E);
11711   }
11712 
11713   case Builtin::BI__builtin_isfinite: {
11714     APFloat Val(0.0);
11715     return EvaluateFloat(E->getArg(0), Val, Info) &&
11716            Success(Val.isFinite() ? 1 : 0, E);
11717   }
11718 
11719   case Builtin::BI__builtin_isnan: {
11720     APFloat Val(0.0);
11721     return EvaluateFloat(E->getArg(0), Val, Info) &&
11722            Success(Val.isNaN() ? 1 : 0, E);
11723   }
11724 
11725   case Builtin::BI__builtin_isnormal: {
11726     APFloat Val(0.0);
11727     return EvaluateFloat(E->getArg(0), Val, Info) &&
11728            Success(Val.isNormal() ? 1 : 0, E);
11729   }
11730 
11731   case Builtin::BI__builtin_parity:
11732   case Builtin::BI__builtin_parityl:
11733   case Builtin::BI__builtin_parityll: {
11734     APSInt Val;
11735     if (!EvaluateInteger(E->getArg(0), Val, Info))
11736       return false;
11737 
11738     return Success(Val.countPopulation() % 2, E);
11739   }
11740 
11741   case Builtin::BI__builtin_popcount:
11742   case Builtin::BI__builtin_popcountl:
11743   case Builtin::BI__builtin_popcountll: {
11744     APSInt Val;
11745     if (!EvaluateInteger(E->getArg(0), Val, Info))
11746       return false;
11747 
11748     return Success(Val.countPopulation(), E);
11749   }
11750 
11751   case Builtin::BI__builtin_rotateleft8:
11752   case Builtin::BI__builtin_rotateleft16:
11753   case Builtin::BI__builtin_rotateleft32:
11754   case Builtin::BI__builtin_rotateleft64:
11755   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11756   case Builtin::BI_rotl16:
11757   case Builtin::BI_rotl:
11758   case Builtin::BI_lrotl:
11759   case Builtin::BI_rotl64: {
11760     APSInt Val, Amt;
11761     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11762         !EvaluateInteger(E->getArg(1), Amt, Info))
11763       return false;
11764 
11765     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11766   }
11767 
11768   case Builtin::BI__builtin_rotateright8:
11769   case Builtin::BI__builtin_rotateright16:
11770   case Builtin::BI__builtin_rotateright32:
11771   case Builtin::BI__builtin_rotateright64:
11772   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11773   case Builtin::BI_rotr16:
11774   case Builtin::BI_rotr:
11775   case Builtin::BI_lrotr:
11776   case Builtin::BI_rotr64: {
11777     APSInt Val, Amt;
11778     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11779         !EvaluateInteger(E->getArg(1), Amt, Info))
11780       return false;
11781 
11782     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11783   }
11784 
11785   case Builtin::BIstrlen:
11786   case Builtin::BIwcslen:
11787     // A call to strlen is not a constant expression.
11788     if (Info.getLangOpts().CPlusPlus11)
11789       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11790         << /*isConstexpr*/0 << /*isConstructor*/0
11791         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11792     else
11793       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11794     LLVM_FALLTHROUGH;
11795   case Builtin::BI__builtin_strlen:
11796   case Builtin::BI__builtin_wcslen: {
11797     // As an extension, we support __builtin_strlen() as a constant expression,
11798     // and support folding strlen() to a constant.
11799     LValue String;
11800     if (!EvaluatePointer(E->getArg(0), String, Info))
11801       return false;
11802 
11803     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11804 
11805     // Fast path: if it's a string literal, search the string value.
11806     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11807             String.getLValueBase().dyn_cast<const Expr *>())) {
11808       // The string literal may have embedded null characters. Find the first
11809       // one and truncate there.
11810       StringRef Str = S->getBytes();
11811       int64_t Off = String.Offset.getQuantity();
11812       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11813           S->getCharByteWidth() == 1 &&
11814           // FIXME: Add fast-path for wchar_t too.
11815           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11816         Str = Str.substr(Off);
11817 
11818         StringRef::size_type Pos = Str.find(0);
11819         if (Pos != StringRef::npos)
11820           Str = Str.substr(0, Pos);
11821 
11822         return Success(Str.size(), E);
11823       }
11824 
11825       // Fall through to slow path to issue appropriate diagnostic.
11826     }
11827 
11828     // Slow path: scan the bytes of the string looking for the terminating 0.
11829     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11830       APValue Char;
11831       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11832           !Char.isInt())
11833         return false;
11834       if (!Char.getInt())
11835         return Success(Strlen, E);
11836       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11837         return false;
11838     }
11839   }
11840 
11841   case Builtin::BIstrcmp:
11842   case Builtin::BIwcscmp:
11843   case Builtin::BIstrncmp:
11844   case Builtin::BIwcsncmp:
11845   case Builtin::BImemcmp:
11846   case Builtin::BIbcmp:
11847   case Builtin::BIwmemcmp:
11848     // A call to strlen is not a constant expression.
11849     if (Info.getLangOpts().CPlusPlus11)
11850       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11851         << /*isConstexpr*/0 << /*isConstructor*/0
11852         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11853     else
11854       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11855     LLVM_FALLTHROUGH;
11856   case Builtin::BI__builtin_strcmp:
11857   case Builtin::BI__builtin_wcscmp:
11858   case Builtin::BI__builtin_strncmp:
11859   case Builtin::BI__builtin_wcsncmp:
11860   case Builtin::BI__builtin_memcmp:
11861   case Builtin::BI__builtin_bcmp:
11862   case Builtin::BI__builtin_wmemcmp: {
11863     LValue String1, String2;
11864     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11865         !EvaluatePointer(E->getArg(1), String2, Info))
11866       return false;
11867 
11868     uint64_t MaxLength = uint64_t(-1);
11869     if (BuiltinOp != Builtin::BIstrcmp &&
11870         BuiltinOp != Builtin::BIwcscmp &&
11871         BuiltinOp != Builtin::BI__builtin_strcmp &&
11872         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11873       APSInt N;
11874       if (!EvaluateInteger(E->getArg(2), N, Info))
11875         return false;
11876       MaxLength = N.getExtValue();
11877     }
11878 
11879     // Empty substrings compare equal by definition.
11880     if (MaxLength == 0u)
11881       return Success(0, E);
11882 
11883     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11884         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11885         String1.Designator.Invalid || String2.Designator.Invalid)
11886       return false;
11887 
11888     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11889     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11890 
11891     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11892                      BuiltinOp == Builtin::BIbcmp ||
11893                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11894                      BuiltinOp == Builtin::BI__builtin_bcmp;
11895 
11896     assert(IsRawByte ||
11897            (Info.Ctx.hasSameUnqualifiedType(
11898                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11899             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11900 
11901     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11902     // 'char8_t', but no other types.
11903     if (IsRawByte &&
11904         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11905       // FIXME: Consider using our bit_cast implementation to support this.
11906       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11907           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11908           << CharTy1 << CharTy2;
11909       return false;
11910     }
11911 
11912     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11913       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11914              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11915              Char1.isInt() && Char2.isInt();
11916     };
11917     const auto &AdvanceElems = [&] {
11918       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11919              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11920     };
11921 
11922     bool StopAtNull =
11923         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11924          BuiltinOp != Builtin::BIwmemcmp &&
11925          BuiltinOp != Builtin::BI__builtin_memcmp &&
11926          BuiltinOp != Builtin::BI__builtin_bcmp &&
11927          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11928     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11929                   BuiltinOp == Builtin::BIwcsncmp ||
11930                   BuiltinOp == Builtin::BIwmemcmp ||
11931                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11932                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11933                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11934 
11935     for (; MaxLength; --MaxLength) {
11936       APValue Char1, Char2;
11937       if (!ReadCurElems(Char1, Char2))
11938         return false;
11939       if (Char1.getInt().ne(Char2.getInt())) {
11940         if (IsWide) // wmemcmp compares with wchar_t signedness.
11941           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11942         // memcmp always compares unsigned chars.
11943         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11944       }
11945       if (StopAtNull && !Char1.getInt())
11946         return Success(0, E);
11947       assert(!(StopAtNull && !Char2.getInt()));
11948       if (!AdvanceElems())
11949         return false;
11950     }
11951     // We hit the strncmp / memcmp limit.
11952     return Success(0, E);
11953   }
11954 
11955   case Builtin::BI__atomic_always_lock_free:
11956   case Builtin::BI__atomic_is_lock_free:
11957   case Builtin::BI__c11_atomic_is_lock_free: {
11958     APSInt SizeVal;
11959     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11960       return false;
11961 
11962     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11963     // of two less than or equal to the maximum inline atomic width, we know it
11964     // is lock-free.  If the size isn't a power of two, or greater than the
11965     // maximum alignment where we promote atomics, we know it is not lock-free
11966     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11967     // the answer can only be determined at runtime; for example, 16-byte
11968     // atomics have lock-free implementations on some, but not all,
11969     // x86-64 processors.
11970 
11971     // Check power-of-two.
11972     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11973     if (Size.isPowerOfTwo()) {
11974       // Check against inlining width.
11975       unsigned InlineWidthBits =
11976           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11977       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11978         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11979             Size == CharUnits::One() ||
11980             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11981                                                 Expr::NPC_NeverValueDependent))
11982           // OK, we will inline appropriately-aligned operations of this size,
11983           // and _Atomic(T) is appropriately-aligned.
11984           return Success(1, E);
11985 
11986         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11987           castAs<PointerType>()->getPointeeType();
11988         if (!PointeeType->isIncompleteType() &&
11989             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11990           // OK, we will inline operations on this object.
11991           return Success(1, E);
11992         }
11993       }
11994     }
11995 
11996     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11997         Success(0, E) : Error(E);
11998   }
11999   case Builtin::BIomp_is_initial_device:
12000     // We can decide statically which value the runtime would return if called.
12001     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
12002   case Builtin::BI__builtin_add_overflow:
12003   case Builtin::BI__builtin_sub_overflow:
12004   case Builtin::BI__builtin_mul_overflow:
12005   case Builtin::BI__builtin_sadd_overflow:
12006   case Builtin::BI__builtin_uadd_overflow:
12007   case Builtin::BI__builtin_uaddl_overflow:
12008   case Builtin::BI__builtin_uaddll_overflow:
12009   case Builtin::BI__builtin_usub_overflow:
12010   case Builtin::BI__builtin_usubl_overflow:
12011   case Builtin::BI__builtin_usubll_overflow:
12012   case Builtin::BI__builtin_umul_overflow:
12013   case Builtin::BI__builtin_umull_overflow:
12014   case Builtin::BI__builtin_umulll_overflow:
12015   case Builtin::BI__builtin_saddl_overflow:
12016   case Builtin::BI__builtin_saddll_overflow:
12017   case Builtin::BI__builtin_ssub_overflow:
12018   case Builtin::BI__builtin_ssubl_overflow:
12019   case Builtin::BI__builtin_ssubll_overflow:
12020   case Builtin::BI__builtin_smul_overflow:
12021   case Builtin::BI__builtin_smull_overflow:
12022   case Builtin::BI__builtin_smulll_overflow: {
12023     LValue ResultLValue;
12024     APSInt LHS, RHS;
12025 
12026     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12027     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12028         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12029         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12030       return false;
12031 
12032     APSInt Result;
12033     bool DidOverflow = false;
12034 
12035     // If the types don't have to match, enlarge all 3 to the largest of them.
12036     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12037         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12038         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12039       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12040                       ResultType->isSignedIntegerOrEnumerationType();
12041       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12042                       ResultType->isSignedIntegerOrEnumerationType();
12043       uint64_t LHSSize = LHS.getBitWidth();
12044       uint64_t RHSSize = RHS.getBitWidth();
12045       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12046       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12047 
12048       // Add an additional bit if the signedness isn't uniformly agreed to. We
12049       // could do this ONLY if there is a signed and an unsigned that both have
12050       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12051       // caught in the shrink-to-result later anyway.
12052       if (IsSigned && !AllSigned)
12053         ++MaxBits;
12054 
12055       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12056       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12057       Result = APSInt(MaxBits, !IsSigned);
12058     }
12059 
12060     // Find largest int.
12061     switch (BuiltinOp) {
12062     default:
12063       llvm_unreachable("Invalid value for BuiltinOp");
12064     case Builtin::BI__builtin_add_overflow:
12065     case Builtin::BI__builtin_sadd_overflow:
12066     case Builtin::BI__builtin_saddl_overflow:
12067     case Builtin::BI__builtin_saddll_overflow:
12068     case Builtin::BI__builtin_uadd_overflow:
12069     case Builtin::BI__builtin_uaddl_overflow:
12070     case Builtin::BI__builtin_uaddll_overflow:
12071       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12072                               : LHS.uadd_ov(RHS, DidOverflow);
12073       break;
12074     case Builtin::BI__builtin_sub_overflow:
12075     case Builtin::BI__builtin_ssub_overflow:
12076     case Builtin::BI__builtin_ssubl_overflow:
12077     case Builtin::BI__builtin_ssubll_overflow:
12078     case Builtin::BI__builtin_usub_overflow:
12079     case Builtin::BI__builtin_usubl_overflow:
12080     case Builtin::BI__builtin_usubll_overflow:
12081       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12082                               : LHS.usub_ov(RHS, DidOverflow);
12083       break;
12084     case Builtin::BI__builtin_mul_overflow:
12085     case Builtin::BI__builtin_smul_overflow:
12086     case Builtin::BI__builtin_smull_overflow:
12087     case Builtin::BI__builtin_smulll_overflow:
12088     case Builtin::BI__builtin_umul_overflow:
12089     case Builtin::BI__builtin_umull_overflow:
12090     case Builtin::BI__builtin_umulll_overflow:
12091       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12092                               : LHS.umul_ov(RHS, DidOverflow);
12093       break;
12094     }
12095 
12096     // In the case where multiple sizes are allowed, truncate and see if
12097     // the values are the same.
12098     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12099         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12100         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12101       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12102       // since it will give us the behavior of a TruncOrSelf in the case where
12103       // its parameter <= its size.  We previously set Result to be at least the
12104       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12105       // will work exactly like TruncOrSelf.
12106       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12107       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12108 
12109       if (!APSInt::isSameValue(Temp, Result))
12110         DidOverflow = true;
12111       Result = Temp;
12112     }
12113 
12114     APValue APV{Result};
12115     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12116       return false;
12117     return Success(DidOverflow, E);
12118   }
12119   }
12120 }
12121 
12122 /// Determine whether this is a pointer past the end of the complete
12123 /// object referred to by the lvalue.
isOnePastTheEndOfCompleteObject(const ASTContext & Ctx,const LValue & LV)12124 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12125                                             const LValue &LV) {
12126   // A null pointer can be viewed as being "past the end" but we don't
12127   // choose to look at it that way here.
12128   if (!LV.getLValueBase())
12129     return false;
12130 
12131   // If the designator is valid and refers to a subobject, we're not pointing
12132   // past the end.
12133   if (!LV.getLValueDesignator().Invalid &&
12134       !LV.getLValueDesignator().isOnePastTheEnd())
12135     return false;
12136 
12137   // A pointer to an incomplete type might be past-the-end if the type's size is
12138   // zero.  We cannot tell because the type is incomplete.
12139   QualType Ty = getType(LV.getLValueBase());
12140   if (Ty->isIncompleteType())
12141     return true;
12142 
12143   // We're a past-the-end pointer if we point to the byte after the object,
12144   // no matter what our type or path is.
12145   auto Size = Ctx.getTypeSizeInChars(Ty);
12146   return LV.getLValueOffset() == Size;
12147 }
12148 
12149 namespace {
12150 
12151 /// Data recursive integer evaluator of certain binary operators.
12152 ///
12153 /// We use a data recursive algorithm for binary operators so that we are able
12154 /// to handle extreme cases of chained binary operators without causing stack
12155 /// overflow.
12156 class DataRecursiveIntBinOpEvaluator {
12157   struct EvalResult {
12158     APValue Val;
12159     bool Failed;
12160 
EvalResult__anone93968c62811::DataRecursiveIntBinOpEvaluator::EvalResult12161     EvalResult() : Failed(false) { }
12162 
swap__anone93968c62811::DataRecursiveIntBinOpEvaluator::EvalResult12163     void swap(EvalResult &RHS) {
12164       Val.swap(RHS.Val);
12165       Failed = RHS.Failed;
12166       RHS.Failed = false;
12167     }
12168   };
12169 
12170   struct Job {
12171     const Expr *E;
12172     EvalResult LHSResult; // meaningful only for binary operator expression.
12173     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12174 
12175     Job() = default;
12176     Job(Job &&) = default;
12177 
startSpeculativeEval__anone93968c62811::DataRecursiveIntBinOpEvaluator::Job12178     void startSpeculativeEval(EvalInfo &Info) {
12179       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12180     }
12181 
12182   private:
12183     SpeculativeEvaluationRAII SpecEvalRAII;
12184   };
12185 
12186   SmallVector<Job, 16> Queue;
12187 
12188   IntExprEvaluator &IntEval;
12189   EvalInfo &Info;
12190   APValue &FinalResult;
12191 
12192 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)12193   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12194     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12195 
12196   /// True if \param E is a binary operator that we are going to handle
12197   /// data recursively.
12198   /// We handle binary operators that are comma, logical, or that have operands
12199   /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)12200   static bool shouldEnqueue(const BinaryOperator *E) {
12201     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12202            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
12203             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12204             E->getRHS()->getType()->isIntegralOrEnumerationType());
12205   }
12206 
Traverse(const BinaryOperator * E)12207   bool Traverse(const BinaryOperator *E) {
12208     enqueue(E);
12209     EvalResult PrevResult;
12210     while (!Queue.empty())
12211       process(PrevResult);
12212 
12213     if (PrevResult.Failed) return false;
12214 
12215     FinalResult.swap(PrevResult.Val);
12216     return true;
12217   }
12218 
12219 private:
Success(uint64_t Value,const Expr * E,APValue & Result)12220   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12221     return IntEval.Success(Value, E, Result);
12222   }
Success(const APSInt & Value,const Expr * E,APValue & Result)12223   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12224     return IntEval.Success(Value, E, Result);
12225   }
Error(const Expr * E)12226   bool Error(const Expr *E) {
12227     return IntEval.Error(E);
12228   }
Error(const Expr * E,diag::kind D)12229   bool Error(const Expr *E, diag::kind D) {
12230     return IntEval.Error(E, D);
12231   }
12232 
CCEDiag(const Expr * E,diag::kind D)12233   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12234     return Info.CCEDiag(E, D);
12235   }
12236 
12237   // Returns true if visiting the RHS is necessary, false otherwise.
12238   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12239                          bool &SuppressRHSDiags);
12240 
12241   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12242                   const BinaryOperator *E, APValue &Result);
12243 
EvaluateExpr(const Expr * E,EvalResult & Result)12244   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12245     Result.Failed = !Evaluate(Result.Val, Info, E);
12246     if (Result.Failed)
12247       Result.Val = APValue();
12248   }
12249 
12250   void process(EvalResult &Result);
12251 
enqueue(const Expr * E)12252   void enqueue(const Expr *E) {
12253     E = E->IgnoreParens();
12254     Queue.resize(Queue.size()+1);
12255     Queue.back().E = E;
12256     Queue.back().Kind = Job::AnyExprKind;
12257   }
12258 };
12259 
12260 }
12261 
12262 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)12263        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12264                          bool &SuppressRHSDiags) {
12265   if (E->getOpcode() == BO_Comma) {
12266     // Ignore LHS but note if we could not evaluate it.
12267     if (LHSResult.Failed)
12268       return Info.noteSideEffect();
12269     return true;
12270   }
12271 
12272   if (E->isLogicalOp()) {
12273     bool LHSAsBool;
12274     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12275       // We were able to evaluate the LHS, see if we can get away with not
12276       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12277       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12278         Success(LHSAsBool, E, LHSResult.Val);
12279         return false; // Ignore RHS
12280       }
12281     } else {
12282       LHSResult.Failed = true;
12283 
12284       // Since we weren't able to evaluate the left hand side, it
12285       // might have had side effects.
12286       if (!Info.noteSideEffect())
12287         return false;
12288 
12289       // We can't evaluate the LHS; however, sometimes the result
12290       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12291       // Don't ignore RHS and suppress diagnostics from this arm.
12292       SuppressRHSDiags = true;
12293     }
12294 
12295     return true;
12296   }
12297 
12298   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12299          E->getRHS()->getType()->isIntegralOrEnumerationType());
12300 
12301   if (LHSResult.Failed && !Info.noteFailure())
12302     return false; // Ignore RHS;
12303 
12304   return true;
12305 }
12306 
addOrSubLValueAsInteger(APValue & LVal,const APSInt & Index,bool IsSub)12307 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12308                                     bool IsSub) {
12309   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12310   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12311   // offsets.
12312   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12313   CharUnits &Offset = LVal.getLValueOffset();
12314   uint64_t Offset64 = Offset.getQuantity();
12315   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12316   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12317                                          : Offset64 + Index64);
12318 }
12319 
12320 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)12321        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12322                   const BinaryOperator *E, APValue &Result) {
12323   if (E->getOpcode() == BO_Comma) {
12324     if (RHSResult.Failed)
12325       return false;
12326     Result = RHSResult.Val;
12327     return true;
12328   }
12329 
12330   if (E->isLogicalOp()) {
12331     bool lhsResult, rhsResult;
12332     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12333     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12334 
12335     if (LHSIsOK) {
12336       if (RHSIsOK) {
12337         if (E->getOpcode() == BO_LOr)
12338           return Success(lhsResult || rhsResult, E, Result);
12339         else
12340           return Success(lhsResult && rhsResult, E, Result);
12341       }
12342     } else {
12343       if (RHSIsOK) {
12344         // We can't evaluate the LHS; however, sometimes the result
12345         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12346         if (rhsResult == (E->getOpcode() == BO_LOr))
12347           return Success(rhsResult, E, Result);
12348       }
12349     }
12350 
12351     return false;
12352   }
12353 
12354   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12355          E->getRHS()->getType()->isIntegralOrEnumerationType());
12356 
12357   if (LHSResult.Failed || RHSResult.Failed)
12358     return false;
12359 
12360   const APValue &LHSVal = LHSResult.Val;
12361   const APValue &RHSVal = RHSResult.Val;
12362 
12363   // Handle cases like (unsigned long)&a + 4.
12364   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12365     Result = LHSVal;
12366     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12367     return true;
12368   }
12369 
12370   // Handle cases like 4 + (unsigned long)&a
12371   if (E->getOpcode() == BO_Add &&
12372       RHSVal.isLValue() && LHSVal.isInt()) {
12373     Result = RHSVal;
12374     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12375     return true;
12376   }
12377 
12378   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12379     // Handle (intptr_t)&&A - (intptr_t)&&B.
12380     if (!LHSVal.getLValueOffset().isZero() ||
12381         !RHSVal.getLValueOffset().isZero())
12382       return false;
12383     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12384     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12385     if (!LHSExpr || !RHSExpr)
12386       return false;
12387     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12388     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12389     if (!LHSAddrExpr || !RHSAddrExpr)
12390       return false;
12391     // Make sure both labels come from the same function.
12392     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12393         RHSAddrExpr->getLabel()->getDeclContext())
12394       return false;
12395     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12396     return true;
12397   }
12398 
12399   // All the remaining cases expect both operands to be an integer
12400   if (!LHSVal.isInt() || !RHSVal.isInt())
12401     return Error(E);
12402 
12403   // Set up the width and signedness manually, in case it can't be deduced
12404   // from the operation we're performing.
12405   // FIXME: Don't do this in the cases where we can deduce it.
12406   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12407                E->getType()->isUnsignedIntegerOrEnumerationType());
12408   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12409                          RHSVal.getInt(), Value))
12410     return false;
12411   return Success(Value, E, Result);
12412 }
12413 
process(EvalResult & Result)12414 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12415   Job &job = Queue.back();
12416 
12417   switch (job.Kind) {
12418     case Job::AnyExprKind: {
12419       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12420         if (shouldEnqueue(Bop)) {
12421           job.Kind = Job::BinOpKind;
12422           enqueue(Bop->getLHS());
12423           return;
12424         }
12425       }
12426 
12427       EvaluateExpr(job.E, Result);
12428       Queue.pop_back();
12429       return;
12430     }
12431 
12432     case Job::BinOpKind: {
12433       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12434       bool SuppressRHSDiags = false;
12435       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12436         Queue.pop_back();
12437         return;
12438       }
12439       if (SuppressRHSDiags)
12440         job.startSpeculativeEval(Info);
12441       job.LHSResult.swap(Result);
12442       job.Kind = Job::BinOpVisitedLHSKind;
12443       enqueue(Bop->getRHS());
12444       return;
12445     }
12446 
12447     case Job::BinOpVisitedLHSKind: {
12448       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12449       EvalResult RHS;
12450       RHS.swap(Result);
12451       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12452       Queue.pop_back();
12453       return;
12454     }
12455   }
12456 
12457   llvm_unreachable("Invalid Job::Kind!");
12458 }
12459 
12460 namespace {
12461 /// Used when we determine that we should fail, but can keep evaluating prior to
12462 /// noting that we had a failure.
12463 class DelayedNoteFailureRAII {
12464   EvalInfo &Info;
12465   bool NoteFailure;
12466 
12467 public:
DelayedNoteFailureRAII(EvalInfo & Info,bool NoteFailure=true)12468   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12469       : Info(Info), NoteFailure(NoteFailure) {}
~DelayedNoteFailureRAII()12470   ~DelayedNoteFailureRAII() {
12471     if (NoteFailure) {
12472       bool ContinueAfterFailure = Info.noteFailure();
12473       (void)ContinueAfterFailure;
12474       assert(ContinueAfterFailure &&
12475              "Shouldn't have kept evaluating on failure.");
12476     }
12477   }
12478 };
12479 
12480 enum class CmpResult {
12481   Unequal,
12482   Less,
12483   Equal,
12484   Greater,
12485   Unordered,
12486 };
12487 }
12488 
12489 template <class SuccessCB, class AfterCB>
12490 static bool
EvaluateComparisonBinaryOperator(EvalInfo & Info,const BinaryOperator * E,SuccessCB && Success,AfterCB && DoAfter)12491 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12492                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12493   assert(!E->isValueDependent());
12494   assert(E->isComparisonOp() && "expected comparison operator");
12495   assert((E->getOpcode() == BO_Cmp ||
12496           E->getType()->isIntegralOrEnumerationType()) &&
12497          "unsupported binary expression evaluation");
12498   auto Error = [&](const Expr *E) {
12499     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12500     return false;
12501   };
12502 
12503   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12504   bool IsEquality = E->isEqualityOp();
12505 
12506   QualType LHSTy = E->getLHS()->getType();
12507   QualType RHSTy = E->getRHS()->getType();
12508 
12509   if (LHSTy->isIntegralOrEnumerationType() &&
12510       RHSTy->isIntegralOrEnumerationType()) {
12511     APSInt LHS, RHS;
12512     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12513     if (!LHSOK && !Info.noteFailure())
12514       return false;
12515     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12516       return false;
12517     if (LHS < RHS)
12518       return Success(CmpResult::Less, E);
12519     if (LHS > RHS)
12520       return Success(CmpResult::Greater, E);
12521     return Success(CmpResult::Equal, E);
12522   }
12523 
12524   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12525     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12526     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12527 
12528     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12529     if (!LHSOK && !Info.noteFailure())
12530       return false;
12531     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12532       return false;
12533     if (LHSFX < RHSFX)
12534       return Success(CmpResult::Less, E);
12535     if (LHSFX > RHSFX)
12536       return Success(CmpResult::Greater, E);
12537     return Success(CmpResult::Equal, E);
12538   }
12539 
12540   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12541     ComplexValue LHS, RHS;
12542     bool LHSOK;
12543     if (E->isAssignmentOp()) {
12544       LValue LV;
12545       EvaluateLValue(E->getLHS(), LV, Info);
12546       LHSOK = false;
12547     } else if (LHSTy->isRealFloatingType()) {
12548       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12549       if (LHSOK) {
12550         LHS.makeComplexFloat();
12551         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12552       }
12553     } else {
12554       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12555     }
12556     if (!LHSOK && !Info.noteFailure())
12557       return false;
12558 
12559     if (E->getRHS()->getType()->isRealFloatingType()) {
12560       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12561         return false;
12562       RHS.makeComplexFloat();
12563       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12564     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12565       return false;
12566 
12567     if (LHS.isComplexFloat()) {
12568       APFloat::cmpResult CR_r =
12569         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12570       APFloat::cmpResult CR_i =
12571         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12572       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12573       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12574     } else {
12575       assert(IsEquality && "invalid complex comparison");
12576       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12577                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12578       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12579     }
12580   }
12581 
12582   if (LHSTy->isRealFloatingType() &&
12583       RHSTy->isRealFloatingType()) {
12584     APFloat RHS(0.0), LHS(0.0);
12585 
12586     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12587     if (!LHSOK && !Info.noteFailure())
12588       return false;
12589 
12590     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12591       return false;
12592 
12593     assert(E->isComparisonOp() && "Invalid binary operator!");
12594     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12595     if (!Info.InConstantContext &&
12596         APFloatCmpResult == APFloat::cmpUnordered &&
12597         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12598       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12599       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12600       return false;
12601     }
12602     auto GetCmpRes = [&]() {
12603       switch (APFloatCmpResult) {
12604       case APFloat::cmpEqual:
12605         return CmpResult::Equal;
12606       case APFloat::cmpLessThan:
12607         return CmpResult::Less;
12608       case APFloat::cmpGreaterThan:
12609         return CmpResult::Greater;
12610       case APFloat::cmpUnordered:
12611         return CmpResult::Unordered;
12612       }
12613       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12614     };
12615     return Success(GetCmpRes(), E);
12616   }
12617 
12618   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12619     LValue LHSValue, RHSValue;
12620 
12621     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12622     if (!LHSOK && !Info.noteFailure())
12623       return false;
12624 
12625     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12626       return false;
12627 
12628     // Reject differing bases from the normal codepath; we special-case
12629     // comparisons to null.
12630     if (!HasSameBase(LHSValue, RHSValue)) {
12631       // Inequalities and subtractions between unrelated pointers have
12632       // unspecified or undefined behavior.
12633       if (!IsEquality) {
12634         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12635         return false;
12636       }
12637       // A constant address may compare equal to the address of a symbol.
12638       // The one exception is that address of an object cannot compare equal
12639       // to a null pointer constant.
12640       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12641           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12642         return Error(E);
12643       // It's implementation-defined whether distinct literals will have
12644       // distinct addresses. In clang, the result of such a comparison is
12645       // unspecified, so it is not a constant expression. However, we do know
12646       // that the address of a literal will be non-null.
12647       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12648           LHSValue.Base && RHSValue.Base)
12649         return Error(E);
12650       // We can't tell whether weak symbols will end up pointing to the same
12651       // object.
12652       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12653         return Error(E);
12654       // We can't compare the address of the start of one object with the
12655       // past-the-end address of another object, per C++ DR1652.
12656       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12657            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12658           (RHSValue.Base && RHSValue.Offset.isZero() &&
12659            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12660         return Error(E);
12661       // We can't tell whether an object is at the same address as another
12662       // zero sized object.
12663       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12664           (LHSValue.Base && isZeroSized(RHSValue)))
12665         return Error(E);
12666       return Success(CmpResult::Unequal, E);
12667     }
12668 
12669     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12670     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12671 
12672     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12673     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12674 
12675     // C++11 [expr.rel]p3:
12676     //   Pointers to void (after pointer conversions) can be compared, with a
12677     //   result defined as follows: If both pointers represent the same
12678     //   address or are both the null pointer value, the result is true if the
12679     //   operator is <= or >= and false otherwise; otherwise the result is
12680     //   unspecified.
12681     // We interpret this as applying to pointers to *cv* void.
12682     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12683       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12684 
12685     // C++11 [expr.rel]p2:
12686     // - If two pointers point to non-static data members of the same object,
12687     //   or to subobjects or array elements fo such members, recursively, the
12688     //   pointer to the later declared member compares greater provided the
12689     //   two members have the same access control and provided their class is
12690     //   not a union.
12691     //   [...]
12692     // - Otherwise pointer comparisons are unspecified.
12693     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12694       bool WasArrayIndex;
12695       unsigned Mismatch = FindDesignatorMismatch(
12696           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12697       // At the point where the designators diverge, the comparison has a
12698       // specified value if:
12699       //  - we are comparing array indices
12700       //  - we are comparing fields of a union, or fields with the same access
12701       // Otherwise, the result is unspecified and thus the comparison is not a
12702       // constant expression.
12703       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12704           Mismatch < RHSDesignator.Entries.size()) {
12705         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12706         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12707         if (!LF && !RF)
12708           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12709         else if (!LF)
12710           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12711               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12712               << RF->getParent() << RF;
12713         else if (!RF)
12714           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12715               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12716               << LF->getParent() << LF;
12717         else if (!LF->getParent()->isUnion() &&
12718                  LF->getAccess() != RF->getAccess())
12719           Info.CCEDiag(E,
12720                        diag::note_constexpr_pointer_comparison_differing_access)
12721               << LF << LF->getAccess() << RF << RF->getAccess()
12722               << LF->getParent();
12723       }
12724     }
12725 
12726     // The comparison here must be unsigned, and performed with the same
12727     // width as the pointer.
12728     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12729     uint64_t CompareLHS = LHSOffset.getQuantity();
12730     uint64_t CompareRHS = RHSOffset.getQuantity();
12731     assert(PtrSize <= 64 && "Unexpected pointer width");
12732     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12733     CompareLHS &= Mask;
12734     CompareRHS &= Mask;
12735 
12736     // If there is a base and this is a relational operator, we can only
12737     // compare pointers within the object in question; otherwise, the result
12738     // depends on where the object is located in memory.
12739     if (!LHSValue.Base.isNull() && IsRelational) {
12740       QualType BaseTy = getType(LHSValue.Base);
12741       if (BaseTy->isIncompleteType())
12742         return Error(E);
12743       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12744       uint64_t OffsetLimit = Size.getQuantity();
12745       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12746         return Error(E);
12747     }
12748 
12749     if (CompareLHS < CompareRHS)
12750       return Success(CmpResult::Less, E);
12751     if (CompareLHS > CompareRHS)
12752       return Success(CmpResult::Greater, E);
12753     return Success(CmpResult::Equal, E);
12754   }
12755 
12756   if (LHSTy->isMemberPointerType()) {
12757     assert(IsEquality && "unexpected member pointer operation");
12758     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12759 
12760     MemberPtr LHSValue, RHSValue;
12761 
12762     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12763     if (!LHSOK && !Info.noteFailure())
12764       return false;
12765 
12766     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12767       return false;
12768 
12769     // C++11 [expr.eq]p2:
12770     //   If both operands are null, they compare equal. Otherwise if only one is
12771     //   null, they compare unequal.
12772     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12773       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12774       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12775     }
12776 
12777     //   Otherwise if either is a pointer to a virtual member function, the
12778     //   result is unspecified.
12779     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12780       if (MD->isVirtual())
12781         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12782     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12783       if (MD->isVirtual())
12784         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12785 
12786     //   Otherwise they compare equal if and only if they would refer to the
12787     //   same member of the same most derived object or the same subobject if
12788     //   they were dereferenced with a hypothetical object of the associated
12789     //   class type.
12790     bool Equal = LHSValue == RHSValue;
12791     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12792   }
12793 
12794   if (LHSTy->isNullPtrType()) {
12795     assert(E->isComparisonOp() && "unexpected nullptr operation");
12796     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12797     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12798     // are compared, the result is true of the operator is <=, >= or ==, and
12799     // false otherwise.
12800     return Success(CmpResult::Equal, E);
12801   }
12802 
12803   return DoAfter();
12804 }
12805 
VisitBinCmp(const BinaryOperator * E)12806 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12807   if (!CheckLiteralType(Info, E))
12808     return false;
12809 
12810   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12811     ComparisonCategoryResult CCR;
12812     switch (CR) {
12813     case CmpResult::Unequal:
12814       llvm_unreachable("should never produce Unequal for three-way comparison");
12815     case CmpResult::Less:
12816       CCR = ComparisonCategoryResult::Less;
12817       break;
12818     case CmpResult::Equal:
12819       CCR = ComparisonCategoryResult::Equal;
12820       break;
12821     case CmpResult::Greater:
12822       CCR = ComparisonCategoryResult::Greater;
12823       break;
12824     case CmpResult::Unordered:
12825       CCR = ComparisonCategoryResult::Unordered;
12826       break;
12827     }
12828     // Evaluation succeeded. Lookup the information for the comparison category
12829     // type and fetch the VarDecl for the result.
12830     const ComparisonCategoryInfo &CmpInfo =
12831         Info.Ctx.CompCategories.getInfoForType(E->getType());
12832     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12833     // Check and evaluate the result as a constant expression.
12834     LValue LV;
12835     LV.set(VD);
12836     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12837       return false;
12838     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12839                                    ConstantExprKind::Normal);
12840   };
12841   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12842     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12843   });
12844 }
12845 
VisitBinaryOperator(const BinaryOperator * E)12846 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12847   // We don't call noteFailure immediately because the assignment happens after
12848   // we evaluate LHS and RHS.
12849   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12850     return Error(E);
12851 
12852   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12853   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12854     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12855 
12856   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12857           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12858          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12859 
12860   if (E->isComparisonOp()) {
12861     // Evaluate builtin binary comparisons by evaluating them as three-way
12862     // comparisons and then translating the result.
12863     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12864       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12865              "should only produce Unequal for equality comparisons");
12866       bool IsEqual   = CR == CmpResult::Equal,
12867            IsLess    = CR == CmpResult::Less,
12868            IsGreater = CR == CmpResult::Greater;
12869       auto Op = E->getOpcode();
12870       switch (Op) {
12871       default:
12872         llvm_unreachable("unsupported binary operator");
12873       case BO_EQ:
12874       case BO_NE:
12875         return Success(IsEqual == (Op == BO_EQ), E);
12876       case BO_LT:
12877         return Success(IsLess, E);
12878       case BO_GT:
12879         return Success(IsGreater, E);
12880       case BO_LE:
12881         return Success(IsEqual || IsLess, E);
12882       case BO_GE:
12883         return Success(IsEqual || IsGreater, E);
12884       }
12885     };
12886     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12887       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12888     });
12889   }
12890 
12891   QualType LHSTy = E->getLHS()->getType();
12892   QualType RHSTy = E->getRHS()->getType();
12893 
12894   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12895       E->getOpcode() == BO_Sub) {
12896     LValue LHSValue, RHSValue;
12897 
12898     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12899     if (!LHSOK && !Info.noteFailure())
12900       return false;
12901 
12902     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12903       return false;
12904 
12905     // Reject differing bases from the normal codepath; we special-case
12906     // comparisons to null.
12907     if (!HasSameBase(LHSValue, RHSValue)) {
12908       // Handle &&A - &&B.
12909       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12910         return Error(E);
12911       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12912       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12913       if (!LHSExpr || !RHSExpr)
12914         return Error(E);
12915       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12916       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12917       if (!LHSAddrExpr || !RHSAddrExpr)
12918         return Error(E);
12919       // Make sure both labels come from the same function.
12920       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12921           RHSAddrExpr->getLabel()->getDeclContext())
12922         return Error(E);
12923       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12924     }
12925     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12926     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12927 
12928     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12929     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12930 
12931     // C++11 [expr.add]p6:
12932     //   Unless both pointers point to elements of the same array object, or
12933     //   one past the last element of the array object, the behavior is
12934     //   undefined.
12935     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12936         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12937                                 RHSDesignator))
12938       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12939 
12940     QualType Type = E->getLHS()->getType();
12941     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12942 
12943     CharUnits ElementSize;
12944     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12945       return false;
12946 
12947     // As an extension, a type may have zero size (empty struct or union in
12948     // C, array of zero length). Pointer subtraction in such cases has
12949     // undefined behavior, so is not constant.
12950     if (ElementSize.isZero()) {
12951       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12952           << ElementType;
12953       return false;
12954     }
12955 
12956     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12957     // and produce incorrect results when it overflows. Such behavior
12958     // appears to be non-conforming, but is common, so perhaps we should
12959     // assume the standard intended for such cases to be undefined behavior
12960     // and check for them.
12961 
12962     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12963     // overflow in the final conversion to ptrdiff_t.
12964     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12965     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12966     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12967                     false);
12968     APSInt TrueResult = (LHS - RHS) / ElemSize;
12969     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12970 
12971     if (Result.extend(65) != TrueResult &&
12972         !HandleOverflow(Info, E, TrueResult, E->getType()))
12973       return false;
12974     return Success(Result, E);
12975   }
12976 
12977   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12978 }
12979 
12980 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12981 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)12982 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12983                                     const UnaryExprOrTypeTraitExpr *E) {
12984   switch(E->getKind()) {
12985   case UETT_PreferredAlignOf:
12986   case UETT_AlignOf: {
12987     if (E->isArgumentType())
12988       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12989                      E);
12990     else
12991       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12992                      E);
12993   }
12994 
12995   case UETT_VecStep: {
12996     QualType Ty = E->getTypeOfArgument();
12997 
12998     if (Ty->isVectorType()) {
12999       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13000 
13001       // The vec_step built-in functions that take a 3-component
13002       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13003       if (n == 3)
13004         n = 4;
13005 
13006       return Success(n, E);
13007     } else
13008       return Success(1, E);
13009   }
13010 
13011   case UETT_SizeOf: {
13012     QualType SrcTy = E->getTypeOfArgument();
13013     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13014     //   the result is the size of the referenced type."
13015     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13016       SrcTy = Ref->getPointeeType();
13017 
13018     CharUnits Sizeof;
13019     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13020       return false;
13021     return Success(Sizeof, E);
13022   }
13023   case UETT_OpenMPRequiredSimdAlign:
13024     assert(E->isArgumentType());
13025     return Success(
13026         Info.Ctx.toCharUnitsFromBits(
13027                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13028             .getQuantity(),
13029         E);
13030   }
13031 
13032   llvm_unreachable("unknown expr/type trait");
13033 }
13034 
VisitOffsetOfExpr(const OffsetOfExpr * OOE)13035 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13036   CharUnits Result;
13037   unsigned n = OOE->getNumComponents();
13038   if (n == 0)
13039     return Error(OOE);
13040   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13041   for (unsigned i = 0; i != n; ++i) {
13042     OffsetOfNode ON = OOE->getComponent(i);
13043     switch (ON.getKind()) {
13044     case OffsetOfNode::Array: {
13045       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13046       APSInt IdxResult;
13047       if (!EvaluateInteger(Idx, IdxResult, Info))
13048         return false;
13049       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13050       if (!AT)
13051         return Error(OOE);
13052       CurrentType = AT->getElementType();
13053       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13054       Result += IdxResult.getSExtValue() * ElementSize;
13055       break;
13056     }
13057 
13058     case OffsetOfNode::Field: {
13059       FieldDecl *MemberDecl = ON.getField();
13060       const RecordType *RT = CurrentType->getAs<RecordType>();
13061       if (!RT)
13062         return Error(OOE);
13063       RecordDecl *RD = RT->getDecl();
13064       if (RD->isInvalidDecl()) return false;
13065       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13066       unsigned i = MemberDecl->getFieldIndex();
13067       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13068       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13069       CurrentType = MemberDecl->getType().getNonReferenceType();
13070       break;
13071     }
13072 
13073     case OffsetOfNode::Identifier:
13074       llvm_unreachable("dependent __builtin_offsetof");
13075 
13076     case OffsetOfNode::Base: {
13077       CXXBaseSpecifier *BaseSpec = ON.getBase();
13078       if (BaseSpec->isVirtual())
13079         return Error(OOE);
13080 
13081       // Find the layout of the class whose base we are looking into.
13082       const RecordType *RT = CurrentType->getAs<RecordType>();
13083       if (!RT)
13084         return Error(OOE);
13085       RecordDecl *RD = RT->getDecl();
13086       if (RD->isInvalidDecl()) return false;
13087       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13088 
13089       // Find the base class itself.
13090       CurrentType = BaseSpec->getType();
13091       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13092       if (!BaseRT)
13093         return Error(OOE);
13094 
13095       // Add the offset to the base.
13096       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13097       break;
13098     }
13099     }
13100   }
13101   return Success(Result, OOE);
13102 }
13103 
VisitUnaryOperator(const UnaryOperator * E)13104 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13105   switch (E->getOpcode()) {
13106   default:
13107     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13108     // See C99 6.6p3.
13109     return Error(E);
13110   case UO_Extension:
13111     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13112     // If so, we could clear the diagnostic ID.
13113     return Visit(E->getSubExpr());
13114   case UO_Plus:
13115     // The result is just the value.
13116     return Visit(E->getSubExpr());
13117   case UO_Minus: {
13118     if (!Visit(E->getSubExpr()))
13119       return false;
13120     if (!Result.isInt()) return Error(E);
13121     const APSInt &Value = Result.getInt();
13122     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13123         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13124                         E->getType()))
13125       return false;
13126     return Success(-Value, E);
13127   }
13128   case UO_Not: {
13129     if (!Visit(E->getSubExpr()))
13130       return false;
13131     if (!Result.isInt()) return Error(E);
13132     return Success(~Result.getInt(), E);
13133   }
13134   case UO_LNot: {
13135     bool bres;
13136     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13137       return false;
13138     return Success(!bres, E);
13139   }
13140   }
13141 }
13142 
13143 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13144 /// result type is integer.
VisitCastExpr(const CastExpr * E)13145 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13146   const Expr *SubExpr = E->getSubExpr();
13147   QualType DestType = E->getType();
13148   QualType SrcType = SubExpr->getType();
13149 
13150   switch (E->getCastKind()) {
13151   case CK_BaseToDerived:
13152   case CK_DerivedToBase:
13153   case CK_UncheckedDerivedToBase:
13154   case CK_Dynamic:
13155   case CK_ToUnion:
13156   case CK_ArrayToPointerDecay:
13157   case CK_FunctionToPointerDecay:
13158   case CK_NullToPointer:
13159   case CK_NullToMemberPointer:
13160   case CK_BaseToDerivedMemberPointer:
13161   case CK_DerivedToBaseMemberPointer:
13162   case CK_ReinterpretMemberPointer:
13163   case CK_ConstructorConversion:
13164   case CK_IntegralToPointer:
13165   case CK_ToVoid:
13166   case CK_VectorSplat:
13167   case CK_IntegralToFloating:
13168   case CK_FloatingCast:
13169   case CK_CPointerToObjCPointerCast:
13170   case CK_BlockPointerToObjCPointerCast:
13171   case CK_AnyPointerToBlockPointerCast:
13172   case CK_ObjCObjectLValueCast:
13173   case CK_FloatingRealToComplex:
13174   case CK_FloatingComplexToReal:
13175   case CK_FloatingComplexCast:
13176   case CK_FloatingComplexToIntegralComplex:
13177   case CK_IntegralRealToComplex:
13178   case CK_IntegralComplexCast:
13179   case CK_IntegralComplexToFloatingComplex:
13180   case CK_BuiltinFnToFnPtr:
13181   case CK_ZeroToOCLOpaqueType:
13182   case CK_NonAtomicToAtomic:
13183   case CK_AddressSpaceConversion:
13184   case CK_IntToOCLSampler:
13185   case CK_FloatingToFixedPoint:
13186   case CK_FixedPointToFloating:
13187   case CK_FixedPointCast:
13188   case CK_IntegralToFixedPoint:
13189     llvm_unreachable("invalid cast kind for integral value");
13190 
13191   case CK_BitCast:
13192   case CK_Dependent:
13193   case CK_LValueBitCast:
13194   case CK_ARCProduceObject:
13195   case CK_ARCConsumeObject:
13196   case CK_ARCReclaimReturnedObject:
13197   case CK_ARCExtendBlockObject:
13198   case CK_CopyAndAutoreleaseBlockObject:
13199     return Error(E);
13200 
13201   case CK_UserDefinedConversion:
13202   case CK_LValueToRValue:
13203   case CK_AtomicToNonAtomic:
13204   case CK_NoOp:
13205   case CK_LValueToRValueBitCast:
13206     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13207 
13208   case CK_MemberPointerToBoolean:
13209   case CK_PointerToBoolean:
13210   case CK_IntegralToBoolean:
13211   case CK_FloatingToBoolean:
13212   case CK_BooleanToSignedIntegral:
13213   case CK_FloatingComplexToBoolean:
13214   case CK_IntegralComplexToBoolean: {
13215     bool BoolResult;
13216     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13217       return false;
13218     uint64_t IntResult = BoolResult;
13219     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13220       IntResult = (uint64_t)-1;
13221     return Success(IntResult, E);
13222   }
13223 
13224   case CK_FixedPointToIntegral: {
13225     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13226     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13227       return false;
13228     bool Overflowed;
13229     llvm::APSInt Result = Src.convertToInt(
13230         Info.Ctx.getIntWidth(DestType),
13231         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13232     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13233       return false;
13234     return Success(Result, E);
13235   }
13236 
13237   case CK_FixedPointToBoolean: {
13238     // Unsigned padding does not affect this.
13239     APValue Val;
13240     if (!Evaluate(Val, Info, SubExpr))
13241       return false;
13242     return Success(Val.getFixedPoint().getBoolValue(), E);
13243   }
13244 
13245   case CK_IntegralCast: {
13246     if (!Visit(SubExpr))
13247       return false;
13248 
13249     if (!Result.isInt()) {
13250       // Allow casts of address-of-label differences if they are no-ops
13251       // or narrowing.  (The narrowing case isn't actually guaranteed to
13252       // be constant-evaluatable except in some narrow cases which are hard
13253       // to detect here.  We let it through on the assumption the user knows
13254       // what they are doing.)
13255       if (Result.isAddrLabelDiff())
13256         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13257       // Only allow casts of lvalues if they are lossless.
13258       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13259     }
13260 
13261     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13262                                       Result.getInt()), E);
13263   }
13264 
13265   case CK_PointerToIntegral: {
13266     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13267 
13268     LValue LV;
13269     if (!EvaluatePointer(SubExpr, LV, Info))
13270       return false;
13271 
13272     if (LV.getLValueBase()) {
13273       // Only allow based lvalue casts if they are lossless.
13274       // FIXME: Allow a larger integer size than the pointer size, and allow
13275       // narrowing back down to pointer width in subsequent integral casts.
13276       // FIXME: Check integer type's active bits, not its type size.
13277       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13278         return Error(E);
13279 
13280       LV.Designator.setInvalid();
13281       LV.moveInto(Result);
13282       return true;
13283     }
13284 
13285     APSInt AsInt;
13286     APValue V;
13287     LV.moveInto(V);
13288     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13289       llvm_unreachable("Can't cast this!");
13290 
13291     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13292   }
13293 
13294   case CK_IntegralComplexToReal: {
13295     ComplexValue C;
13296     if (!EvaluateComplex(SubExpr, C, Info))
13297       return false;
13298     return Success(C.getComplexIntReal(), E);
13299   }
13300 
13301   case CK_FloatingToIntegral: {
13302     APFloat F(0.0);
13303     if (!EvaluateFloat(SubExpr, F, Info))
13304       return false;
13305 
13306     APSInt Value;
13307     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13308       return false;
13309     return Success(Value, E);
13310   }
13311   }
13312 
13313   llvm_unreachable("unknown cast resulting in integral value");
13314 }
13315 
VisitUnaryReal(const UnaryOperator * E)13316 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13317   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13318     ComplexValue LV;
13319     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13320       return false;
13321     if (!LV.isComplexInt())
13322       return Error(E);
13323     return Success(LV.getComplexIntReal(), E);
13324   }
13325 
13326   return Visit(E->getSubExpr());
13327 }
13328 
VisitUnaryImag(const UnaryOperator * E)13329 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13330   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13331     ComplexValue LV;
13332     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13333       return false;
13334     if (!LV.isComplexInt())
13335       return Error(E);
13336     return Success(LV.getComplexIntImag(), E);
13337   }
13338 
13339   VisitIgnoredValue(E->getSubExpr());
13340   return Success(0, E);
13341 }
13342 
VisitSizeOfPackExpr(const SizeOfPackExpr * E)13343 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13344   return Success(E->getPackLength(), E);
13345 }
13346 
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)13347 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13348   return Success(E->getValue(), E);
13349 }
13350 
VisitConceptSpecializationExpr(const ConceptSpecializationExpr * E)13351 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13352        const ConceptSpecializationExpr *E) {
13353   return Success(E->isSatisfied(), E);
13354 }
13355 
VisitRequiresExpr(const RequiresExpr * E)13356 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13357   return Success(E->isSatisfied(), E);
13358 }
13359 
VisitUnaryOperator(const UnaryOperator * E)13360 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13361   switch (E->getOpcode()) {
13362     default:
13363       // Invalid unary operators
13364       return Error(E);
13365     case UO_Plus:
13366       // The result is just the value.
13367       return Visit(E->getSubExpr());
13368     case UO_Minus: {
13369       if (!Visit(E->getSubExpr())) return false;
13370       if (!Result.isFixedPoint())
13371         return Error(E);
13372       bool Overflowed;
13373       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13374       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13375         return false;
13376       return Success(Negated, E);
13377     }
13378     case UO_LNot: {
13379       bool bres;
13380       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13381         return false;
13382       return Success(!bres, E);
13383     }
13384   }
13385 }
13386 
VisitCastExpr(const CastExpr * E)13387 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13388   const Expr *SubExpr = E->getSubExpr();
13389   QualType DestType = E->getType();
13390   assert(DestType->isFixedPointType() &&
13391          "Expected destination type to be a fixed point type");
13392   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13393 
13394   switch (E->getCastKind()) {
13395   case CK_FixedPointCast: {
13396     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13397     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13398       return false;
13399     bool Overflowed;
13400     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13401     if (Overflowed) {
13402       if (Info.checkingForUndefinedBehavior())
13403         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13404                                          diag::warn_fixedpoint_constant_overflow)
13405           << Result.toString() << E->getType();
13406       else if (!HandleOverflow(Info, E, Result, E->getType()))
13407         return false;
13408     }
13409     return Success(Result, E);
13410   }
13411   case CK_IntegralToFixedPoint: {
13412     APSInt Src;
13413     if (!EvaluateInteger(SubExpr, Src, Info))
13414       return false;
13415 
13416     bool Overflowed;
13417     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13418         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13419 
13420     if (Overflowed) {
13421       if (Info.checkingForUndefinedBehavior())
13422         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13423                                          diag::warn_fixedpoint_constant_overflow)
13424           << IntResult.toString() << E->getType();
13425       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13426         return false;
13427     }
13428 
13429     return Success(IntResult, E);
13430   }
13431   case CK_FloatingToFixedPoint: {
13432     APFloat Src(0.0);
13433     if (!EvaluateFloat(SubExpr, Src, Info))
13434       return false;
13435 
13436     bool Overflowed;
13437     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13438         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13439 
13440     if (Overflowed) {
13441       if (Info.checkingForUndefinedBehavior())
13442         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13443                                          diag::warn_fixedpoint_constant_overflow)
13444           << Result.toString() << E->getType();
13445       else if (!HandleOverflow(Info, E, Result, E->getType()))
13446         return false;
13447     }
13448 
13449     return Success(Result, E);
13450   }
13451   case CK_NoOp:
13452   case CK_LValueToRValue:
13453     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13454   default:
13455     return Error(E);
13456   }
13457 }
13458 
VisitBinaryOperator(const BinaryOperator * E)13459 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13460   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13461     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13462 
13463   const Expr *LHS = E->getLHS();
13464   const Expr *RHS = E->getRHS();
13465   FixedPointSemantics ResultFXSema =
13466       Info.Ctx.getFixedPointSemantics(E->getType());
13467 
13468   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13469   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13470     return false;
13471   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13472   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13473     return false;
13474 
13475   bool OpOverflow = false, ConversionOverflow = false;
13476   APFixedPoint Result(LHSFX.getSemantics());
13477   switch (E->getOpcode()) {
13478   case BO_Add: {
13479     Result = LHSFX.add(RHSFX, &OpOverflow)
13480                   .convert(ResultFXSema, &ConversionOverflow);
13481     break;
13482   }
13483   case BO_Sub: {
13484     Result = LHSFX.sub(RHSFX, &OpOverflow)
13485                   .convert(ResultFXSema, &ConversionOverflow);
13486     break;
13487   }
13488   case BO_Mul: {
13489     Result = LHSFX.mul(RHSFX, &OpOverflow)
13490                   .convert(ResultFXSema, &ConversionOverflow);
13491     break;
13492   }
13493   case BO_Div: {
13494     if (RHSFX.getValue() == 0) {
13495       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13496       return false;
13497     }
13498     Result = LHSFX.div(RHSFX, &OpOverflow)
13499                   .convert(ResultFXSema, &ConversionOverflow);
13500     break;
13501   }
13502   case BO_Shl:
13503   case BO_Shr: {
13504     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13505     llvm::APSInt RHSVal = RHSFX.getValue();
13506 
13507     unsigned ShiftBW =
13508         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13509     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13510     // Embedded-C 4.1.6.2.2:
13511     //   The right operand must be nonnegative and less than the total number
13512     //   of (nonpadding) bits of the fixed-point operand ...
13513     if (RHSVal.isNegative())
13514       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13515     else if (Amt != RHSVal)
13516       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13517           << RHSVal << E->getType() << ShiftBW;
13518 
13519     if (E->getOpcode() == BO_Shl)
13520       Result = LHSFX.shl(Amt, &OpOverflow);
13521     else
13522       Result = LHSFX.shr(Amt, &OpOverflow);
13523     break;
13524   }
13525   default:
13526     return false;
13527   }
13528   if (OpOverflow || ConversionOverflow) {
13529     if (Info.checkingForUndefinedBehavior())
13530       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13531                                        diag::warn_fixedpoint_constant_overflow)
13532         << Result.toString() << E->getType();
13533     else if (!HandleOverflow(Info, E, Result, E->getType()))
13534       return false;
13535   }
13536   return Success(Result, E);
13537 }
13538 
13539 //===----------------------------------------------------------------------===//
13540 // Float Evaluation
13541 //===----------------------------------------------------------------------===//
13542 
13543 namespace {
13544 class FloatExprEvaluator
13545   : public ExprEvaluatorBase<FloatExprEvaluator> {
13546   APFloat &Result;
13547 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)13548   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13549     : ExprEvaluatorBaseTy(info), Result(result) {}
13550 
Success(const APValue & V,const Expr * e)13551   bool Success(const APValue &V, const Expr *e) {
13552     Result = V.getFloat();
13553     return true;
13554   }
13555 
ZeroInitialization(const Expr * E)13556   bool ZeroInitialization(const Expr *E) {
13557     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13558     return true;
13559   }
13560 
13561   bool VisitCallExpr(const CallExpr *E);
13562 
13563   bool VisitUnaryOperator(const UnaryOperator *E);
13564   bool VisitBinaryOperator(const BinaryOperator *E);
13565   bool VisitFloatingLiteral(const FloatingLiteral *E);
13566   bool VisitCastExpr(const CastExpr *E);
13567 
13568   bool VisitUnaryReal(const UnaryOperator *E);
13569   bool VisitUnaryImag(const UnaryOperator *E);
13570 
13571   // FIXME: Missing: array subscript of vector, member of vector
13572 };
13573 } // end anonymous namespace
13574 
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)13575 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13576   assert(!E->isValueDependent());
13577   assert(E->isRValue() && E->getType()->isRealFloatingType());
13578   return FloatExprEvaluator(Info, Result).Visit(E);
13579 }
13580 
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)13581 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13582                                   QualType ResultTy,
13583                                   const Expr *Arg,
13584                                   bool SNaN,
13585                                   llvm::APFloat &Result) {
13586   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13587   if (!S) return false;
13588 
13589   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13590 
13591   llvm::APInt fill;
13592 
13593   // Treat empty strings as if they were zero.
13594   if (S->getString().empty())
13595     fill = llvm::APInt(32, 0);
13596   else if (S->getString().getAsInteger(0, fill))
13597     return false;
13598 
13599   if (Context.getTargetInfo().isNan2008()) {
13600     if (SNaN)
13601       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13602     else
13603       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13604   } else {
13605     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13606     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13607     // a different encoding to what became a standard in 2008, and for pre-
13608     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13609     // sNaN. This is now known as "legacy NaN" encoding.
13610     if (SNaN)
13611       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13612     else
13613       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13614   }
13615 
13616   return true;
13617 }
13618 
VisitCallExpr(const CallExpr * E)13619 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13620   switch (E->getBuiltinCallee()) {
13621   default:
13622     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13623 
13624   case Builtin::BI__builtin_huge_val:
13625   case Builtin::BI__builtin_huge_valf:
13626   case Builtin::BI__builtin_huge_vall:
13627   case Builtin::BI__builtin_huge_valf128:
13628   case Builtin::BI__builtin_inf:
13629   case Builtin::BI__builtin_inff:
13630   case Builtin::BI__builtin_infl:
13631   case Builtin::BI__builtin_inff128: {
13632     const llvm::fltSemantics &Sem =
13633       Info.Ctx.getFloatTypeSemantics(E->getType());
13634     Result = llvm::APFloat::getInf(Sem);
13635     return true;
13636   }
13637 
13638   case Builtin::BI__builtin_nans:
13639   case Builtin::BI__builtin_nansf:
13640   case Builtin::BI__builtin_nansl:
13641   case Builtin::BI__builtin_nansf128:
13642     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13643                                true, Result))
13644       return Error(E);
13645     return true;
13646 
13647   case Builtin::BI__builtin_nan:
13648   case Builtin::BI__builtin_nanf:
13649   case Builtin::BI__builtin_nanl:
13650   case Builtin::BI__builtin_nanf128:
13651     // If this is __builtin_nan() turn this into a nan, otherwise we
13652     // can't constant fold it.
13653     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13654                                false, Result))
13655       return Error(E);
13656     return true;
13657 
13658   case Builtin::BI__builtin_fabs:
13659   case Builtin::BI__builtin_fabsf:
13660   case Builtin::BI__builtin_fabsl:
13661   case Builtin::BI__builtin_fabsf128:
13662     // The C standard says "fabs raises no floating-point exceptions,
13663     // even if x is a signaling NaN. The returned value is independent of
13664     // the current rounding direction mode."  Therefore constant folding can
13665     // proceed without regard to the floating point settings.
13666     // Reference, WG14 N2478 F.10.4.3
13667     if (!EvaluateFloat(E->getArg(0), Result, Info))
13668       return false;
13669 
13670     if (Result.isNegative())
13671       Result.changeSign();
13672     return true;
13673 
13674   // FIXME: Builtin::BI__builtin_powi
13675   // FIXME: Builtin::BI__builtin_powif
13676   // FIXME: Builtin::BI__builtin_powil
13677 
13678   case Builtin::BI__builtin_copysign:
13679   case Builtin::BI__builtin_copysignf:
13680   case Builtin::BI__builtin_copysignl:
13681   case Builtin::BI__builtin_copysignf128: {
13682     APFloat RHS(0.);
13683     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13684         !EvaluateFloat(E->getArg(1), RHS, Info))
13685       return false;
13686     Result.copySign(RHS);
13687     return true;
13688   }
13689   }
13690 }
13691 
VisitUnaryReal(const UnaryOperator * E)13692 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13693   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13694     ComplexValue CV;
13695     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13696       return false;
13697     Result = CV.FloatReal;
13698     return true;
13699   }
13700 
13701   return Visit(E->getSubExpr());
13702 }
13703 
VisitUnaryImag(const UnaryOperator * E)13704 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13705   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13706     ComplexValue CV;
13707     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13708       return false;
13709     Result = CV.FloatImag;
13710     return true;
13711   }
13712 
13713   VisitIgnoredValue(E->getSubExpr());
13714   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13715   Result = llvm::APFloat::getZero(Sem);
13716   return true;
13717 }
13718 
VisitUnaryOperator(const UnaryOperator * E)13719 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13720   switch (E->getOpcode()) {
13721   default: return Error(E);
13722   case UO_Plus:
13723     return EvaluateFloat(E->getSubExpr(), Result, Info);
13724   case UO_Minus:
13725     // In C standard, WG14 N2478 F.3 p4
13726     // "the unary - raises no floating point exceptions,
13727     // even if the operand is signalling."
13728     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13729       return false;
13730     Result.changeSign();
13731     return true;
13732   }
13733 }
13734 
VisitBinaryOperator(const BinaryOperator * E)13735 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13736   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13737     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13738 
13739   APFloat RHS(0.0);
13740   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13741   if (!LHSOK && !Info.noteFailure())
13742     return false;
13743   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13744          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13745 }
13746 
VisitFloatingLiteral(const FloatingLiteral * E)13747 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13748   Result = E->getValue();
13749   return true;
13750 }
13751 
VisitCastExpr(const CastExpr * E)13752 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13753   const Expr* SubExpr = E->getSubExpr();
13754 
13755   switch (E->getCastKind()) {
13756   default:
13757     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13758 
13759   case CK_IntegralToFloating: {
13760     APSInt IntResult;
13761     const FPOptions FPO = E->getFPFeaturesInEffect(
13762                                   Info.Ctx.getLangOpts());
13763     return EvaluateInteger(SubExpr, IntResult, Info) &&
13764            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13765                                 IntResult, E->getType(), Result);
13766   }
13767 
13768   case CK_FixedPointToFloating: {
13769     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13770     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13771       return false;
13772     Result =
13773         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13774     return true;
13775   }
13776 
13777   case CK_FloatingCast: {
13778     if (!Visit(SubExpr))
13779       return false;
13780     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13781                                   Result);
13782   }
13783 
13784   case CK_FloatingComplexToReal: {
13785     ComplexValue V;
13786     if (!EvaluateComplex(SubExpr, V, Info))
13787       return false;
13788     Result = V.getComplexFloatReal();
13789     return true;
13790   }
13791   }
13792 }
13793 
13794 //===----------------------------------------------------------------------===//
13795 // Complex Evaluation (for float and integer)
13796 //===----------------------------------------------------------------------===//
13797 
13798 namespace {
13799 class ComplexExprEvaluator
13800   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13801   ComplexValue &Result;
13802 
13803 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)13804   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13805     : ExprEvaluatorBaseTy(info), Result(Result) {}
13806 
Success(const APValue & V,const Expr * e)13807   bool Success(const APValue &V, const Expr *e) {
13808     Result.setFrom(V);
13809     return true;
13810   }
13811 
13812   bool ZeroInitialization(const Expr *E);
13813 
13814   //===--------------------------------------------------------------------===//
13815   //                            Visitor Methods
13816   //===--------------------------------------------------------------------===//
13817 
13818   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13819   bool VisitCastExpr(const CastExpr *E);
13820   bool VisitBinaryOperator(const BinaryOperator *E);
13821   bool VisitUnaryOperator(const UnaryOperator *E);
13822   bool VisitInitListExpr(const InitListExpr *E);
13823   bool VisitCallExpr(const CallExpr *E);
13824 };
13825 } // end anonymous namespace
13826 
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)13827 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13828                             EvalInfo &Info) {
13829   assert(!E->isValueDependent());
13830   assert(E->isRValue() && E->getType()->isAnyComplexType());
13831   return ComplexExprEvaluator(Info, Result).Visit(E);
13832 }
13833 
ZeroInitialization(const Expr * E)13834 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13835   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13836   if (ElemTy->isRealFloatingType()) {
13837     Result.makeComplexFloat();
13838     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13839     Result.FloatReal = Zero;
13840     Result.FloatImag = Zero;
13841   } else {
13842     Result.makeComplexInt();
13843     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13844     Result.IntReal = Zero;
13845     Result.IntImag = Zero;
13846   }
13847   return true;
13848 }
13849 
VisitImaginaryLiteral(const ImaginaryLiteral * E)13850 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13851   const Expr* SubExpr = E->getSubExpr();
13852 
13853   if (SubExpr->getType()->isRealFloatingType()) {
13854     Result.makeComplexFloat();
13855     APFloat &Imag = Result.FloatImag;
13856     if (!EvaluateFloat(SubExpr, Imag, Info))
13857       return false;
13858 
13859     Result.FloatReal = APFloat(Imag.getSemantics());
13860     return true;
13861   } else {
13862     assert(SubExpr->getType()->isIntegerType() &&
13863            "Unexpected imaginary literal.");
13864 
13865     Result.makeComplexInt();
13866     APSInt &Imag = Result.IntImag;
13867     if (!EvaluateInteger(SubExpr, Imag, Info))
13868       return false;
13869 
13870     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13871     return true;
13872   }
13873 }
13874 
VisitCastExpr(const CastExpr * E)13875 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13876 
13877   switch (E->getCastKind()) {
13878   case CK_BitCast:
13879   case CK_BaseToDerived:
13880   case CK_DerivedToBase:
13881   case CK_UncheckedDerivedToBase:
13882   case CK_Dynamic:
13883   case CK_ToUnion:
13884   case CK_ArrayToPointerDecay:
13885   case CK_FunctionToPointerDecay:
13886   case CK_NullToPointer:
13887   case CK_NullToMemberPointer:
13888   case CK_BaseToDerivedMemberPointer:
13889   case CK_DerivedToBaseMemberPointer:
13890   case CK_MemberPointerToBoolean:
13891   case CK_ReinterpretMemberPointer:
13892   case CK_ConstructorConversion:
13893   case CK_IntegralToPointer:
13894   case CK_PointerToIntegral:
13895   case CK_PointerToBoolean:
13896   case CK_ToVoid:
13897   case CK_VectorSplat:
13898   case CK_IntegralCast:
13899   case CK_BooleanToSignedIntegral:
13900   case CK_IntegralToBoolean:
13901   case CK_IntegralToFloating:
13902   case CK_FloatingToIntegral:
13903   case CK_FloatingToBoolean:
13904   case CK_FloatingCast:
13905   case CK_CPointerToObjCPointerCast:
13906   case CK_BlockPointerToObjCPointerCast:
13907   case CK_AnyPointerToBlockPointerCast:
13908   case CK_ObjCObjectLValueCast:
13909   case CK_FloatingComplexToReal:
13910   case CK_FloatingComplexToBoolean:
13911   case CK_IntegralComplexToReal:
13912   case CK_IntegralComplexToBoolean:
13913   case CK_ARCProduceObject:
13914   case CK_ARCConsumeObject:
13915   case CK_ARCReclaimReturnedObject:
13916   case CK_ARCExtendBlockObject:
13917   case CK_CopyAndAutoreleaseBlockObject:
13918   case CK_BuiltinFnToFnPtr:
13919   case CK_ZeroToOCLOpaqueType:
13920   case CK_NonAtomicToAtomic:
13921   case CK_AddressSpaceConversion:
13922   case CK_IntToOCLSampler:
13923   case CK_FloatingToFixedPoint:
13924   case CK_FixedPointToFloating:
13925   case CK_FixedPointCast:
13926   case CK_FixedPointToBoolean:
13927   case CK_FixedPointToIntegral:
13928   case CK_IntegralToFixedPoint:
13929     llvm_unreachable("invalid cast kind for complex value");
13930 
13931   case CK_LValueToRValue:
13932   case CK_AtomicToNonAtomic:
13933   case CK_NoOp:
13934   case CK_LValueToRValueBitCast:
13935     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13936 
13937   case CK_Dependent:
13938   case CK_LValueBitCast:
13939   case CK_UserDefinedConversion:
13940     return Error(E);
13941 
13942   case CK_FloatingRealToComplex: {
13943     APFloat &Real = Result.FloatReal;
13944     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13945       return false;
13946 
13947     Result.makeComplexFloat();
13948     Result.FloatImag = APFloat(Real.getSemantics());
13949     return true;
13950   }
13951 
13952   case CK_FloatingComplexCast: {
13953     if (!Visit(E->getSubExpr()))
13954       return false;
13955 
13956     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13957     QualType From
13958       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13959 
13960     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13961            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13962   }
13963 
13964   case CK_FloatingComplexToIntegralComplex: {
13965     if (!Visit(E->getSubExpr()))
13966       return false;
13967 
13968     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13969     QualType From
13970       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13971     Result.makeComplexInt();
13972     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13973                                 To, Result.IntReal) &&
13974            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13975                                 To, Result.IntImag);
13976   }
13977 
13978   case CK_IntegralRealToComplex: {
13979     APSInt &Real = Result.IntReal;
13980     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13981       return false;
13982 
13983     Result.makeComplexInt();
13984     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13985     return true;
13986   }
13987 
13988   case CK_IntegralComplexCast: {
13989     if (!Visit(E->getSubExpr()))
13990       return false;
13991 
13992     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13993     QualType From
13994       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13995 
13996     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13997     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13998     return true;
13999   }
14000 
14001   case CK_IntegralComplexToFloatingComplex: {
14002     if (!Visit(E->getSubExpr()))
14003       return false;
14004 
14005     const FPOptions FPO = E->getFPFeaturesInEffect(
14006                                   Info.Ctx.getLangOpts());
14007     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14008     QualType From
14009       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14010     Result.makeComplexFloat();
14011     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14012                                 To, Result.FloatReal) &&
14013            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14014                                 To, Result.FloatImag);
14015   }
14016   }
14017 
14018   llvm_unreachable("unknown cast resulting in complex value");
14019 }
14020 
VisitBinaryOperator(const BinaryOperator * E)14021 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14022   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14023     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14024 
14025   // Track whether the LHS or RHS is real at the type system level. When this is
14026   // the case we can simplify our evaluation strategy.
14027   bool LHSReal = false, RHSReal = false;
14028 
14029   bool LHSOK;
14030   if (E->getLHS()->getType()->isRealFloatingType()) {
14031     LHSReal = true;
14032     APFloat &Real = Result.FloatReal;
14033     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14034     if (LHSOK) {
14035       Result.makeComplexFloat();
14036       Result.FloatImag = APFloat(Real.getSemantics());
14037     }
14038   } else {
14039     LHSOK = Visit(E->getLHS());
14040   }
14041   if (!LHSOK && !Info.noteFailure())
14042     return false;
14043 
14044   ComplexValue RHS;
14045   if (E->getRHS()->getType()->isRealFloatingType()) {
14046     RHSReal = true;
14047     APFloat &Real = RHS.FloatReal;
14048     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14049       return false;
14050     RHS.makeComplexFloat();
14051     RHS.FloatImag = APFloat(Real.getSemantics());
14052   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14053     return false;
14054 
14055   assert(!(LHSReal && RHSReal) &&
14056          "Cannot have both operands of a complex operation be real.");
14057   switch (E->getOpcode()) {
14058   default: return Error(E);
14059   case BO_Add:
14060     if (Result.isComplexFloat()) {
14061       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14062                                        APFloat::rmNearestTiesToEven);
14063       if (LHSReal)
14064         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14065       else if (!RHSReal)
14066         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14067                                          APFloat::rmNearestTiesToEven);
14068     } else {
14069       Result.getComplexIntReal() += RHS.getComplexIntReal();
14070       Result.getComplexIntImag() += RHS.getComplexIntImag();
14071     }
14072     break;
14073   case BO_Sub:
14074     if (Result.isComplexFloat()) {
14075       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14076                                             APFloat::rmNearestTiesToEven);
14077       if (LHSReal) {
14078         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14079         Result.getComplexFloatImag().changeSign();
14080       } else if (!RHSReal) {
14081         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14082                                               APFloat::rmNearestTiesToEven);
14083       }
14084     } else {
14085       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14086       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14087     }
14088     break;
14089   case BO_Mul:
14090     if (Result.isComplexFloat()) {
14091       // This is an implementation of complex multiplication according to the
14092       // constraints laid out in C11 Annex G. The implementation uses the
14093       // following naming scheme:
14094       //   (a + ib) * (c + id)
14095       ComplexValue LHS = Result;
14096       APFloat &A = LHS.getComplexFloatReal();
14097       APFloat &B = LHS.getComplexFloatImag();
14098       APFloat &C = RHS.getComplexFloatReal();
14099       APFloat &D = RHS.getComplexFloatImag();
14100       APFloat &ResR = Result.getComplexFloatReal();
14101       APFloat &ResI = Result.getComplexFloatImag();
14102       if (LHSReal) {
14103         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14104         ResR = A * C;
14105         ResI = A * D;
14106       } else if (RHSReal) {
14107         ResR = C * A;
14108         ResI = C * B;
14109       } else {
14110         // In the fully general case, we need to handle NaNs and infinities
14111         // robustly.
14112         APFloat AC = A * C;
14113         APFloat BD = B * D;
14114         APFloat AD = A * D;
14115         APFloat BC = B * C;
14116         ResR = AC - BD;
14117         ResI = AD + BC;
14118         if (ResR.isNaN() && ResI.isNaN()) {
14119           bool Recalc = false;
14120           if (A.isInfinity() || B.isInfinity()) {
14121             A = APFloat::copySign(
14122                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14123             B = APFloat::copySign(
14124                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14125             if (C.isNaN())
14126               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14127             if (D.isNaN())
14128               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14129             Recalc = true;
14130           }
14131           if (C.isInfinity() || D.isInfinity()) {
14132             C = APFloat::copySign(
14133                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14134             D = APFloat::copySign(
14135                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14136             if (A.isNaN())
14137               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14138             if (B.isNaN())
14139               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14140             Recalc = true;
14141           }
14142           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14143                           AD.isInfinity() || BC.isInfinity())) {
14144             if (A.isNaN())
14145               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14146             if (B.isNaN())
14147               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14148             if (C.isNaN())
14149               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14150             if (D.isNaN())
14151               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14152             Recalc = true;
14153           }
14154           if (Recalc) {
14155             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14156             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14157           }
14158         }
14159       }
14160     } else {
14161       ComplexValue LHS = Result;
14162       Result.getComplexIntReal() =
14163         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14164          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14165       Result.getComplexIntImag() =
14166         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14167          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14168     }
14169     break;
14170   case BO_Div:
14171     if (Result.isComplexFloat()) {
14172       // This is an implementation of complex division according to the
14173       // constraints laid out in C11 Annex G. The implementation uses the
14174       // following naming scheme:
14175       //   (a + ib) / (c + id)
14176       ComplexValue LHS = Result;
14177       APFloat &A = LHS.getComplexFloatReal();
14178       APFloat &B = LHS.getComplexFloatImag();
14179       APFloat &C = RHS.getComplexFloatReal();
14180       APFloat &D = RHS.getComplexFloatImag();
14181       APFloat &ResR = Result.getComplexFloatReal();
14182       APFloat &ResI = Result.getComplexFloatImag();
14183       if (RHSReal) {
14184         ResR = A / C;
14185         ResI = B / C;
14186       } else {
14187         if (LHSReal) {
14188           // No real optimizations we can do here, stub out with zero.
14189           B = APFloat::getZero(A.getSemantics());
14190         }
14191         int DenomLogB = 0;
14192         APFloat MaxCD = maxnum(abs(C), abs(D));
14193         if (MaxCD.isFinite()) {
14194           DenomLogB = ilogb(MaxCD);
14195           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14196           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14197         }
14198         APFloat Denom = C * C + D * D;
14199         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14200                       APFloat::rmNearestTiesToEven);
14201         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14202                       APFloat::rmNearestTiesToEven);
14203         if (ResR.isNaN() && ResI.isNaN()) {
14204           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14205             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14206             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14207           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14208                      D.isFinite()) {
14209             A = APFloat::copySign(
14210                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14211             B = APFloat::copySign(
14212                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14213             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14214             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14215           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14216             C = APFloat::copySign(
14217                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14218             D = APFloat::copySign(
14219                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14220             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14221             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14222           }
14223         }
14224       }
14225     } else {
14226       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14227         return Error(E, diag::note_expr_divide_by_zero);
14228 
14229       ComplexValue LHS = Result;
14230       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14231         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14232       Result.getComplexIntReal() =
14233         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14234          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14235       Result.getComplexIntImag() =
14236         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14237          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14238     }
14239     break;
14240   }
14241 
14242   return true;
14243 }
14244 
VisitUnaryOperator(const UnaryOperator * E)14245 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14246   // Get the operand value into 'Result'.
14247   if (!Visit(E->getSubExpr()))
14248     return false;
14249 
14250   switch (E->getOpcode()) {
14251   default:
14252     return Error(E);
14253   case UO_Extension:
14254     return true;
14255   case UO_Plus:
14256     // The result is always just the subexpr.
14257     return true;
14258   case UO_Minus:
14259     if (Result.isComplexFloat()) {
14260       Result.getComplexFloatReal().changeSign();
14261       Result.getComplexFloatImag().changeSign();
14262     }
14263     else {
14264       Result.getComplexIntReal() = -Result.getComplexIntReal();
14265       Result.getComplexIntImag() = -Result.getComplexIntImag();
14266     }
14267     return true;
14268   case UO_Not:
14269     if (Result.isComplexFloat())
14270       Result.getComplexFloatImag().changeSign();
14271     else
14272       Result.getComplexIntImag() = -Result.getComplexIntImag();
14273     return true;
14274   }
14275 }
14276 
VisitInitListExpr(const InitListExpr * E)14277 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14278   if (E->getNumInits() == 2) {
14279     if (E->getType()->isComplexType()) {
14280       Result.makeComplexFloat();
14281       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14282         return false;
14283       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14284         return false;
14285     } else {
14286       Result.makeComplexInt();
14287       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14288         return false;
14289       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14290         return false;
14291     }
14292     return true;
14293   }
14294   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14295 }
14296 
VisitCallExpr(const CallExpr * E)14297 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14298   switch (E->getBuiltinCallee()) {
14299   case Builtin::BI__builtin_complex:
14300     Result.makeComplexFloat();
14301     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14302       return false;
14303     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14304       return false;
14305     return true;
14306 
14307   default:
14308     break;
14309   }
14310 
14311   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14312 }
14313 
14314 //===----------------------------------------------------------------------===//
14315 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14316 // implicit conversion.
14317 //===----------------------------------------------------------------------===//
14318 
14319 namespace {
14320 class AtomicExprEvaluator :
14321     public ExprEvaluatorBase<AtomicExprEvaluator> {
14322   const LValue *This;
14323   APValue &Result;
14324 public:
AtomicExprEvaluator(EvalInfo & Info,const LValue * This,APValue & Result)14325   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14326       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14327 
Success(const APValue & V,const Expr * E)14328   bool Success(const APValue &V, const Expr *E) {
14329     Result = V;
14330     return true;
14331   }
14332 
ZeroInitialization(const Expr * E)14333   bool ZeroInitialization(const Expr *E) {
14334     ImplicitValueInitExpr VIE(
14335         E->getType()->castAs<AtomicType>()->getValueType());
14336     // For atomic-qualified class (and array) types in C++, initialize the
14337     // _Atomic-wrapped subobject directly, in-place.
14338     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14339                 : Evaluate(Result, Info, &VIE);
14340   }
14341 
VisitCastExpr(const CastExpr * E)14342   bool VisitCastExpr(const CastExpr *E) {
14343     switch (E->getCastKind()) {
14344     default:
14345       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14346     case CK_NonAtomicToAtomic:
14347       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14348                   : Evaluate(Result, Info, E->getSubExpr());
14349     }
14350   }
14351 };
14352 } // end anonymous namespace
14353 
EvaluateAtomic(const Expr * E,const LValue * This,APValue & Result,EvalInfo & Info)14354 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14355                            EvalInfo &Info) {
14356   assert(!E->isValueDependent());
14357   assert(E->isRValue() && E->getType()->isAtomicType());
14358   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14359 }
14360 
14361 //===----------------------------------------------------------------------===//
14362 // Void expression evaluation, primarily for a cast to void on the LHS of a
14363 // comma operator
14364 //===----------------------------------------------------------------------===//
14365 
14366 namespace {
14367 class VoidExprEvaluator
14368   : public ExprEvaluatorBase<VoidExprEvaluator> {
14369 public:
VoidExprEvaluator(EvalInfo & Info)14370   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14371 
Success(const APValue & V,const Expr * e)14372   bool Success(const APValue &V, const Expr *e) { return true; }
14373 
ZeroInitialization(const Expr * E)14374   bool ZeroInitialization(const Expr *E) { return true; }
14375 
VisitCastExpr(const CastExpr * E)14376   bool VisitCastExpr(const CastExpr *E) {
14377     switch (E->getCastKind()) {
14378     default:
14379       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14380     case CK_ToVoid:
14381       VisitIgnoredValue(E->getSubExpr());
14382       return true;
14383     }
14384   }
14385 
VisitCallExpr(const CallExpr * E)14386   bool VisitCallExpr(const CallExpr *E) {
14387     switch (E->getBuiltinCallee()) {
14388     case Builtin::BI__assume:
14389     case Builtin::BI__builtin_assume:
14390       // The argument is not evaluated!
14391       return true;
14392 
14393     case Builtin::BI__builtin_operator_delete:
14394       return HandleOperatorDeleteCall(Info, E);
14395 
14396     default:
14397       break;
14398     }
14399 
14400     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14401   }
14402 
14403   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14404 };
14405 } // end anonymous namespace
14406 
VisitCXXDeleteExpr(const CXXDeleteExpr * E)14407 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14408   // We cannot speculatively evaluate a delete expression.
14409   if (Info.SpeculativeEvaluationDepth)
14410     return false;
14411 
14412   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14413   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14414     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14415         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14416     return false;
14417   }
14418 
14419   const Expr *Arg = E->getArgument();
14420 
14421   LValue Pointer;
14422   if (!EvaluatePointer(Arg, Pointer, Info))
14423     return false;
14424   if (Pointer.Designator.Invalid)
14425     return false;
14426 
14427   // Deleting a null pointer has no effect.
14428   if (Pointer.isNullPointer()) {
14429     // This is the only case where we need to produce an extension warning:
14430     // the only other way we can succeed is if we find a dynamic allocation,
14431     // and we will have warned when we allocated it in that case.
14432     if (!Info.getLangOpts().CPlusPlus20)
14433       Info.CCEDiag(E, diag::note_constexpr_new);
14434     return true;
14435   }
14436 
14437   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14438       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14439   if (!Alloc)
14440     return false;
14441   QualType AllocType = Pointer.Base.getDynamicAllocType();
14442 
14443   // For the non-array case, the designator must be empty if the static type
14444   // does not have a virtual destructor.
14445   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14446       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14447     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14448         << Arg->getType()->getPointeeType() << AllocType;
14449     return false;
14450   }
14451 
14452   // For a class type with a virtual destructor, the selected operator delete
14453   // is the one looked up when building the destructor.
14454   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14455     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14456     if (VirtualDelete &&
14457         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14458       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14459           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14460       return false;
14461     }
14462   }
14463 
14464   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14465                          (*Alloc)->Value, AllocType))
14466     return false;
14467 
14468   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14469     // The element was already erased. This means the destructor call also
14470     // deleted the object.
14471     // FIXME: This probably results in undefined behavior before we get this
14472     // far, and should be diagnosed elsewhere first.
14473     Info.FFDiag(E, diag::note_constexpr_double_delete);
14474     return false;
14475   }
14476 
14477   return true;
14478 }
14479 
EvaluateVoid(const Expr * E,EvalInfo & Info)14480 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14481   assert(!E->isValueDependent());
14482   assert(E->isRValue() && E->getType()->isVoidType());
14483   return VoidExprEvaluator(Info).Visit(E);
14484 }
14485 
14486 //===----------------------------------------------------------------------===//
14487 // Top level Expr::EvaluateAsRValue method.
14488 //===----------------------------------------------------------------------===//
14489 
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)14490 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14491   assert(!E->isValueDependent());
14492   // In C, function designators are not lvalues, but we evaluate them as if they
14493   // are.
14494   QualType T = E->getType();
14495   if (E->isGLValue() || T->isFunctionType()) {
14496     LValue LV;
14497     if (!EvaluateLValue(E, LV, Info))
14498       return false;
14499     LV.moveInto(Result);
14500   } else if (T->isVectorType()) {
14501     if (!EvaluateVector(E, Result, Info))
14502       return false;
14503   } else if (T->isIntegralOrEnumerationType()) {
14504     if (!IntExprEvaluator(Info, Result).Visit(E))
14505       return false;
14506   } else if (T->hasPointerRepresentation()) {
14507     LValue LV;
14508     if (!EvaluatePointer(E, LV, Info))
14509       return false;
14510     LV.moveInto(Result);
14511   } else if (T->isRealFloatingType()) {
14512     llvm::APFloat F(0.0);
14513     if (!EvaluateFloat(E, F, Info))
14514       return false;
14515     Result = APValue(F);
14516   } else if (T->isAnyComplexType()) {
14517     ComplexValue C;
14518     if (!EvaluateComplex(E, C, Info))
14519       return false;
14520     C.moveInto(Result);
14521   } else if (T->isFixedPointType()) {
14522     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14523   } else if (T->isMemberPointerType()) {
14524     MemberPtr P;
14525     if (!EvaluateMemberPointer(E, P, Info))
14526       return false;
14527     P.moveInto(Result);
14528     return true;
14529   } else if (T->isArrayType()) {
14530     LValue LV;
14531     APValue &Value =
14532         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14533     if (!EvaluateArray(E, LV, Value, Info))
14534       return false;
14535     Result = Value;
14536   } else if (T->isRecordType()) {
14537     LValue LV;
14538     APValue &Value =
14539         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14540     if (!EvaluateRecord(E, LV, Value, Info))
14541       return false;
14542     Result = Value;
14543   } else if (T->isVoidType()) {
14544     if (!Info.getLangOpts().CPlusPlus11)
14545       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14546         << E->getType();
14547     if (!EvaluateVoid(E, Info))
14548       return false;
14549   } else if (T->isAtomicType()) {
14550     QualType Unqual = T.getAtomicUnqualifiedType();
14551     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14552       LValue LV;
14553       APValue &Value = Info.CurrentCall->createTemporary(
14554           E, Unqual, ScopeKind::FullExpression, LV);
14555       if (!EvaluateAtomic(E, &LV, Value, Info))
14556         return false;
14557     } else {
14558       if (!EvaluateAtomic(E, nullptr, Result, Info))
14559         return false;
14560     }
14561   } else if (Info.getLangOpts().CPlusPlus11) {
14562     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14563     return false;
14564   } else {
14565     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14566     return false;
14567   }
14568 
14569   return true;
14570 }
14571 
14572 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14573 /// cases, the in-place evaluation is essential, since later initializers for
14574 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,bool AllowNonLiteralTypes)14575 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14576                             const Expr *E, bool AllowNonLiteralTypes) {
14577   assert(!E->isValueDependent());
14578 
14579   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14580     return false;
14581 
14582   if (E->isRValue()) {
14583     // Evaluate arrays and record types in-place, so that later initializers can
14584     // refer to earlier-initialized members of the object.
14585     QualType T = E->getType();
14586     if (T->isArrayType())
14587       return EvaluateArray(E, This, Result, Info);
14588     else if (T->isRecordType())
14589       return EvaluateRecord(E, This, Result, Info);
14590     else if (T->isAtomicType()) {
14591       QualType Unqual = T.getAtomicUnqualifiedType();
14592       if (Unqual->isArrayType() || Unqual->isRecordType())
14593         return EvaluateAtomic(E, &This, Result, Info);
14594     }
14595   }
14596 
14597   // For any other type, in-place evaluation is unimportant.
14598   return Evaluate(Result, Info, E);
14599 }
14600 
14601 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14602 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)14603 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14604   assert(!E->isValueDependent());
14605   if (Info.EnableNewConstInterp) {
14606     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14607       return false;
14608   } else {
14609     if (E->getType().isNull())
14610       return false;
14611 
14612     if (!CheckLiteralType(Info, E))
14613       return false;
14614 
14615     if (!::Evaluate(Result, Info, E))
14616       return false;
14617 
14618     if (E->isGLValue()) {
14619       LValue LV;
14620       LV.setFrom(Info.Ctx, Result);
14621       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14622         return false;
14623     }
14624   }
14625 
14626   // Check this core constant expression is a constant expression.
14627   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14628                                  ConstantExprKind::Normal) &&
14629          CheckMemoryLeaks(Info);
14630 }
14631 
FastEvaluateAsRValue(const Expr * Exp,Expr::EvalResult & Result,const ASTContext & Ctx,bool & IsConst)14632 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14633                                  const ASTContext &Ctx, bool &IsConst) {
14634   // Fast-path evaluations of integer literals, since we sometimes see files
14635   // containing vast quantities of these.
14636   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14637     Result.Val = APValue(APSInt(L->getValue(),
14638                                 L->getType()->isUnsignedIntegerType()));
14639     IsConst = true;
14640     return true;
14641   }
14642 
14643   // This case should be rare, but we need to check it before we check on
14644   // the type below.
14645   if (Exp->getType().isNull()) {
14646     IsConst = false;
14647     return true;
14648   }
14649 
14650   // FIXME: Evaluating values of large array and record types can cause
14651   // performance problems. Only do so in C++11 for now.
14652   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14653                           Exp->getType()->isRecordType()) &&
14654       !Ctx.getLangOpts().CPlusPlus11) {
14655     IsConst = false;
14656     return true;
14657   }
14658   return false;
14659 }
14660 
hasUnacceptableSideEffect(Expr::EvalStatus & Result,Expr::SideEffectsKind SEK)14661 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14662                                       Expr::SideEffectsKind SEK) {
14663   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14664          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14665 }
14666 
EvaluateAsRValue(const Expr * E,Expr::EvalResult & Result,const ASTContext & Ctx,EvalInfo & Info)14667 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14668                              const ASTContext &Ctx, EvalInfo &Info) {
14669   assert(!E->isValueDependent());
14670   bool IsConst;
14671   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14672     return IsConst;
14673 
14674   return EvaluateAsRValue(Info, E, Result.Val);
14675 }
14676 
EvaluateAsInt(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14677 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14678                           const ASTContext &Ctx,
14679                           Expr::SideEffectsKind AllowSideEffects,
14680                           EvalInfo &Info) {
14681   assert(!E->isValueDependent());
14682   if (!E->getType()->isIntegralOrEnumerationType())
14683     return false;
14684 
14685   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14686       !ExprResult.Val.isInt() ||
14687       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14688     return false;
14689 
14690   return true;
14691 }
14692 
EvaluateAsFixedPoint(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14693 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14694                                  const ASTContext &Ctx,
14695                                  Expr::SideEffectsKind AllowSideEffects,
14696                                  EvalInfo &Info) {
14697   assert(!E->isValueDependent());
14698   if (!E->getType()->isFixedPointType())
14699     return false;
14700 
14701   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14702     return false;
14703 
14704   if (!ExprResult.Val.isFixedPoint() ||
14705       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14706     return false;
14707 
14708   return true;
14709 }
14710 
14711 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14712 /// any crazy technique (that has nothing to do with language standards) that
14713 /// we want to.  If this function returns true, it returns the folded constant
14714 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14715 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const14716 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14717                             bool InConstantContext) const {
14718   assert(!isValueDependent() &&
14719          "Expression evaluator can't be called on a dependent expression.");
14720   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14721   Info.InConstantContext = InConstantContext;
14722   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14723 }
14724 
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx,bool InConstantContext) const14725 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14726                                       bool InConstantContext) const {
14727   assert(!isValueDependent() &&
14728          "Expression evaluator can't be called on a dependent expression.");
14729   EvalResult Scratch;
14730   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14731          HandleConversionToBool(Scratch.Val, Result);
14732 }
14733 
EvaluateAsInt(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14734 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14735                          SideEffectsKind AllowSideEffects,
14736                          bool InConstantContext) const {
14737   assert(!isValueDependent() &&
14738          "Expression evaluator can't be called on a dependent expression.");
14739   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14740   Info.InConstantContext = InConstantContext;
14741   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14742 }
14743 
EvaluateAsFixedPoint(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14744 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14745                                 SideEffectsKind AllowSideEffects,
14746                                 bool InConstantContext) const {
14747   assert(!isValueDependent() &&
14748          "Expression evaluator can't be called on a dependent expression.");
14749   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14750   Info.InConstantContext = InConstantContext;
14751   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14752 }
14753 
EvaluateAsFloat(APFloat & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14754 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14755                            SideEffectsKind AllowSideEffects,
14756                            bool InConstantContext) const {
14757   assert(!isValueDependent() &&
14758          "Expression evaluator can't be called on a dependent expression.");
14759 
14760   if (!getType()->isRealFloatingType())
14761     return false;
14762 
14763   EvalResult ExprResult;
14764   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14765       !ExprResult.Val.isFloat() ||
14766       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14767     return false;
14768 
14769   Result = ExprResult.Val.getFloat();
14770   return true;
14771 }
14772 
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const14773 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14774                             bool InConstantContext) const {
14775   assert(!isValueDependent() &&
14776          "Expression evaluator can't be called on a dependent expression.");
14777 
14778   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14779   Info.InConstantContext = InConstantContext;
14780   LValue LV;
14781   CheckedTemporaries CheckedTemps;
14782   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14783       Result.HasSideEffects ||
14784       !CheckLValueConstantExpression(Info, getExprLoc(),
14785                                      Ctx.getLValueReferenceType(getType()), LV,
14786                                      ConstantExprKind::Normal, CheckedTemps))
14787     return false;
14788 
14789   LV.moveInto(Result.Val);
14790   return true;
14791 }
14792 
EvaluateDestruction(const ASTContext & Ctx,APValue::LValueBase Base,APValue DestroyedValue,QualType Type,SourceLocation Loc,Expr::EvalStatus & EStatus,bool IsConstantDestruction)14793 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14794                                 APValue DestroyedValue, QualType Type,
14795                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14796                                 bool IsConstantDestruction) {
14797   EvalInfo Info(Ctx, EStatus,
14798                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14799                                       : EvalInfo::EM_ConstantFold);
14800   Info.setEvaluatingDecl(Base, DestroyedValue,
14801                          EvalInfo::EvaluatingDeclKind::Dtor);
14802   Info.InConstantContext = IsConstantDestruction;
14803 
14804   LValue LVal;
14805   LVal.set(Base);
14806 
14807   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14808       EStatus.HasSideEffects)
14809     return false;
14810 
14811   if (!Info.discardCleanups())
14812     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14813 
14814   return true;
14815 }
14816 
EvaluateAsConstantExpr(EvalResult & Result,const ASTContext & Ctx,ConstantExprKind Kind) const14817 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14818                                   ConstantExprKind Kind) const {
14819   assert(!isValueDependent() &&
14820          "Expression evaluator can't be called on a dependent expression.");
14821 
14822   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14823   EvalInfo Info(Ctx, Result, EM);
14824   Info.InConstantContext = true;
14825 
14826   // The type of the object we're initializing is 'const T' for a class NTTP.
14827   QualType T = getType();
14828   if (Kind == ConstantExprKind::ClassTemplateArgument)
14829     T.addConst();
14830 
14831   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14832   // represent the result of the evaluation. CheckConstantExpression ensures
14833   // this doesn't escape.
14834   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14835   APValue::LValueBase Base(&BaseMTE);
14836 
14837   Info.setEvaluatingDecl(Base, Result.Val);
14838   LValue LVal;
14839   LVal.set(Base);
14840 
14841   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14842     return false;
14843 
14844   if (!Info.discardCleanups())
14845     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14846 
14847   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14848                                Result.Val, Kind))
14849     return false;
14850   if (!CheckMemoryLeaks(Info))
14851     return false;
14852 
14853   // If this is a class template argument, it's required to have constant
14854   // destruction too.
14855   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14856       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14857                             true) ||
14858        Result.HasSideEffects)) {
14859     // FIXME: Prefix a note to indicate that the problem is lack of constant
14860     // destruction.
14861     return false;
14862   }
14863 
14864   return true;
14865 }
14866 
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const14867 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14868                                  const VarDecl *VD,
14869                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14870                                  bool IsConstantInitialization) const {
14871   assert(!isValueDependent() &&
14872          "Expression evaluator can't be called on a dependent expression.");
14873 
14874   // FIXME: Evaluating initializers for large array and record types can cause
14875   // performance problems. Only do so in C++11 for now.
14876   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14877       !Ctx.getLangOpts().CPlusPlus11)
14878     return false;
14879 
14880   Expr::EvalStatus EStatus;
14881   EStatus.Diag = &Notes;
14882 
14883   EvalInfo Info(Ctx, EStatus,
14884                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14885                     ? EvalInfo::EM_ConstantExpression
14886                     : EvalInfo::EM_ConstantFold);
14887   Info.setEvaluatingDecl(VD, Value);
14888   Info.InConstantContext = IsConstantInitialization;
14889 
14890   SourceLocation DeclLoc = VD->getLocation();
14891   QualType DeclTy = VD->getType();
14892 
14893   if (Info.EnableNewConstInterp) {
14894     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14895     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14896       return false;
14897   } else {
14898     LValue LVal;
14899     LVal.set(VD);
14900 
14901     if (!EvaluateInPlace(Value, Info, LVal, this,
14902                          /*AllowNonLiteralTypes=*/true) ||
14903         EStatus.HasSideEffects)
14904       return false;
14905 
14906     // At this point, any lifetime-extended temporaries are completely
14907     // initialized.
14908     Info.performLifetimeExtension();
14909 
14910     if (!Info.discardCleanups())
14911       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14912   }
14913   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14914                                  ConstantExprKind::Normal) &&
14915          CheckMemoryLeaks(Info);
14916 }
14917 
evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> & Notes) const14918 bool VarDecl::evaluateDestruction(
14919     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14920   Expr::EvalStatus EStatus;
14921   EStatus.Diag = &Notes;
14922 
14923   // Only treat the destruction as constant destruction if we formally have
14924   // constant initialization (or are usable in a constant expression).
14925   bool IsConstantDestruction = hasConstantInitialization();
14926 
14927   // Make a copy of the value for the destructor to mutate, if we know it.
14928   // Otherwise, treat the value as default-initialized; if the destructor works
14929   // anyway, then the destruction is constant (and must be essentially empty).
14930   APValue DestroyedValue;
14931   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14932     DestroyedValue = *getEvaluatedValue();
14933   else if (!getDefaultInitValue(getType(), DestroyedValue))
14934     return false;
14935 
14936   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14937                            getType(), getLocation(), EStatus,
14938                            IsConstantDestruction) ||
14939       EStatus.HasSideEffects)
14940     return false;
14941 
14942   ensureEvaluatedStmt()->HasConstantDestruction = true;
14943   return true;
14944 }
14945 
14946 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14947 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx,SideEffectsKind SEK) const14948 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14949   assert(!isValueDependent() &&
14950          "Expression evaluator can't be called on a dependent expression.");
14951 
14952   EvalResult Result;
14953   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14954          !hasUnacceptableSideEffect(Result, SEK);
14955 }
14956 
EvaluateKnownConstInt(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const14957 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14958                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14959   assert(!isValueDependent() &&
14960          "Expression evaluator can't be called on a dependent expression.");
14961 
14962   EvalResult EVResult;
14963   EVResult.Diag = Diag;
14964   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14965   Info.InConstantContext = true;
14966 
14967   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14968   (void)Result;
14969   assert(Result && "Could not evaluate expression");
14970   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14971 
14972   return EVResult.Val.getInt();
14973 }
14974 
EvaluateKnownConstIntCheckOverflow(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const14975 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14976     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14977   assert(!isValueDependent() &&
14978          "Expression evaluator can't be called on a dependent expression.");
14979 
14980   EvalResult EVResult;
14981   EVResult.Diag = Diag;
14982   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14983   Info.InConstantContext = true;
14984   Info.CheckingForUndefinedBehavior = true;
14985 
14986   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14987   (void)Result;
14988   assert(Result && "Could not evaluate expression");
14989   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14990 
14991   return EVResult.Val.getInt();
14992 }
14993 
EvaluateForOverflow(const ASTContext & Ctx) const14994 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14995   assert(!isValueDependent() &&
14996          "Expression evaluator can't be called on a dependent expression.");
14997 
14998   bool IsConst;
14999   EvalResult EVResult;
15000   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15001     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15002     Info.CheckingForUndefinedBehavior = true;
15003     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15004   }
15005 }
15006 
isGlobalLValue() const15007 bool Expr::EvalResult::isGlobalLValue() const {
15008   assert(Val.isLValue());
15009   return IsGlobalLValue(Val.getLValueBase());
15010 }
15011 
15012 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15013 /// an integer constant expression.
15014 
15015 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15016 /// comma, etc
15017 
15018 // CheckICE - This function does the fundamental ICE checking: the returned
15019 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15020 // and a (possibly null) SourceLocation indicating the location of the problem.
15021 //
15022 // Note that to reduce code duplication, this helper does no evaluation
15023 // itself; the caller checks whether the expression is evaluatable, and
15024 // in the rare cases where CheckICE actually cares about the evaluated
15025 // value, it calls into Evaluate.
15026 
15027 namespace {
15028 
15029 enum ICEKind {
15030   /// This expression is an ICE.
15031   IK_ICE,
15032   /// This expression is not an ICE, but if it isn't evaluated, it's
15033   /// a legal subexpression for an ICE. This return value is used to handle
15034   /// the comma operator in C99 mode, and non-constant subexpressions.
15035   IK_ICEIfUnevaluated,
15036   /// This expression is not an ICE, and is not a legal subexpression for one.
15037   IK_NotICE
15038 };
15039 
15040 struct ICEDiag {
15041   ICEKind Kind;
15042   SourceLocation Loc;
15043 
ICEDiag__anone93968c63511::ICEDiag15044   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15045 };
15046 
15047 }
15048 
NoDiag()15049 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15050 
Worst(ICEDiag A,ICEDiag B)15051 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15052 
CheckEvalInICE(const Expr * E,const ASTContext & Ctx)15053 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15054   Expr::EvalResult EVResult;
15055   Expr::EvalStatus Status;
15056   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15057 
15058   Info.InConstantContext = true;
15059   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15060       !EVResult.Val.isInt())
15061     return ICEDiag(IK_NotICE, E->getBeginLoc());
15062 
15063   return NoDiag();
15064 }
15065 
CheckICE(const Expr * E,const ASTContext & Ctx)15066 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15067   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15068   if (!E->getType()->isIntegralOrEnumerationType())
15069     return ICEDiag(IK_NotICE, E->getBeginLoc());
15070 
15071   switch (E->getStmtClass()) {
15072 #define ABSTRACT_STMT(Node)
15073 #define STMT(Node, Base) case Expr::Node##Class:
15074 #define EXPR(Node, Base)
15075 #include "clang/AST/StmtNodes.inc"
15076   case Expr::PredefinedExprClass:
15077   case Expr::FloatingLiteralClass:
15078   case Expr::ImaginaryLiteralClass:
15079   case Expr::StringLiteralClass:
15080   case Expr::ArraySubscriptExprClass:
15081   case Expr::MatrixSubscriptExprClass:
15082   case Expr::OMPArraySectionExprClass:
15083   case Expr::OMPArrayShapingExprClass:
15084   case Expr::OMPIteratorExprClass:
15085   case Expr::MemberExprClass:
15086   case Expr::CompoundAssignOperatorClass:
15087   case Expr::CompoundLiteralExprClass:
15088   case Expr::ExtVectorElementExprClass:
15089   case Expr::DesignatedInitExprClass:
15090   case Expr::ArrayInitLoopExprClass:
15091   case Expr::ArrayInitIndexExprClass:
15092   case Expr::NoInitExprClass:
15093   case Expr::DesignatedInitUpdateExprClass:
15094   case Expr::ImplicitValueInitExprClass:
15095   case Expr::ParenListExprClass:
15096   case Expr::VAArgExprClass:
15097   case Expr::AddrLabelExprClass:
15098   case Expr::StmtExprClass:
15099   case Expr::CXXMemberCallExprClass:
15100   case Expr::CUDAKernelCallExprClass:
15101   case Expr::CXXAddrspaceCastExprClass:
15102   case Expr::CXXDynamicCastExprClass:
15103   case Expr::CXXTypeidExprClass:
15104   case Expr::CXXUuidofExprClass:
15105   case Expr::MSPropertyRefExprClass:
15106   case Expr::MSPropertySubscriptExprClass:
15107   case Expr::CXXNullPtrLiteralExprClass:
15108   case Expr::UserDefinedLiteralClass:
15109   case Expr::CXXThisExprClass:
15110   case Expr::CXXThrowExprClass:
15111   case Expr::CXXNewExprClass:
15112   case Expr::CXXDeleteExprClass:
15113   case Expr::CXXPseudoDestructorExprClass:
15114   case Expr::UnresolvedLookupExprClass:
15115   case Expr::TypoExprClass:
15116   case Expr::RecoveryExprClass:
15117   case Expr::DependentScopeDeclRefExprClass:
15118   case Expr::CXXConstructExprClass:
15119   case Expr::CXXInheritedCtorInitExprClass:
15120   case Expr::CXXStdInitializerListExprClass:
15121   case Expr::CXXBindTemporaryExprClass:
15122   case Expr::ExprWithCleanupsClass:
15123   case Expr::CXXTemporaryObjectExprClass:
15124   case Expr::CXXUnresolvedConstructExprClass:
15125   case Expr::CXXDependentScopeMemberExprClass:
15126   case Expr::UnresolvedMemberExprClass:
15127   case Expr::ObjCStringLiteralClass:
15128   case Expr::ObjCBoxedExprClass:
15129   case Expr::ObjCArrayLiteralClass:
15130   case Expr::ObjCDictionaryLiteralClass:
15131   case Expr::ObjCEncodeExprClass:
15132   case Expr::ObjCMessageExprClass:
15133   case Expr::ObjCSelectorExprClass:
15134   case Expr::ObjCProtocolExprClass:
15135   case Expr::ObjCIvarRefExprClass:
15136   case Expr::ObjCPropertyRefExprClass:
15137   case Expr::ObjCSubscriptRefExprClass:
15138   case Expr::ObjCIsaExprClass:
15139   case Expr::ObjCAvailabilityCheckExprClass:
15140   case Expr::ShuffleVectorExprClass:
15141   case Expr::ConvertVectorExprClass:
15142   case Expr::BlockExprClass:
15143   case Expr::NoStmtClass:
15144   case Expr::OpaqueValueExprClass:
15145   case Expr::PackExpansionExprClass:
15146   case Expr::SubstNonTypeTemplateParmPackExprClass:
15147   case Expr::FunctionParmPackExprClass:
15148   case Expr::AsTypeExprClass:
15149   case Expr::ObjCIndirectCopyRestoreExprClass:
15150   case Expr::MaterializeTemporaryExprClass:
15151   case Expr::PseudoObjectExprClass:
15152   case Expr::AtomicExprClass:
15153   case Expr::LambdaExprClass:
15154   case Expr::CXXFoldExprClass:
15155   case Expr::CoawaitExprClass:
15156   case Expr::DependentCoawaitExprClass:
15157   case Expr::CoyieldExprClass:
15158     return ICEDiag(IK_NotICE, E->getBeginLoc());
15159 
15160   case Expr::InitListExprClass: {
15161     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15162     // form "T x = { a };" is equivalent to "T x = a;".
15163     // Unless we're initializing a reference, T is a scalar as it is known to be
15164     // of integral or enumeration type.
15165     if (E->isRValue())
15166       if (cast<InitListExpr>(E)->getNumInits() == 1)
15167         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15168     return ICEDiag(IK_NotICE, E->getBeginLoc());
15169   }
15170 
15171   case Expr::SizeOfPackExprClass:
15172   case Expr::GNUNullExprClass:
15173   case Expr::SourceLocExprClass:
15174     return NoDiag();
15175 
15176   case Expr::SubstNonTypeTemplateParmExprClass:
15177     return
15178       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15179 
15180   case Expr::ConstantExprClass:
15181     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15182 
15183   case Expr::ParenExprClass:
15184     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15185   case Expr::GenericSelectionExprClass:
15186     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15187   case Expr::IntegerLiteralClass:
15188   case Expr::FixedPointLiteralClass:
15189   case Expr::CharacterLiteralClass:
15190   case Expr::ObjCBoolLiteralExprClass:
15191   case Expr::CXXBoolLiteralExprClass:
15192   case Expr::CXXScalarValueInitExprClass:
15193   case Expr::TypeTraitExprClass:
15194   case Expr::ConceptSpecializationExprClass:
15195   case Expr::RequiresExprClass:
15196   case Expr::ArrayTypeTraitExprClass:
15197   case Expr::ExpressionTraitExprClass:
15198   case Expr::CXXNoexceptExprClass:
15199     return NoDiag();
15200   case Expr::CallExprClass:
15201   case Expr::CXXOperatorCallExprClass: {
15202     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15203     // constant expressions, but they can never be ICEs because an ICE cannot
15204     // contain an operand of (pointer to) function type.
15205     const CallExpr *CE = cast<CallExpr>(E);
15206     if (CE->getBuiltinCallee())
15207       return CheckEvalInICE(E, Ctx);
15208     return ICEDiag(IK_NotICE, E->getBeginLoc());
15209   }
15210   case Expr::CXXRewrittenBinaryOperatorClass:
15211     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15212                     Ctx);
15213   case Expr::DeclRefExprClass: {
15214     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15215     if (isa<EnumConstantDecl>(D))
15216       return NoDiag();
15217 
15218     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15219     // integer variables in constant expressions:
15220     //
15221     // C++ 7.1.5.1p2
15222     //   A variable of non-volatile const-qualified integral or enumeration
15223     //   type initialized by an ICE can be used in ICEs.
15224     //
15225     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15226     // that mode, use of reference variables should not be allowed.
15227     const VarDecl *VD = dyn_cast<VarDecl>(D);
15228     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15229         !VD->getType()->isReferenceType())
15230       return NoDiag();
15231 
15232     return ICEDiag(IK_NotICE, E->getBeginLoc());
15233   }
15234   case Expr::UnaryOperatorClass: {
15235     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15236     switch (Exp->getOpcode()) {
15237     case UO_PostInc:
15238     case UO_PostDec:
15239     case UO_PreInc:
15240     case UO_PreDec:
15241     case UO_AddrOf:
15242     case UO_Deref:
15243     case UO_Coawait:
15244       // C99 6.6/3 allows increment and decrement within unevaluated
15245       // subexpressions of constant expressions, but they can never be ICEs
15246       // because an ICE cannot contain an lvalue operand.
15247       return ICEDiag(IK_NotICE, E->getBeginLoc());
15248     case UO_Extension:
15249     case UO_LNot:
15250     case UO_Plus:
15251     case UO_Minus:
15252     case UO_Not:
15253     case UO_Real:
15254     case UO_Imag:
15255       return CheckICE(Exp->getSubExpr(), Ctx);
15256     }
15257     llvm_unreachable("invalid unary operator class");
15258   }
15259   case Expr::OffsetOfExprClass: {
15260     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15261     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15262     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15263     // compliance: we should warn earlier for offsetof expressions with
15264     // array subscripts that aren't ICEs, and if the array subscripts
15265     // are ICEs, the value of the offsetof must be an integer constant.
15266     return CheckEvalInICE(E, Ctx);
15267   }
15268   case Expr::UnaryExprOrTypeTraitExprClass: {
15269     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15270     if ((Exp->getKind() ==  UETT_SizeOf) &&
15271         Exp->getTypeOfArgument()->isVariableArrayType())
15272       return ICEDiag(IK_NotICE, E->getBeginLoc());
15273     return NoDiag();
15274   }
15275   case Expr::BinaryOperatorClass: {
15276     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15277     switch (Exp->getOpcode()) {
15278     case BO_PtrMemD:
15279     case BO_PtrMemI:
15280     case BO_Assign:
15281     case BO_MulAssign:
15282     case BO_DivAssign:
15283     case BO_RemAssign:
15284     case BO_AddAssign:
15285     case BO_SubAssign:
15286     case BO_ShlAssign:
15287     case BO_ShrAssign:
15288     case BO_AndAssign:
15289     case BO_XorAssign:
15290     case BO_OrAssign:
15291       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15292       // constant expressions, but they can never be ICEs because an ICE cannot
15293       // contain an lvalue operand.
15294       return ICEDiag(IK_NotICE, E->getBeginLoc());
15295 
15296     case BO_Mul:
15297     case BO_Div:
15298     case BO_Rem:
15299     case BO_Add:
15300     case BO_Sub:
15301     case BO_Shl:
15302     case BO_Shr:
15303     case BO_LT:
15304     case BO_GT:
15305     case BO_LE:
15306     case BO_GE:
15307     case BO_EQ:
15308     case BO_NE:
15309     case BO_And:
15310     case BO_Xor:
15311     case BO_Or:
15312     case BO_Comma:
15313     case BO_Cmp: {
15314       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15315       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15316       if (Exp->getOpcode() == BO_Div ||
15317           Exp->getOpcode() == BO_Rem) {
15318         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15319         // we don't evaluate one.
15320         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15321           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15322           if (REval == 0)
15323             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15324           if (REval.isSigned() && REval.isAllOnesValue()) {
15325             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15326             if (LEval.isMinSignedValue())
15327               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15328           }
15329         }
15330       }
15331       if (Exp->getOpcode() == BO_Comma) {
15332         if (Ctx.getLangOpts().C99) {
15333           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15334           // if it isn't evaluated.
15335           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15336             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15337         } else {
15338           // In both C89 and C++, commas in ICEs are illegal.
15339           return ICEDiag(IK_NotICE, E->getBeginLoc());
15340         }
15341       }
15342       return Worst(LHSResult, RHSResult);
15343     }
15344     case BO_LAnd:
15345     case BO_LOr: {
15346       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15347       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15348       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15349         // Rare case where the RHS has a comma "side-effect"; we need
15350         // to actually check the condition to see whether the side
15351         // with the comma is evaluated.
15352         if ((Exp->getOpcode() == BO_LAnd) !=
15353             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15354           return RHSResult;
15355         return NoDiag();
15356       }
15357 
15358       return Worst(LHSResult, RHSResult);
15359     }
15360     }
15361     llvm_unreachable("invalid binary operator kind");
15362   }
15363   case Expr::ImplicitCastExprClass:
15364   case Expr::CStyleCastExprClass:
15365   case Expr::CXXFunctionalCastExprClass:
15366   case Expr::CXXStaticCastExprClass:
15367   case Expr::CXXReinterpretCastExprClass:
15368   case Expr::CXXConstCastExprClass:
15369   case Expr::ObjCBridgedCastExprClass: {
15370     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15371     if (isa<ExplicitCastExpr>(E)) {
15372       if (const FloatingLiteral *FL
15373             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15374         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15375         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15376         APSInt IgnoredVal(DestWidth, !DestSigned);
15377         bool Ignored;
15378         // If the value does not fit in the destination type, the behavior is
15379         // undefined, so we are not required to treat it as a constant
15380         // expression.
15381         if (FL->getValue().convertToInteger(IgnoredVal,
15382                                             llvm::APFloat::rmTowardZero,
15383                                             &Ignored) & APFloat::opInvalidOp)
15384           return ICEDiag(IK_NotICE, E->getBeginLoc());
15385         return NoDiag();
15386       }
15387     }
15388     switch (cast<CastExpr>(E)->getCastKind()) {
15389     case CK_LValueToRValue:
15390     case CK_AtomicToNonAtomic:
15391     case CK_NonAtomicToAtomic:
15392     case CK_NoOp:
15393     case CK_IntegralToBoolean:
15394     case CK_IntegralCast:
15395       return CheckICE(SubExpr, Ctx);
15396     default:
15397       return ICEDiag(IK_NotICE, E->getBeginLoc());
15398     }
15399   }
15400   case Expr::BinaryConditionalOperatorClass: {
15401     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15402     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15403     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15404     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15405     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15406     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15407     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15408         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15409     return FalseResult;
15410   }
15411   case Expr::ConditionalOperatorClass: {
15412     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15413     // If the condition (ignoring parens) is a __builtin_constant_p call,
15414     // then only the true side is actually considered in an integer constant
15415     // expression, and it is fully evaluated.  This is an important GNU
15416     // extension.  See GCC PR38377 for discussion.
15417     if (const CallExpr *CallCE
15418         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15419       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15420         return CheckEvalInICE(E, Ctx);
15421     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15422     if (CondResult.Kind == IK_NotICE)
15423       return CondResult;
15424 
15425     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15426     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15427 
15428     if (TrueResult.Kind == IK_NotICE)
15429       return TrueResult;
15430     if (FalseResult.Kind == IK_NotICE)
15431       return FalseResult;
15432     if (CondResult.Kind == IK_ICEIfUnevaluated)
15433       return CondResult;
15434     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15435       return NoDiag();
15436     // Rare case where the diagnostics depend on which side is evaluated
15437     // Note that if we get here, CondResult is 0, and at least one of
15438     // TrueResult and FalseResult is non-zero.
15439     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15440       return FalseResult;
15441     return TrueResult;
15442   }
15443   case Expr::CXXDefaultArgExprClass:
15444     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15445   case Expr::CXXDefaultInitExprClass:
15446     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15447   case Expr::ChooseExprClass: {
15448     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15449   }
15450   case Expr::BuiltinBitCastExprClass: {
15451     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15452       return ICEDiag(IK_NotICE, E->getBeginLoc());
15453     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15454   }
15455   }
15456 
15457   llvm_unreachable("Invalid StmtClass!");
15458 }
15459 
15460 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)15461 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15462                                                     const Expr *E,
15463                                                     llvm::APSInt *Value,
15464                                                     SourceLocation *Loc) {
15465   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15466     if (Loc) *Loc = E->getExprLoc();
15467     return false;
15468   }
15469 
15470   APValue Result;
15471   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15472     return false;
15473 
15474   if (!Result.isInt()) {
15475     if (Loc) *Loc = E->getExprLoc();
15476     return false;
15477   }
15478 
15479   if (Value) *Value = Result.getInt();
15480   return true;
15481 }
15482 
isIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const15483 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15484                                  SourceLocation *Loc) const {
15485   assert(!isValueDependent() &&
15486          "Expression evaluator can't be called on a dependent expression.");
15487 
15488   if (Ctx.getLangOpts().CPlusPlus11)
15489     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15490 
15491   ICEDiag D = CheckICE(this, Ctx);
15492   if (D.Kind != IK_ICE) {
15493     if (Loc) *Loc = D.Loc;
15494     return false;
15495   }
15496   return true;
15497 }
15498 
getIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc,bool isEvaluated) const15499 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15500                                                     SourceLocation *Loc,
15501                                                     bool isEvaluated) const {
15502   assert(!isValueDependent() &&
15503          "Expression evaluator can't be called on a dependent expression.");
15504 
15505   APSInt Value;
15506 
15507   if (Ctx.getLangOpts().CPlusPlus11) {
15508     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15509       return Value;
15510     return None;
15511   }
15512 
15513   if (!isIntegerConstantExpr(Ctx, Loc))
15514     return None;
15515 
15516   // The only possible side-effects here are due to UB discovered in the
15517   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15518   // required to treat the expression as an ICE, so we produce the folded
15519   // value.
15520   EvalResult ExprResult;
15521   Expr::EvalStatus Status;
15522   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15523   Info.InConstantContext = true;
15524 
15525   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15526     llvm_unreachable("ICE cannot be evaluated!");
15527 
15528   return ExprResult.Val.getInt();
15529 }
15530 
isCXX98IntegralConstantExpr(const ASTContext & Ctx) const15531 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15532   assert(!isValueDependent() &&
15533          "Expression evaluator can't be called on a dependent expression.");
15534 
15535   return CheckICE(this, Ctx).Kind == IK_ICE;
15536 }
15537 
isCXX11ConstantExpr(const ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const15538 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15539                                SourceLocation *Loc) const {
15540   assert(!isValueDependent() &&
15541          "Expression evaluator can't be called on a dependent expression.");
15542 
15543   // We support this checking in C++98 mode in order to diagnose compatibility
15544   // issues.
15545   assert(Ctx.getLangOpts().CPlusPlus);
15546 
15547   // Build evaluation settings.
15548   Expr::EvalStatus Status;
15549   SmallVector<PartialDiagnosticAt, 8> Diags;
15550   Status.Diag = &Diags;
15551   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15552 
15553   APValue Scratch;
15554   bool IsConstExpr =
15555       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15556       // FIXME: We don't produce a diagnostic for this, but the callers that
15557       // call us on arbitrary full-expressions should generally not care.
15558       Info.discardCleanups() && !Status.HasSideEffects;
15559 
15560   if (!Diags.empty()) {
15561     IsConstExpr = false;
15562     if (Loc) *Loc = Diags[0].first;
15563   } else if (!IsConstExpr) {
15564     // FIXME: This shouldn't happen.
15565     if (Loc) *Loc = getExprLoc();
15566   }
15567 
15568   return IsConstExpr;
15569 }
15570 
EvaluateWithSubstitution(APValue & Value,ASTContext & Ctx,const FunctionDecl * Callee,ArrayRef<const Expr * > Args,const Expr * This) const15571 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15572                                     const FunctionDecl *Callee,
15573                                     ArrayRef<const Expr*> Args,
15574                                     const Expr *This) const {
15575   assert(!isValueDependent() &&
15576          "Expression evaluator can't be called on a dependent expression.");
15577 
15578   Expr::EvalStatus Status;
15579   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15580   Info.InConstantContext = true;
15581 
15582   LValue ThisVal;
15583   const LValue *ThisPtr = nullptr;
15584   if (This) {
15585 #ifndef NDEBUG
15586     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15587     assert(MD && "Don't provide `this` for non-methods.");
15588     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15589 #endif
15590     if (!This->isValueDependent() &&
15591         EvaluateObjectArgument(Info, This, ThisVal) &&
15592         !Info.EvalStatus.HasSideEffects)
15593       ThisPtr = &ThisVal;
15594 
15595     // Ignore any side-effects from a failed evaluation. This is safe because
15596     // they can't interfere with any other argument evaluation.
15597     Info.EvalStatus.HasSideEffects = false;
15598   }
15599 
15600   CallRef Call = Info.CurrentCall->createCall(Callee);
15601   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15602        I != E; ++I) {
15603     unsigned Idx = I - Args.begin();
15604     if (Idx >= Callee->getNumParams())
15605       break;
15606     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15607     if ((*I)->isValueDependent() ||
15608         !EvaluateCallArg(PVD, *I, Call, Info) ||
15609         Info.EvalStatus.HasSideEffects) {
15610       // If evaluation fails, throw away the argument entirely.
15611       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15612         *Slot = APValue();
15613     }
15614 
15615     // Ignore any side-effects from a failed evaluation. This is safe because
15616     // they can't interfere with any other argument evaluation.
15617     Info.EvalStatus.HasSideEffects = false;
15618   }
15619 
15620   // Parameter cleanups happen in the caller and are not part of this
15621   // evaluation.
15622   Info.discardCleanups();
15623   Info.EvalStatus.HasSideEffects = false;
15624 
15625   // Build fake call to Callee.
15626   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15627   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15628   FullExpressionRAII Scope(Info);
15629   return Evaluate(Value, Info, this) && Scope.destroy() &&
15630          !Info.EvalStatus.HasSideEffects;
15631 }
15632 
isPotentialConstantExpr(const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15633 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15634                                    SmallVectorImpl<
15635                                      PartialDiagnosticAt> &Diags) {
15636   // FIXME: It would be useful to check constexpr function templates, but at the
15637   // moment the constant expression evaluator cannot cope with the non-rigorous
15638   // ASTs which we build for dependent expressions.
15639   if (FD->isDependentContext())
15640     return true;
15641 
15642   Expr::EvalStatus Status;
15643   Status.Diag = &Diags;
15644 
15645   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15646   Info.InConstantContext = true;
15647   Info.CheckingPotentialConstantExpression = true;
15648 
15649   // The constexpr VM attempts to compile all methods to bytecode here.
15650   if (Info.EnableNewConstInterp) {
15651     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15652     return Diags.empty();
15653   }
15654 
15655   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15656   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15657 
15658   // Fabricate an arbitrary expression on the stack and pretend that it
15659   // is a temporary being used as the 'this' pointer.
15660   LValue This;
15661   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15662   This.set({&VIE, Info.CurrentCall->Index});
15663 
15664   ArrayRef<const Expr*> Args;
15665 
15666   APValue Scratch;
15667   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15668     // Evaluate the call as a constant initializer, to allow the construction
15669     // of objects of non-literal types.
15670     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15671     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15672   } else {
15673     SourceLocation Loc = FD->getLocation();
15674     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15675                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15676   }
15677 
15678   return Diags.empty();
15679 }
15680 
isPotentialConstantExprUnevaluated(Expr * E,const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15681 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15682                                               const FunctionDecl *FD,
15683                                               SmallVectorImpl<
15684                                                 PartialDiagnosticAt> &Diags) {
15685   assert(!E->isValueDependent() &&
15686          "Expression evaluator can't be called on a dependent expression.");
15687 
15688   Expr::EvalStatus Status;
15689   Status.Diag = &Diags;
15690 
15691   EvalInfo Info(FD->getASTContext(), Status,
15692                 EvalInfo::EM_ConstantExpressionUnevaluated);
15693   Info.InConstantContext = true;
15694   Info.CheckingPotentialConstantExpression = true;
15695 
15696   // Fabricate a call stack frame to give the arguments a plausible cover story.
15697   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15698 
15699   APValue ResultScratch;
15700   Evaluate(ResultScratch, Info, E);
15701   return Diags.empty();
15702 }
15703 
tryEvaluateObjectSize(uint64_t & Result,ASTContext & Ctx,unsigned Type) const15704 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15705                                  unsigned Type) const {
15706   if (!getType()->isPointerType())
15707     return false;
15708 
15709   Expr::EvalStatus Status;
15710   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15711   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15712 }
15713