• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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__anona656c3110111::SubobjectDesignator269     SubobjectDesignator() : Invalid(true) {}
270 
SubobjectDesignator__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::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__anona656c3110111::CallRef492     CallRef() : OrigCallee(), CallIndex(0), Version() {}
CallRef__anona656c3110111::CallRef493     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
494         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
495 
operator bool__anona656c3110111::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__anona656c3110111::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__anona656c3110311::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 ()__anona656c3110311::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__anona656c3110311::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__anona656c3110311::EvalInfo::EvaluatingConstructorRAII864       void finishedConstructingBases() {
865         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
866       }
finishedConstructingFields__anona656c3110311::EvalInfo::EvaluatingConstructorRAII867       void finishedConstructingFields() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
869       }
~EvaluatingConstructorRAII__anona656c3110311::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__anona656c3110311::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__anona656c3110311::EvalInfo::EvaluatingDestructorRAII885       void startedDestroyingBases() {
886         EI.ObjectsUnderConstruction[Object] =
887             ConstructionPhase::DestroyingBases;
888       }
~EvaluatingDestructorRAII__anona656c3110311::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__anona656c3110311::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__anona656c3110311::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__anona656c3110311::FoldConstant1265     void keepDiagnostics() { Enabled = false; }
~FoldConstant__anona656c3110311::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__anona656c3110311::IgnoreSideEffectsRAII1279     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1280         : Info(Info), OldMode(Info.EvalMode) {
1281       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1282     }
1283 
~IgnoreSideEffectsRAII__anona656c3110311::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__anona656c3110611::ComplexValue1511     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1512 
makeComplexFloat__anona656c3110611::ComplexValue1513     void makeComplexFloat() { IsInt = false; }
isComplexFloat__anona656c3110611::ComplexValue1514     bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anona656c3110611::ComplexValue1515     APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anona656c3110611::ComplexValue1516     APFloat &getComplexFloatImag() { return FloatImag; }
1517 
makeComplexInt__anona656c3110611::ComplexValue1518     void makeComplexInt() { IsInt = true; }
isComplexInt__anona656c3110611::ComplexValue1519     bool isComplexInt() const { return IsInt; }
getComplexIntReal__anona656c3110611::ComplexValue1520     APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anona656c3110611::ComplexValue1521     APSInt &getComplexIntImag() { return IntImag; }
1522 
moveInto__anona656c3110611::ComplexValue1523     void moveInto(APValue &v) const {
1524       if (isComplexFloat())
1525         v = APValue(FloatReal, FloatImag);
1526       else
1527         v = APValue(IntReal, IntImag);
1528     }
setFrom__anona656c3110611::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__anona656c3110611::LValue1550     const APValue::LValueBase getLValueBase() const { return Base; }
getLValueOffset__anona656c3110611::LValue1551     CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anona656c3110611::LValue1552     const CharUnits &getLValueOffset() const { return Offset; }
getLValueDesignator__anona656c3110611::LValue1553     SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anona656c3110611::LValue1554     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
isNullPointer__anona656c3110611::LValue1555     bool isNullPointer() const { return IsNullPtr;}
1556 
getLValueCallIndex__anona656c3110611::LValue1557     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
getLValueVersion__anona656c3110611::LValue1558     unsigned getLValueVersion() const { return Base.getVersion(); }
1559 
moveInto__anona656c3110611::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__anona656c3110611::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__anona656c3110611::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__anona656c3110611::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__anona656c3110611::LValue1604     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1605       set(B, true);
1606     }
1607 
toString__anona656c3110611::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__anona656c3110611::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__anona656c3110611::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__anona656c3110611::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__anona656c3110611::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__anona656c3110611::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__anona656c3110611::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__anona656c3110611::LValue1668     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1669       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1670         Designator.addArrayUnchecked(CAT);
1671     }
addComplex__anona656c3110611::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__anona656c3110611::LValue1676     void clearIsNullPointer() {
1677       IsNullPtr = false;
1678     }
adjustOffsetAndIndex__anona656c3110611::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__anona656c3110611::LValue1698     void adjustOffset(CharUnits N) {
1699       Offset += N;
1700       if (N.getQuantity())
1701         clearIsNullPointer();
1702     }
1703   };
1704 
1705   struct MemberPtr {
MemberPtr__anona656c3110611::MemberPtr1706     MemberPtr() {}
MemberPtr__anona656c3110611::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__anona656c3110611::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__anona656c3110611::MemberPtr1716     bool isDerivedMember() const {
1717       return DeclAndIsDerivedMember.getInt();
1718     }
1719     /// Get the class which the declaration actually lives in.
getContainingRecord__anona656c3110611::MemberPtr1720     const CXXRecordDecl *getContainingRecord() const {
1721       return cast<CXXRecordDecl>(
1722           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1723     }
1724 
moveInto__anona656c3110611::MemberPtr1725     void moveInto(APValue &V) const {
1726       V = APValue(getDecl(), isDerivedMember(), Path);
1727     }
setFrom__anona656c3110611::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__anona656c3110611::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__anona656c3110611::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__anona656c3110611::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 we created.
3501   if (Base.getCallIndex())
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__anona656c3110911::CompleteObject3548   CompleteObject() : Value(nullptr) {}
CompleteObject__anona656c3110911::CompleteObject3549   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3550       : Base(Base), Value(Value), Type(Type) {}
3551 
mayAccessMutableMembers__anona656c3110911::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__anona656c3110911::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__anona656c3110a11::ExtractSubobjectHandler3794   bool failed() { return false; }
found__anona656c3110a11::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__anona656c3110a11::ExtractSubobjectHandler3801   bool found(APSInt &Value, QualType SubobjType) {
3802     Result = APValue(Value);
3803     return true;
3804   }
found__anona656c3110a11::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__anona656c3110b11::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__anona656c3110b11::ModifySubobjectHandler3840   bool failed() { return false; }
found__anona656c3110b11::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__anona656c3110b11::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__anona656c3110b11::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__anona656c3110c11::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__anona656c3110c11::CompoundAssignSubobjectHandler4295   bool failed() { return false; }
found__anona656c3110c11::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__anona656c3110c11::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__anona656c3110c11::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__anona656c3110c11::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__anona656c3110c11::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__anona656c3110d11::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__anona656c3110d11::IncDecSubobjectHandler4437   bool failed() { return false; }
found__anona656c3110d11::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__anona656c3110d11::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__anona656c3110d11::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__anona656c3110d11::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__anona656c3110f11::TempVersionRAII4867   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4868     Frame.pushTempVersion();
4869   }
4870 
~TempVersionRAII__anona656c3110f11::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       return EvaluateDependentExpr(RetExpr, Info) ? ESR_Returned : ESR_Failed;
5147     if (RetExpr &&
5148         !(Result.Slot
5149               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5150               : Evaluate(Result.Value, Info, RetExpr)))
5151       return ESR_Failed;
5152     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5153   }
5154 
5155   case Stmt::CompoundStmtClass: {
5156     BlockScopeRAII Scope(Info);
5157 
5158     const CompoundStmt *CS = cast<CompoundStmt>(S);
5159     for (const auto *BI : CS->body()) {
5160       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5161       if (ESR == ESR_Succeeded)
5162         Case = nullptr;
5163       else if (ESR != ESR_CaseNotFound) {
5164         if (ESR != ESR_Failed && !Scope.destroy())
5165           return ESR_Failed;
5166         return ESR;
5167       }
5168     }
5169     if (Case)
5170       return ESR_CaseNotFound;
5171     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5172   }
5173 
5174   case Stmt::IfStmtClass: {
5175     const IfStmt *IS = cast<IfStmt>(S);
5176 
5177     // Evaluate the condition, as either a var decl or as an expression.
5178     BlockScopeRAII Scope(Info);
5179     if (const Stmt *Init = IS->getInit()) {
5180       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5181       if (ESR != ESR_Succeeded) {
5182         if (ESR != ESR_Failed && !Scope.destroy())
5183           return ESR_Failed;
5184         return ESR;
5185       }
5186     }
5187     bool Cond;
5188     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5189       return ESR_Failed;
5190 
5191     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5192       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5193       if (ESR != ESR_Succeeded) {
5194         if (ESR != ESR_Failed && !Scope.destroy())
5195           return ESR_Failed;
5196         return ESR;
5197       }
5198     }
5199     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5200   }
5201 
5202   case Stmt::WhileStmtClass: {
5203     const WhileStmt *WS = cast<WhileStmt>(S);
5204     while (true) {
5205       BlockScopeRAII Scope(Info);
5206       bool Continue;
5207       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5208                         Continue))
5209         return ESR_Failed;
5210       if (!Continue)
5211         break;
5212 
5213       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5214       if (ESR != ESR_Continue) {
5215         if (ESR != ESR_Failed && !Scope.destroy())
5216           return ESR_Failed;
5217         return ESR;
5218       }
5219       if (!Scope.destroy())
5220         return ESR_Failed;
5221     }
5222     return ESR_Succeeded;
5223   }
5224 
5225   case Stmt::DoStmtClass: {
5226     const DoStmt *DS = cast<DoStmt>(S);
5227     bool Continue;
5228     do {
5229       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5230       if (ESR != ESR_Continue)
5231         return ESR;
5232       Case = nullptr;
5233 
5234       if (DS->getCond()->isValueDependent()) {
5235         EvaluateDependentExpr(DS->getCond(), Info);
5236         // Bailout as we don't know whether to keep going or terminate the loop.
5237         return ESR_Failed;
5238       }
5239       FullExpressionRAII CondScope(Info);
5240       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5241           !CondScope.destroy())
5242         return ESR_Failed;
5243     } while (Continue);
5244     return ESR_Succeeded;
5245   }
5246 
5247   case Stmt::ForStmtClass: {
5248     const ForStmt *FS = cast<ForStmt>(S);
5249     BlockScopeRAII ForScope(Info);
5250     if (FS->getInit()) {
5251       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5252       if (ESR != ESR_Succeeded) {
5253         if (ESR != ESR_Failed && !ForScope.destroy())
5254           return ESR_Failed;
5255         return ESR;
5256       }
5257     }
5258     while (true) {
5259       BlockScopeRAII IterScope(Info);
5260       bool Continue = true;
5261       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5262                                          FS->getCond(), Continue))
5263         return ESR_Failed;
5264       if (!Continue)
5265         break;
5266 
5267       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5268       if (ESR != ESR_Continue) {
5269         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5270           return ESR_Failed;
5271         return ESR;
5272       }
5273 
5274       if (const auto *Inc = FS->getInc()) {
5275         if (Inc->isValueDependent()) {
5276           if (!EvaluateDependentExpr(Inc, Info))
5277             return ESR_Failed;
5278         } else {
5279           FullExpressionRAII IncScope(Info);
5280           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5281             return ESR_Failed;
5282         }
5283       }
5284 
5285       if (!IterScope.destroy())
5286         return ESR_Failed;
5287     }
5288     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5289   }
5290 
5291   case Stmt::CXXForRangeStmtClass: {
5292     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5293     BlockScopeRAII Scope(Info);
5294 
5295     // Evaluate the init-statement if present.
5296     if (FS->getInit()) {
5297       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5298       if (ESR != ESR_Succeeded) {
5299         if (ESR != ESR_Failed && !Scope.destroy())
5300           return ESR_Failed;
5301         return ESR;
5302       }
5303     }
5304 
5305     // Initialize the __range variable.
5306     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5307     if (ESR != ESR_Succeeded) {
5308       if (ESR != ESR_Failed && !Scope.destroy())
5309         return ESR_Failed;
5310       return ESR;
5311     }
5312 
5313     // Create the __begin and __end iterators.
5314     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5315     if (ESR != ESR_Succeeded) {
5316       if (ESR != ESR_Failed && !Scope.destroy())
5317         return ESR_Failed;
5318       return ESR;
5319     }
5320     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5321     if (ESR != ESR_Succeeded) {
5322       if (ESR != ESR_Failed && !Scope.destroy())
5323         return ESR_Failed;
5324       return ESR;
5325     }
5326 
5327     while (true) {
5328       // Condition: __begin != __end.
5329       {
5330         if (FS->getCond()->isValueDependent()) {
5331           EvaluateDependentExpr(FS->getCond(), Info);
5332           // We don't know whether to keep going or terminate the loop.
5333           return ESR_Failed;
5334         }
5335         bool Continue = true;
5336         FullExpressionRAII CondExpr(Info);
5337         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5338           return ESR_Failed;
5339         if (!Continue)
5340           break;
5341       }
5342 
5343       // User's variable declaration, initialized by *__begin.
5344       BlockScopeRAII InnerScope(Info);
5345       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5346       if (ESR != ESR_Succeeded) {
5347         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5348           return ESR_Failed;
5349         return ESR;
5350       }
5351 
5352       // Loop body.
5353       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5354       if (ESR != ESR_Continue) {
5355         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5356           return ESR_Failed;
5357         return ESR;
5358       }
5359       if (FS->getInc()->isValueDependent()) {
5360         if (!EvaluateDependentExpr(FS->getInc(), Info))
5361           return ESR_Failed;
5362       } else {
5363         // Increment: ++__begin
5364         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5365           return ESR_Failed;
5366       }
5367 
5368       if (!InnerScope.destroy())
5369         return ESR_Failed;
5370     }
5371 
5372     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5373   }
5374 
5375   case Stmt::SwitchStmtClass:
5376     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5377 
5378   case Stmt::ContinueStmtClass:
5379     return ESR_Continue;
5380 
5381   case Stmt::BreakStmtClass:
5382     return ESR_Break;
5383 
5384   case Stmt::LabelStmtClass:
5385     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5386 
5387   case Stmt::AttributedStmtClass:
5388     // As a general principle, C++11 attributes can be ignored without
5389     // any semantic impact.
5390     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5391                         Case);
5392 
5393   case Stmt::CaseStmtClass:
5394   case Stmt::DefaultStmtClass:
5395     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5396   case Stmt::CXXTryStmtClass:
5397     // Evaluate try blocks by evaluating all sub statements.
5398     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5399   }
5400 }
5401 
5402 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5403 /// default constructor. If so, we'll fold it whether or not it's marked as
5404 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5405 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)5406 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5407                                            const CXXConstructorDecl *CD,
5408                                            bool IsValueInitialization) {
5409   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5410     return false;
5411 
5412   // Value-initialization does not call a trivial default constructor, so such a
5413   // call is a core constant expression whether or not the constructor is
5414   // constexpr.
5415   if (!CD->isConstexpr() && !IsValueInitialization) {
5416     if (Info.getLangOpts().CPlusPlus11) {
5417       // FIXME: If DiagDecl is an implicitly-declared special member function,
5418       // we should be much more explicit about why it's not constexpr.
5419       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5420         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5421       Info.Note(CD->getLocation(), diag::note_declared_at);
5422     } else {
5423       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5424     }
5425   }
5426   return true;
5427 }
5428 
5429 /// CheckConstexprFunction - Check that a function can be called in a constant
5430 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition,const Stmt * Body)5431 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5432                                    const FunctionDecl *Declaration,
5433                                    const FunctionDecl *Definition,
5434                                    const Stmt *Body) {
5435   // Potential constant expressions can contain calls to declared, but not yet
5436   // defined, constexpr functions.
5437   if (Info.checkingPotentialConstantExpression() && !Definition &&
5438       Declaration->isConstexpr())
5439     return false;
5440 
5441   // Bail out if the function declaration itself is invalid.  We will
5442   // have produced a relevant diagnostic while parsing it, so just
5443   // note the problematic sub-expression.
5444   if (Declaration->isInvalidDecl()) {
5445     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5446     return false;
5447   }
5448 
5449   // DR1872: An instantiated virtual constexpr function can't be called in a
5450   // constant expression (prior to C++20). We can still constant-fold such a
5451   // call.
5452   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5453       cast<CXXMethodDecl>(Declaration)->isVirtual())
5454     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5455 
5456   if (Definition && Definition->isInvalidDecl()) {
5457     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5458     return false;
5459   }
5460 
5461   // Can we evaluate this function call?
5462   if (Definition && Definition->isConstexpr() && Body)
5463     return true;
5464 
5465   if (Info.getLangOpts().CPlusPlus11) {
5466     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5467 
5468     // If this function is not constexpr because it is an inherited
5469     // non-constexpr constructor, diagnose that directly.
5470     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5471     if (CD && CD->isInheritingConstructor()) {
5472       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5473       if (!Inherited->isConstexpr())
5474         DiagDecl = CD = Inherited;
5475     }
5476 
5477     // FIXME: If DiagDecl is an implicitly-declared special member function
5478     // or an inheriting constructor, we should be much more explicit about why
5479     // it's not constexpr.
5480     if (CD && CD->isInheritingConstructor())
5481       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5482         << CD->getInheritedConstructor().getConstructor()->getParent();
5483     else
5484       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5485         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5486     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5487   } else {
5488     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5489   }
5490   return false;
5491 }
5492 
5493 namespace {
5494 struct CheckDynamicTypeHandler {
5495   AccessKinds AccessKind;
5496   typedef bool result_type;
failed__anona656c3111011::CheckDynamicTypeHandler5497   bool failed() { return false; }
found__anona656c3111011::CheckDynamicTypeHandler5498   bool found(APValue &Subobj, QualType SubobjType) { return true; }
found__anona656c3111011::CheckDynamicTypeHandler5499   bool found(APSInt &Value, QualType SubobjType) { return true; }
found__anona656c3111011::CheckDynamicTypeHandler5500   bool found(APFloat &Value, QualType SubobjType) { return true; }
5501 };
5502 } // end anonymous namespace
5503 
5504 /// Check that we can access the notional vptr of an object / determine its
5505 /// dynamic type.
checkDynamicType(EvalInfo & Info,const Expr * E,const LValue & This,AccessKinds AK,bool Polymorphic)5506 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5507                              AccessKinds AK, bool Polymorphic) {
5508   if (This.Designator.Invalid)
5509     return false;
5510 
5511   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5512 
5513   if (!Obj)
5514     return false;
5515 
5516   if (!Obj.Value) {
5517     // The object is not usable in constant expressions, so we can't inspect
5518     // its value to see if it's in-lifetime or what the active union members
5519     // are. We can still check for a one-past-the-end lvalue.
5520     if (This.Designator.isOnePastTheEnd() ||
5521         This.Designator.isMostDerivedAnUnsizedArray()) {
5522       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5523                          ? diag::note_constexpr_access_past_end
5524                          : diag::note_constexpr_access_unsized_array)
5525           << AK;
5526       return false;
5527     } else if (Polymorphic) {
5528       // Conservatively refuse to perform a polymorphic operation if we would
5529       // not be able to read a notional 'vptr' value.
5530       APValue Val;
5531       This.moveInto(Val);
5532       QualType StarThisType =
5533           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5534       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5535           << AK << Val.getAsString(Info.Ctx, StarThisType);
5536       return false;
5537     }
5538     return true;
5539   }
5540 
5541   CheckDynamicTypeHandler Handler{AK};
5542   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5543 }
5544 
5545 /// Check that the pointee of the 'this' pointer in a member function call is
5546 /// either within its lifetime or in its period of construction or destruction.
5547 static bool
checkNonVirtualMemberCallThisPointer(EvalInfo & Info,const Expr * E,const LValue & This,const CXXMethodDecl * NamedMember)5548 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5549                                      const LValue &This,
5550                                      const CXXMethodDecl *NamedMember) {
5551   return checkDynamicType(
5552       Info, E, This,
5553       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5554 }
5555 
5556 struct DynamicType {
5557   /// The dynamic class type of the object.
5558   const CXXRecordDecl *Type;
5559   /// The corresponding path length in the lvalue.
5560   unsigned PathLength;
5561 };
5562 
getBaseClassType(SubobjectDesignator & Designator,unsigned PathLength)5563 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5564                                              unsigned PathLength) {
5565   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5566       Designator.Entries.size() && "invalid path length");
5567   return (PathLength == Designator.MostDerivedPathLength)
5568              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5569              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5570 }
5571 
5572 /// Determine the dynamic type of an object.
ComputeDynamicType(EvalInfo & Info,const Expr * E,LValue & This,AccessKinds AK)5573 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5574                                                 LValue &This, AccessKinds AK) {
5575   // If we don't have an lvalue denoting an object of class type, there is no
5576   // meaningful dynamic type. (We consider objects of non-class type to have no
5577   // dynamic type.)
5578   if (!checkDynamicType(Info, E, This, AK, true))
5579     return None;
5580 
5581   // Refuse to compute a dynamic type in the presence of virtual bases. This
5582   // shouldn't happen other than in constant-folding situations, since literal
5583   // types can't have virtual bases.
5584   //
5585   // Note that consumers of DynamicType assume that the type has no virtual
5586   // bases, and will need modifications if this restriction is relaxed.
5587   const CXXRecordDecl *Class =
5588       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5589   if (!Class || Class->getNumVBases()) {
5590     Info.FFDiag(E);
5591     return None;
5592   }
5593 
5594   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5595   // binary search here instead. But the overwhelmingly common case is that
5596   // we're not in the middle of a constructor, so it probably doesn't matter
5597   // in practice.
5598   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5599   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5600        PathLength <= Path.size(); ++PathLength) {
5601     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5602                                       Path.slice(0, PathLength))) {
5603     case ConstructionPhase::Bases:
5604     case ConstructionPhase::DestroyingBases:
5605       // We're constructing or destroying a base class. This is not the dynamic
5606       // type.
5607       break;
5608 
5609     case ConstructionPhase::None:
5610     case ConstructionPhase::AfterBases:
5611     case ConstructionPhase::AfterFields:
5612     case ConstructionPhase::Destroying:
5613       // We've finished constructing the base classes and not yet started
5614       // destroying them again, so this is the dynamic type.
5615       return DynamicType{getBaseClassType(This.Designator, PathLength),
5616                          PathLength};
5617     }
5618   }
5619 
5620   // CWG issue 1517: we're constructing a base class of the object described by
5621   // 'This', so that object has not yet begun its period of construction and
5622   // any polymorphic operation on it results in undefined behavior.
5623   Info.FFDiag(E);
5624   return None;
5625 }
5626 
5627 /// Perform virtual dispatch.
HandleVirtualDispatch(EvalInfo & Info,const Expr * E,LValue & This,const CXXMethodDecl * Found,llvm::SmallVectorImpl<QualType> & CovariantAdjustmentPath)5628 static const CXXMethodDecl *HandleVirtualDispatch(
5629     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5630     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5631   Optional<DynamicType> DynType = ComputeDynamicType(
5632       Info, E, This,
5633       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5634   if (!DynType)
5635     return nullptr;
5636 
5637   // Find the final overrider. It must be declared in one of the classes on the
5638   // path from the dynamic type to the static type.
5639   // FIXME: If we ever allow literal types to have virtual base classes, that
5640   // won't be true.
5641   const CXXMethodDecl *Callee = Found;
5642   unsigned PathLength = DynType->PathLength;
5643   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5644     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5645     const CXXMethodDecl *Overrider =
5646         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5647     if (Overrider) {
5648       Callee = Overrider;
5649       break;
5650     }
5651   }
5652 
5653   // C++2a [class.abstract]p6:
5654   //   the effect of making a virtual call to a pure virtual function [...] is
5655   //   undefined
5656   if (Callee->isPure()) {
5657     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5658     Info.Note(Callee->getLocation(), diag::note_declared_at);
5659     return nullptr;
5660   }
5661 
5662   // If necessary, walk the rest of the path to determine the sequence of
5663   // covariant adjustment steps to apply.
5664   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5665                                        Found->getReturnType())) {
5666     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5667     for (unsigned CovariantPathLength = PathLength + 1;
5668          CovariantPathLength != This.Designator.Entries.size();
5669          ++CovariantPathLength) {
5670       const CXXRecordDecl *NextClass =
5671           getBaseClassType(This.Designator, CovariantPathLength);
5672       const CXXMethodDecl *Next =
5673           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5674       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5675                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5676         CovariantAdjustmentPath.push_back(Next->getReturnType());
5677     }
5678     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5679                                          CovariantAdjustmentPath.back()))
5680       CovariantAdjustmentPath.push_back(Found->getReturnType());
5681   }
5682 
5683   // Perform 'this' adjustment.
5684   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5685     return nullptr;
5686 
5687   return Callee;
5688 }
5689 
5690 /// Perform the adjustment from a value returned by a virtual function to
5691 /// a value of the statically expected type, which may be a pointer or
5692 /// reference to a base class of the returned type.
HandleCovariantReturnAdjustment(EvalInfo & Info,const Expr * E,APValue & Result,ArrayRef<QualType> Path)5693 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5694                                             APValue &Result,
5695                                             ArrayRef<QualType> Path) {
5696   assert(Result.isLValue() &&
5697          "unexpected kind of APValue for covariant return");
5698   if (Result.isNullPointer())
5699     return true;
5700 
5701   LValue LVal;
5702   LVal.setFrom(Info.Ctx, Result);
5703 
5704   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5705   for (unsigned I = 1; I != Path.size(); ++I) {
5706     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5707     assert(OldClass && NewClass && "unexpected kind of covariant return");
5708     if (OldClass != NewClass &&
5709         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5710       return false;
5711     OldClass = NewClass;
5712   }
5713 
5714   LVal.moveInto(Result);
5715   return true;
5716 }
5717 
5718 /// Determine whether \p Base, which is known to be a direct base class of
5719 /// \p Derived, is a public base class.
isBaseClassPublic(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)5720 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5721                               const CXXRecordDecl *Base) {
5722   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5723     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5724     if (BaseClass && declaresSameEntity(BaseClass, Base))
5725       return BaseSpec.getAccessSpecifier() == AS_public;
5726   }
5727   llvm_unreachable("Base is not a direct base of Derived");
5728 }
5729 
5730 /// Apply the given dynamic cast operation on the provided lvalue.
5731 ///
5732 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5733 /// to find a suitable target subobject.
HandleDynamicCast(EvalInfo & Info,const ExplicitCastExpr * E,LValue & Ptr)5734 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5735                               LValue &Ptr) {
5736   // We can't do anything with a non-symbolic pointer value.
5737   SubobjectDesignator &D = Ptr.Designator;
5738   if (D.Invalid)
5739     return false;
5740 
5741   // C++ [expr.dynamic.cast]p6:
5742   //   If v is a null pointer value, the result is a null pointer value.
5743   if (Ptr.isNullPointer() && !E->isGLValue())
5744     return true;
5745 
5746   // For all the other cases, we need the pointer to point to an object within
5747   // its lifetime / period of construction / destruction, and we need to know
5748   // its dynamic type.
5749   Optional<DynamicType> DynType =
5750       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5751   if (!DynType)
5752     return false;
5753 
5754   // C++ [expr.dynamic.cast]p7:
5755   //   If T is "pointer to cv void", then the result is a pointer to the most
5756   //   derived object
5757   if (E->getType()->isVoidPointerType())
5758     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5759 
5760   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5761   assert(C && "dynamic_cast target is not void pointer nor class");
5762   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5763 
5764   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5765     // C++ [expr.dynamic.cast]p9:
5766     if (!E->isGLValue()) {
5767       //   The value of a failed cast to pointer type is the null pointer value
5768       //   of the required result type.
5769       Ptr.setNull(Info.Ctx, E->getType());
5770       return true;
5771     }
5772 
5773     //   A failed cast to reference type throws [...] std::bad_cast.
5774     unsigned DiagKind;
5775     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5776                    DynType->Type->isDerivedFrom(C)))
5777       DiagKind = 0;
5778     else if (!Paths || Paths->begin() == Paths->end())
5779       DiagKind = 1;
5780     else if (Paths->isAmbiguous(CQT))
5781       DiagKind = 2;
5782     else {
5783       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5784       DiagKind = 3;
5785     }
5786     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5787         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5788         << Info.Ctx.getRecordType(DynType->Type)
5789         << E->getType().getUnqualifiedType();
5790     return false;
5791   };
5792 
5793   // Runtime check, phase 1:
5794   //   Walk from the base subobject towards the derived object looking for the
5795   //   target type.
5796   for (int PathLength = Ptr.Designator.Entries.size();
5797        PathLength >= (int)DynType->PathLength; --PathLength) {
5798     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5799     if (declaresSameEntity(Class, C))
5800       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5801     // We can only walk across public inheritance edges.
5802     if (PathLength > (int)DynType->PathLength &&
5803         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5804                            Class))
5805       return RuntimeCheckFailed(nullptr);
5806   }
5807 
5808   // Runtime check, phase 2:
5809   //   Search the dynamic type for an unambiguous public base of type C.
5810   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5811                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5812   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5813       Paths.front().Access == AS_public) {
5814     // Downcast to the dynamic type...
5815     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5816       return false;
5817     // ... then upcast to the chosen base class subobject.
5818     for (CXXBasePathElement &Elem : Paths.front())
5819       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5820         return false;
5821     return true;
5822   }
5823 
5824   // Otherwise, the runtime check fails.
5825   return RuntimeCheckFailed(&Paths);
5826 }
5827 
5828 namespace {
5829 struct StartLifetimeOfUnionMemberHandler {
5830   EvalInfo &Info;
5831   const Expr *LHSExpr;
5832   const FieldDecl *Field;
5833   bool DuringInit;
5834   bool Failed = false;
5835   static const AccessKinds AccessKind = AK_Assign;
5836 
5837   typedef bool result_type;
failed__anona656c3111211::StartLifetimeOfUnionMemberHandler5838   bool failed() { return Failed; }
found__anona656c3111211::StartLifetimeOfUnionMemberHandler5839   bool found(APValue &Subobj, QualType SubobjType) {
5840     // We are supposed to perform no initialization but begin the lifetime of
5841     // the object. We interpret that as meaning to do what default
5842     // initialization of the object would do if all constructors involved were
5843     // trivial:
5844     //  * All base, non-variant member, and array element subobjects' lifetimes
5845     //    begin
5846     //  * No variant members' lifetimes begin
5847     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5848     assert(SubobjType->isUnionType());
5849     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5850       // This union member is already active. If it's also in-lifetime, there's
5851       // nothing to do.
5852       if (Subobj.getUnionValue().hasValue())
5853         return true;
5854     } else if (DuringInit) {
5855       // We're currently in the process of initializing a different union
5856       // member.  If we carried on, that initialization would attempt to
5857       // store to an inactive union member, resulting in undefined behavior.
5858       Info.FFDiag(LHSExpr,
5859                   diag::note_constexpr_union_member_change_during_init);
5860       return false;
5861     }
5862     APValue Result;
5863     Failed = !getDefaultInitValue(Field->getType(), Result);
5864     Subobj.setUnion(Field, Result);
5865     return true;
5866   }
found__anona656c3111211::StartLifetimeOfUnionMemberHandler5867   bool found(APSInt &Value, QualType SubobjType) {
5868     llvm_unreachable("wrong value kind for union object");
5869   }
found__anona656c3111211::StartLifetimeOfUnionMemberHandler5870   bool found(APFloat &Value, QualType SubobjType) {
5871     llvm_unreachable("wrong value kind for union object");
5872   }
5873 };
5874 } // end anonymous namespace
5875 
5876 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5877 
5878 /// Handle a builtin simple-assignment or a call to a trivial assignment
5879 /// operator whose left-hand side might involve a union member access. If it
5880 /// does, implicitly start the lifetime of any accessed union elements per
5881 /// C++20 [class.union]5.
HandleUnionActiveMemberChange(EvalInfo & Info,const Expr * LHSExpr,const LValue & LHS)5882 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5883                                           const LValue &LHS) {
5884   if (LHS.InvalidBase || LHS.Designator.Invalid)
5885     return false;
5886 
5887   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5888   // C++ [class.union]p5:
5889   //   define the set S(E) of subexpressions of E as follows:
5890   unsigned PathLength = LHS.Designator.Entries.size();
5891   for (const Expr *E = LHSExpr; E != nullptr;) {
5892     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5893     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5894       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5895       // Note that we can't implicitly start the lifetime of a reference,
5896       // so we don't need to proceed any further if we reach one.
5897       if (!FD || FD->getType()->isReferenceType())
5898         break;
5899 
5900       //    ... and also contains A.B if B names a union member ...
5901       if (FD->getParent()->isUnion()) {
5902         //    ... of a non-class, non-array type, or of a class type with a
5903         //    trivial default constructor that is not deleted, or an array of
5904         //    such types.
5905         auto *RD =
5906             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5907         if (!RD || RD->hasTrivialDefaultConstructor())
5908           UnionPathLengths.push_back({PathLength - 1, FD});
5909       }
5910 
5911       E = ME->getBase();
5912       --PathLength;
5913       assert(declaresSameEntity(FD,
5914                                 LHS.Designator.Entries[PathLength]
5915                                     .getAsBaseOrMember().getPointer()));
5916 
5917       //   -- If E is of the form A[B] and is interpreted as a built-in array
5918       //      subscripting operator, S(E) is [S(the array operand, if any)].
5919     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5920       // Step over an ArrayToPointerDecay implicit cast.
5921       auto *Base = ASE->getBase()->IgnoreImplicit();
5922       if (!Base->getType()->isArrayType())
5923         break;
5924 
5925       E = Base;
5926       --PathLength;
5927 
5928     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5929       // Step over a derived-to-base conversion.
5930       E = ICE->getSubExpr();
5931       if (ICE->getCastKind() == CK_NoOp)
5932         continue;
5933       if (ICE->getCastKind() != CK_DerivedToBase &&
5934           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5935         break;
5936       // Walk path backwards as we walk up from the base to the derived class.
5937       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5938         --PathLength;
5939         (void)Elt;
5940         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5941                                   LHS.Designator.Entries[PathLength]
5942                                       .getAsBaseOrMember().getPointer()));
5943       }
5944 
5945     //   -- Otherwise, S(E) is empty.
5946     } else {
5947       break;
5948     }
5949   }
5950 
5951   // Common case: no unions' lifetimes are started.
5952   if (UnionPathLengths.empty())
5953     return true;
5954 
5955   //   if modification of X [would access an inactive union member], an object
5956   //   of the type of X is implicitly created
5957   CompleteObject Obj =
5958       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5959   if (!Obj)
5960     return false;
5961   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5962            llvm::reverse(UnionPathLengths)) {
5963     // Form a designator for the union object.
5964     SubobjectDesignator D = LHS.Designator;
5965     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5966 
5967     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5968                       ConstructionPhase::AfterBases;
5969     StartLifetimeOfUnionMemberHandler StartLifetime{
5970         Info, LHSExpr, LengthAndField.second, DuringInit};
5971     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5972       return false;
5973   }
5974 
5975   return true;
5976 }
5977 
EvaluateCallArg(const ParmVarDecl * PVD,const Expr * Arg,CallRef Call,EvalInfo & Info,bool NonNull=false)5978 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5979                             CallRef Call, EvalInfo &Info,
5980                             bool NonNull = false) {
5981   LValue LV;
5982   // Create the parameter slot and register its destruction. For a vararg
5983   // argument, create a temporary.
5984   // FIXME: For calling conventions that destroy parameters in the callee,
5985   // should we consider performing destruction when the function returns
5986   // instead?
5987   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5988                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5989                                                        ScopeKind::Call, LV);
5990   if (!EvaluateInPlace(V, Info, LV, Arg))
5991     return false;
5992 
5993   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
5994   // undefined behavior, so is non-constant.
5995   if (NonNull && V.isLValue() && V.isNullPointer()) {
5996     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
5997     return false;
5998   }
5999 
6000   return true;
6001 }
6002 
6003 /// Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,CallRef Call,EvalInfo & Info,const FunctionDecl * Callee,bool RightToLeft=false)6004 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6005                          EvalInfo &Info, const FunctionDecl *Callee,
6006                          bool RightToLeft = false) {
6007   bool Success = true;
6008   llvm::SmallBitVector ForbiddenNullArgs;
6009   if (Callee->hasAttr<NonNullAttr>()) {
6010     ForbiddenNullArgs.resize(Args.size());
6011     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6012       if (!Attr->args_size()) {
6013         ForbiddenNullArgs.set();
6014         break;
6015       } else
6016         for (auto Idx : Attr->args()) {
6017           unsigned ASTIdx = Idx.getASTIndex();
6018           if (ASTIdx >= Args.size())
6019             continue;
6020           ForbiddenNullArgs[ASTIdx] = 1;
6021         }
6022     }
6023   }
6024   for (unsigned I = 0; I < Args.size(); I++) {
6025     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6026     const ParmVarDecl *PVD =
6027         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6028     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6029     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6030       // If we're checking for a potential constant expression, evaluate all
6031       // initializers even if some of them fail.
6032       if (!Info.noteFailure())
6033         return false;
6034       Success = false;
6035     }
6036   }
6037   return Success;
6038 }
6039 
6040 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6041 /// constructor or assignment operator.
handleTrivialCopy(EvalInfo & Info,const ParmVarDecl * Param,const Expr * E,APValue & Result,bool CopyObjectRepresentation)6042 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6043                               const Expr *E, APValue &Result,
6044                               bool CopyObjectRepresentation) {
6045   // Find the reference argument.
6046   CallStackFrame *Frame = Info.CurrentCall;
6047   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6048   if (!RefValue) {
6049     Info.FFDiag(E);
6050     return false;
6051   }
6052 
6053   // Copy out the contents of the RHS object.
6054   LValue RefLValue;
6055   RefLValue.setFrom(Info.Ctx, *RefValue);
6056   return handleLValueToRValueConversion(
6057       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6058       CopyObjectRepresentation);
6059 }
6060 
6061 /// 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)6062 static bool HandleFunctionCall(SourceLocation CallLoc,
6063                                const FunctionDecl *Callee, const LValue *This,
6064                                ArrayRef<const Expr *> Args, CallRef Call,
6065                                const Stmt *Body, EvalInfo &Info,
6066                                APValue &Result, const LValue *ResultSlot) {
6067   if (!Info.CheckCallLimit(CallLoc))
6068     return false;
6069 
6070   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6071 
6072   // For a trivial copy or move assignment, perform an APValue copy. This is
6073   // essential for unions, where the operations performed by the assignment
6074   // operator cannot be represented as statements.
6075   //
6076   // Skip this for non-union classes with no fields; in that case, the defaulted
6077   // copy/move does not actually read the object.
6078   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6079   if (MD && MD->isDefaulted() &&
6080       (MD->getParent()->isUnion() ||
6081        (MD->isTrivial() &&
6082         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6083     assert(This &&
6084            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6085     APValue RHSValue;
6086     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6087                            MD->getParent()->isUnion()))
6088       return false;
6089     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6090         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6091       return false;
6092     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6093                           RHSValue))
6094       return false;
6095     This->moveInto(Result);
6096     return true;
6097   } else if (MD && isLambdaCallOperator(MD)) {
6098     // We're in a lambda; determine the lambda capture field maps unless we're
6099     // just constexpr checking a lambda's call operator. constexpr checking is
6100     // done before the captures have been added to the closure object (unless
6101     // we're inferring constexpr-ness), so we don't have access to them in this
6102     // case. But since we don't need the captures to constexpr check, we can
6103     // just ignore them.
6104     if (!Info.checkingPotentialConstantExpression())
6105       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6106                                         Frame.LambdaThisCaptureField);
6107   }
6108 
6109   StmtResult Ret = {Result, ResultSlot};
6110   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6111   if (ESR == ESR_Succeeded) {
6112     if (Callee->getReturnType()->isVoidType())
6113       return true;
6114     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6115   }
6116   return ESR == ESR_Returned;
6117 }
6118 
6119 /// Evaluate a constructor call.
HandleConstructorCall(const Expr * E,const LValue & This,CallRef Call,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6120 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6121                                   CallRef Call,
6122                                   const CXXConstructorDecl *Definition,
6123                                   EvalInfo &Info, APValue &Result) {
6124   SourceLocation CallLoc = E->getExprLoc();
6125   if (!Info.CheckCallLimit(CallLoc))
6126     return false;
6127 
6128   const CXXRecordDecl *RD = Definition->getParent();
6129   if (RD->getNumVBases()) {
6130     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6131     return false;
6132   }
6133 
6134   EvalInfo::EvaluatingConstructorRAII EvalObj(
6135       Info,
6136       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6137       RD->getNumBases());
6138   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6139 
6140   // FIXME: Creating an APValue just to hold a nonexistent return value is
6141   // wasteful.
6142   APValue RetVal;
6143   StmtResult Ret = {RetVal, nullptr};
6144 
6145   // If it's a delegating constructor, delegate.
6146   if (Definition->isDelegatingConstructor()) {
6147     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6148     if ((*I)->getInit()->isValueDependent()) {
6149       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6150         return false;
6151     } else {
6152       FullExpressionRAII InitScope(Info);
6153       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6154           !InitScope.destroy())
6155         return false;
6156     }
6157     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6158   }
6159 
6160   // For a trivial copy or move constructor, perform an APValue copy. This is
6161   // essential for unions (or classes with anonymous union members), where the
6162   // operations performed by the constructor cannot be represented by
6163   // ctor-initializers.
6164   //
6165   // Skip this for empty non-union classes; we should not perform an
6166   // lvalue-to-rvalue conversion on them because their copy constructor does not
6167   // actually read them.
6168   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6169       (Definition->getParent()->isUnion() ||
6170        (Definition->isTrivial() &&
6171         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6172     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6173                              Definition->getParent()->isUnion());
6174   }
6175 
6176   // Reserve space for the struct members.
6177   if (!Result.hasValue()) {
6178     if (!RD->isUnion())
6179       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6180                        std::distance(RD->field_begin(), RD->field_end()));
6181     else
6182       // A union starts with no active member.
6183       Result = APValue((const FieldDecl*)nullptr);
6184   }
6185 
6186   if (RD->isInvalidDecl()) return false;
6187   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6188 
6189   // A scope for temporaries lifetime-extended by reference members.
6190   BlockScopeRAII LifetimeExtendedScope(Info);
6191 
6192   bool Success = true;
6193   unsigned BasesSeen = 0;
6194 #ifndef NDEBUG
6195   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6196 #endif
6197   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6198   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6199     // We might be initializing the same field again if this is an indirect
6200     // field initialization.
6201     if (FieldIt == RD->field_end() ||
6202         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6203       assert(Indirect && "fields out of order?");
6204       return;
6205     }
6206 
6207     // Default-initialize any fields with no explicit initializer.
6208     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6209       assert(FieldIt != RD->field_end() && "missing field?");
6210       if (!FieldIt->isUnnamedBitfield())
6211         Success &= getDefaultInitValue(
6212             FieldIt->getType(),
6213             Result.getStructField(FieldIt->getFieldIndex()));
6214     }
6215     ++FieldIt;
6216   };
6217   for (const auto *I : Definition->inits()) {
6218     LValue Subobject = This;
6219     LValue SubobjectParent = This;
6220     APValue *Value = &Result;
6221 
6222     // Determine the subobject to initialize.
6223     FieldDecl *FD = nullptr;
6224     if (I->isBaseInitializer()) {
6225       QualType BaseType(I->getBaseClass(), 0);
6226 #ifndef NDEBUG
6227       // Non-virtual base classes are initialized in the order in the class
6228       // definition. We have already checked for virtual base classes.
6229       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6230       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6231              "base class initializers not in expected order");
6232       ++BaseIt;
6233 #endif
6234       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6235                                   BaseType->getAsCXXRecordDecl(), &Layout))
6236         return false;
6237       Value = &Result.getStructBase(BasesSeen++);
6238     } else if ((FD = I->getMember())) {
6239       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6240         return false;
6241       if (RD->isUnion()) {
6242         Result = APValue(FD);
6243         Value = &Result.getUnionValue();
6244       } else {
6245         SkipToField(FD, false);
6246         Value = &Result.getStructField(FD->getFieldIndex());
6247       }
6248     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6249       // Walk the indirect field decl's chain to find the object to initialize,
6250       // and make sure we've initialized every step along it.
6251       auto IndirectFieldChain = IFD->chain();
6252       for (auto *C : IndirectFieldChain) {
6253         FD = cast<FieldDecl>(C);
6254         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6255         // Switch the union field if it differs. This happens if we had
6256         // preceding zero-initialization, and we're now initializing a union
6257         // subobject other than the first.
6258         // FIXME: In this case, the values of the other subobjects are
6259         // specified, since zero-initialization sets all padding bits to zero.
6260         if (!Value->hasValue() ||
6261             (Value->isUnion() && Value->getUnionField() != FD)) {
6262           if (CD->isUnion())
6263             *Value = APValue(FD);
6264           else
6265             // FIXME: This immediately starts the lifetime of all members of
6266             // an anonymous struct. It would be preferable to strictly start
6267             // member lifetime in initialization order.
6268             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6269         }
6270         // Store Subobject as its parent before updating it for the last element
6271         // in the chain.
6272         if (C == IndirectFieldChain.back())
6273           SubobjectParent = Subobject;
6274         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6275           return false;
6276         if (CD->isUnion())
6277           Value = &Value->getUnionValue();
6278         else {
6279           if (C == IndirectFieldChain.front() && !RD->isUnion())
6280             SkipToField(FD, true);
6281           Value = &Value->getStructField(FD->getFieldIndex());
6282         }
6283       }
6284     } else {
6285       llvm_unreachable("unknown base initializer kind");
6286     }
6287 
6288     // Need to override This for implicit field initializers as in this case
6289     // This refers to innermost anonymous struct/union containing initializer,
6290     // not to currently constructed class.
6291     const Expr *Init = I->getInit();
6292     if (Init->isValueDependent()) {
6293       if (!EvaluateDependentExpr(Init, Info))
6294         return false;
6295     } else {
6296       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6297                                     isa<CXXDefaultInitExpr>(Init));
6298       FullExpressionRAII InitScope(Info);
6299       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6300           (FD && FD->isBitField() &&
6301            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6302         // If we're checking for a potential constant expression, evaluate all
6303         // initializers even if some of them fail.
6304         if (!Info.noteFailure())
6305           return false;
6306         Success = false;
6307       }
6308     }
6309 
6310     // This is the point at which the dynamic type of the object becomes this
6311     // class type.
6312     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6313       EvalObj.finishedConstructingBases();
6314   }
6315 
6316   // Default-initialize any remaining fields.
6317   if (!RD->isUnion()) {
6318     for (; FieldIt != RD->field_end(); ++FieldIt) {
6319       if (!FieldIt->isUnnamedBitfield())
6320         Success &= getDefaultInitValue(
6321             FieldIt->getType(),
6322             Result.getStructField(FieldIt->getFieldIndex()));
6323     }
6324   }
6325 
6326   EvalObj.finishedConstructingFields();
6327 
6328   return Success &&
6329          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6330          LifetimeExtendedScope.destroy();
6331 }
6332 
HandleConstructorCall(const Expr * E,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6333 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6334                                   ArrayRef<const Expr*> Args,
6335                                   const CXXConstructorDecl *Definition,
6336                                   EvalInfo &Info, APValue &Result) {
6337   CallScopeRAII CallScope(Info);
6338   CallRef Call = Info.CurrentCall->createCall(Definition);
6339   if (!EvaluateArgs(Args, Call, Info, Definition))
6340     return false;
6341 
6342   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6343          CallScope.destroy();
6344 }
6345 
HandleDestructionImpl(EvalInfo & Info,SourceLocation CallLoc,const LValue & This,APValue & Value,QualType T)6346 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6347                                   const LValue &This, APValue &Value,
6348                                   QualType T) {
6349   // Objects can only be destroyed while they're within their lifetimes.
6350   // FIXME: We have no representation for whether an object of type nullptr_t
6351   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6352   // as indeterminate instead?
6353   if (Value.isAbsent() && !T->isNullPtrType()) {
6354     APValue Printable;
6355     This.moveInto(Printable);
6356     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6357       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6358     return false;
6359   }
6360 
6361   // Invent an expression for location purposes.
6362   // FIXME: We shouldn't need to do this.
6363   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6364 
6365   // For arrays, destroy elements right-to-left.
6366   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6367     uint64_t Size = CAT->getSize().getZExtValue();
6368     QualType ElemT = CAT->getElementType();
6369 
6370     LValue ElemLV = This;
6371     ElemLV.addArray(Info, &LocE, CAT);
6372     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6373       return false;
6374 
6375     // Ensure that we have actual array elements available to destroy; the
6376     // destructors might mutate the value, so we can't run them on the array
6377     // filler.
6378     if (Size && Size > Value.getArrayInitializedElts())
6379       expandArray(Value, Value.getArraySize() - 1);
6380 
6381     for (; Size != 0; --Size) {
6382       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6383       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6384           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6385         return false;
6386     }
6387 
6388     // End the lifetime of this array now.
6389     Value = APValue();
6390     return true;
6391   }
6392 
6393   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6394   if (!RD) {
6395     if (T.isDestructedType()) {
6396       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6397       return false;
6398     }
6399 
6400     Value = APValue();
6401     return true;
6402   }
6403 
6404   if (RD->getNumVBases()) {
6405     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6406     return false;
6407   }
6408 
6409   const CXXDestructorDecl *DD = RD->getDestructor();
6410   if (!DD && !RD->hasTrivialDestructor()) {
6411     Info.FFDiag(CallLoc);
6412     return false;
6413   }
6414 
6415   if (!DD || DD->isTrivial() ||
6416       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6417     // A trivial destructor just ends the lifetime of the object. Check for
6418     // this case before checking for a body, because we might not bother
6419     // building a body for a trivial destructor. Note that it doesn't matter
6420     // whether the destructor is constexpr in this case; all trivial
6421     // destructors are constexpr.
6422     //
6423     // If an anonymous union would be destroyed, some enclosing destructor must
6424     // have been explicitly defined, and the anonymous union destruction should
6425     // have no effect.
6426     Value = APValue();
6427     return true;
6428   }
6429 
6430   if (!Info.CheckCallLimit(CallLoc))
6431     return false;
6432 
6433   const FunctionDecl *Definition = nullptr;
6434   const Stmt *Body = DD->getBody(Definition);
6435 
6436   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6437     return false;
6438 
6439   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6440 
6441   // We're now in the period of destruction of this object.
6442   unsigned BasesLeft = RD->getNumBases();
6443   EvalInfo::EvaluatingDestructorRAII EvalObj(
6444       Info,
6445       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6446   if (!EvalObj.DidInsert) {
6447     // C++2a [class.dtor]p19:
6448     //   the behavior is undefined if the destructor is invoked for an object
6449     //   whose lifetime has ended
6450     // (Note that formally the lifetime ends when the period of destruction
6451     // begins, even though certain uses of the object remain valid until the
6452     // period of destruction ends.)
6453     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6454     return false;
6455   }
6456 
6457   // FIXME: Creating an APValue just to hold a nonexistent return value is
6458   // wasteful.
6459   APValue RetVal;
6460   StmtResult Ret = {RetVal, nullptr};
6461   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6462     return false;
6463 
6464   // A union destructor does not implicitly destroy its members.
6465   if (RD->isUnion())
6466     return true;
6467 
6468   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6469 
6470   // We don't have a good way to iterate fields in reverse, so collect all the
6471   // fields first and then walk them backwards.
6472   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6473   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6474     if (FD->isUnnamedBitfield())
6475       continue;
6476 
6477     LValue Subobject = This;
6478     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6479       return false;
6480 
6481     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6482     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6483                                FD->getType()))
6484       return false;
6485   }
6486 
6487   if (BasesLeft != 0)
6488     EvalObj.startedDestroyingBases();
6489 
6490   // Destroy base classes in reverse order.
6491   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6492     --BasesLeft;
6493 
6494     QualType BaseType = Base.getType();
6495     LValue Subobject = This;
6496     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6497                                 BaseType->getAsCXXRecordDecl(), &Layout))
6498       return false;
6499 
6500     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6501     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6502                                BaseType))
6503       return false;
6504   }
6505   assert(BasesLeft == 0 && "NumBases was wrong?");
6506 
6507   // The period of destruction ends now. The object is gone.
6508   Value = APValue();
6509   return true;
6510 }
6511 
6512 namespace {
6513 struct DestroyObjectHandler {
6514   EvalInfo &Info;
6515   const Expr *E;
6516   const LValue &This;
6517   const AccessKinds AccessKind;
6518 
6519   typedef bool result_type;
failed__anona656c3111411::DestroyObjectHandler6520   bool failed() { return false; }
found__anona656c3111411::DestroyObjectHandler6521   bool found(APValue &Subobj, QualType SubobjType) {
6522     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6523                                  SubobjType);
6524   }
found__anona656c3111411::DestroyObjectHandler6525   bool found(APSInt &Value, QualType SubobjType) {
6526     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6527     return false;
6528   }
found__anona656c3111411::DestroyObjectHandler6529   bool found(APFloat &Value, QualType SubobjType) {
6530     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6531     return false;
6532   }
6533 };
6534 }
6535 
6536 /// Perform a destructor or pseudo-destructor call on the given object, which
6537 /// might in general not be a complete object.
HandleDestruction(EvalInfo & Info,const Expr * E,const LValue & This,QualType ThisType)6538 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6539                               const LValue &This, QualType ThisType) {
6540   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6541   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6542   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6543 }
6544 
6545 /// Destroy and end the lifetime of the given complete object.
HandleDestruction(EvalInfo & Info,SourceLocation Loc,APValue::LValueBase LVBase,APValue & Value,QualType T)6546 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6547                               APValue::LValueBase LVBase, APValue &Value,
6548                               QualType T) {
6549   // If we've had an unmodeled side-effect, we can't rely on mutable state
6550   // (such as the object we're about to destroy) being correct.
6551   if (Info.EvalStatus.HasSideEffects)
6552     return false;
6553 
6554   LValue LV;
6555   LV.set({LVBase});
6556   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6557 }
6558 
6559 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
HandleOperatorNewCall(EvalInfo & Info,const CallExpr * E,LValue & Result)6560 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6561                                   LValue &Result) {
6562   if (Info.checkingPotentialConstantExpression() ||
6563       Info.SpeculativeEvaluationDepth)
6564     return false;
6565 
6566   // This is permitted only within a call to std::allocator<T>::allocate.
6567   auto Caller = Info.getStdAllocatorCaller("allocate");
6568   if (!Caller) {
6569     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6570                                      ? diag::note_constexpr_new_untyped
6571                                      : diag::note_constexpr_new);
6572     return false;
6573   }
6574 
6575   QualType ElemType = Caller.ElemType;
6576   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6577     Info.FFDiag(E->getExprLoc(),
6578                 diag::note_constexpr_new_not_complete_object_type)
6579         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6580     return false;
6581   }
6582 
6583   APSInt ByteSize;
6584   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6585     return false;
6586   bool IsNothrow = false;
6587   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6588     EvaluateIgnoredValue(Info, E->getArg(I));
6589     IsNothrow |= E->getType()->isNothrowT();
6590   }
6591 
6592   CharUnits ElemSize;
6593   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6594     return false;
6595   APInt Size, Remainder;
6596   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6597   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6598   if (Remainder != 0) {
6599     // This likely indicates a bug in the implementation of 'std::allocator'.
6600     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6601         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6602     return false;
6603   }
6604 
6605   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6606     if (IsNothrow) {
6607       Result.setNull(Info.Ctx, E->getType());
6608       return true;
6609     }
6610 
6611     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6612     return false;
6613   }
6614 
6615   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6616                                                      ArrayType::Normal, 0);
6617   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6618   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6619   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6620   return true;
6621 }
6622 
hasVirtualDestructor(QualType T)6623 static bool hasVirtualDestructor(QualType T) {
6624   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6625     if (CXXDestructorDecl *DD = RD->getDestructor())
6626       return DD->isVirtual();
6627   return false;
6628 }
6629 
getVirtualOperatorDelete(QualType T)6630 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6631   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6632     if (CXXDestructorDecl *DD = RD->getDestructor())
6633       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6634   return nullptr;
6635 }
6636 
6637 /// Check that the given object is a suitable pointer to a heap allocation that
6638 /// still exists and is of the right kind for the purpose of a deletion.
6639 ///
6640 /// On success, returns the heap allocation to deallocate. On failure, produces
6641 /// a diagnostic and returns None.
CheckDeleteKind(EvalInfo & Info,const Expr * E,const LValue & Pointer,DynAlloc::Kind DeallocKind)6642 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6643                                             const LValue &Pointer,
6644                                             DynAlloc::Kind DeallocKind) {
6645   auto PointerAsString = [&] {
6646     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6647   };
6648 
6649   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6650   if (!DA) {
6651     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6652         << PointerAsString();
6653     if (Pointer.Base)
6654       NoteLValueLocation(Info, Pointer.Base);
6655     return None;
6656   }
6657 
6658   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6659   if (!Alloc) {
6660     Info.FFDiag(E, diag::note_constexpr_double_delete);
6661     return None;
6662   }
6663 
6664   QualType AllocType = Pointer.Base.getDynamicAllocType();
6665   if (DeallocKind != (*Alloc)->getKind()) {
6666     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6667         << DeallocKind << (*Alloc)->getKind() << AllocType;
6668     NoteLValueLocation(Info, Pointer.Base);
6669     return None;
6670   }
6671 
6672   bool Subobject = false;
6673   if (DeallocKind == DynAlloc::New) {
6674     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6675                 Pointer.Designator.isOnePastTheEnd();
6676   } else {
6677     Subobject = Pointer.Designator.Entries.size() != 1 ||
6678                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6679   }
6680   if (Subobject) {
6681     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6682         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6683     return None;
6684   }
6685 
6686   return Alloc;
6687 }
6688 
6689 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
HandleOperatorDeleteCall(EvalInfo & Info,const CallExpr * E)6690 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6691   if (Info.checkingPotentialConstantExpression() ||
6692       Info.SpeculativeEvaluationDepth)
6693     return false;
6694 
6695   // This is permitted only within a call to std::allocator<T>::deallocate.
6696   if (!Info.getStdAllocatorCaller("deallocate")) {
6697     Info.FFDiag(E->getExprLoc());
6698     return true;
6699   }
6700 
6701   LValue Pointer;
6702   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6703     return false;
6704   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6705     EvaluateIgnoredValue(Info, E->getArg(I));
6706 
6707   if (Pointer.Designator.Invalid)
6708     return false;
6709 
6710   // Deleting a null pointer has no effect.
6711   if (Pointer.isNullPointer())
6712     return true;
6713 
6714   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6715     return false;
6716 
6717   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6718   return true;
6719 }
6720 
6721 //===----------------------------------------------------------------------===//
6722 // Generic Evaluation
6723 //===----------------------------------------------------------------------===//
6724 namespace {
6725 
6726 class BitCastBuffer {
6727   // FIXME: We're going to need bit-level granularity when we support
6728   // bit-fields.
6729   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6730   // we don't support a host or target where that is the case. Still, we should
6731   // use a more generic type in case we ever do.
6732   SmallVector<Optional<unsigned char>, 32> Bytes;
6733 
6734   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6735                 "Need at least 8 bit unsigned char");
6736 
6737   bool TargetIsLittleEndian;
6738 
6739 public:
BitCastBuffer(CharUnits Width,bool TargetIsLittleEndian)6740   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6741       : Bytes(Width.getQuantity()),
6742         TargetIsLittleEndian(TargetIsLittleEndian) {}
6743 
6744   LLVM_NODISCARD
readObject(CharUnits Offset,CharUnits Width,SmallVectorImpl<unsigned char> & Output) const6745   bool readObject(CharUnits Offset, CharUnits Width,
6746                   SmallVectorImpl<unsigned char> &Output) const {
6747     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6748       // If a byte of an integer is uninitialized, then the whole integer is
6749       // uninitalized.
6750       if (!Bytes[I.getQuantity()])
6751         return false;
6752       Output.push_back(*Bytes[I.getQuantity()]);
6753     }
6754     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6755       std::reverse(Output.begin(), Output.end());
6756     return true;
6757   }
6758 
writeObject(CharUnits Offset,SmallVectorImpl<unsigned char> & Input)6759   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6760     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6761       std::reverse(Input.begin(), Input.end());
6762 
6763     size_t Index = 0;
6764     for (unsigned char Byte : Input) {
6765       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6766       Bytes[Offset.getQuantity() + Index] = Byte;
6767       ++Index;
6768     }
6769   }
6770 
size()6771   size_t size() { return Bytes.size(); }
6772 };
6773 
6774 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6775 /// target would represent the value at runtime.
6776 class APValueToBufferConverter {
6777   EvalInfo &Info;
6778   BitCastBuffer Buffer;
6779   const CastExpr *BCE;
6780 
APValueToBufferConverter(EvalInfo & Info,CharUnits ObjectWidth,const CastExpr * BCE)6781   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6782                            const CastExpr *BCE)
6783       : Info(Info),
6784         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6785         BCE(BCE) {}
6786 
visit(const APValue & Val,QualType Ty)6787   bool visit(const APValue &Val, QualType Ty) {
6788     return visit(Val, Ty, CharUnits::fromQuantity(0));
6789   }
6790 
6791   // Write out Val with type Ty into Buffer starting at Offset.
visit(const APValue & Val,QualType Ty,CharUnits Offset)6792   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6793     assert((size_t)Offset.getQuantity() <= Buffer.size());
6794 
6795     // As a special case, nullptr_t has an indeterminate value.
6796     if (Ty->isNullPtrType())
6797       return true;
6798 
6799     // Dig through Src to find the byte at SrcOffset.
6800     switch (Val.getKind()) {
6801     case APValue::Indeterminate:
6802     case APValue::None:
6803       return true;
6804 
6805     case APValue::Int:
6806       return visitInt(Val.getInt(), Ty, Offset);
6807     case APValue::Float:
6808       return visitFloat(Val.getFloat(), Ty, Offset);
6809     case APValue::Array:
6810       return visitArray(Val, Ty, Offset);
6811     case APValue::Struct:
6812       return visitRecord(Val, Ty, Offset);
6813 
6814     case APValue::ComplexInt:
6815     case APValue::ComplexFloat:
6816     case APValue::Vector:
6817     case APValue::FixedPoint:
6818       // FIXME: We should support these.
6819 
6820     case APValue::Union:
6821     case APValue::MemberPointer:
6822     case APValue::AddrLabelDiff: {
6823       Info.FFDiag(BCE->getBeginLoc(),
6824                   diag::note_constexpr_bit_cast_unsupported_type)
6825           << Ty;
6826       return false;
6827     }
6828 
6829     case APValue::LValue:
6830       llvm_unreachable("LValue subobject in bit_cast?");
6831     }
6832     llvm_unreachable("Unhandled APValue::ValueKind");
6833   }
6834 
visitRecord(const APValue & Val,QualType Ty,CharUnits Offset)6835   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6836     const RecordDecl *RD = Ty->getAsRecordDecl();
6837     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6838 
6839     // Visit the base classes.
6840     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6841       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6842         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6843         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6844 
6845         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6846                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6847           return false;
6848       }
6849     }
6850 
6851     // Visit the fields.
6852     unsigned FieldIdx = 0;
6853     for (FieldDecl *FD : RD->fields()) {
6854       if (FD->isBitField()) {
6855         Info.FFDiag(BCE->getBeginLoc(),
6856                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6857         return false;
6858       }
6859 
6860       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6861 
6862       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6863              "only bit-fields can have sub-char alignment");
6864       CharUnits FieldOffset =
6865           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6866       QualType FieldTy = FD->getType();
6867       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6868         return false;
6869       ++FieldIdx;
6870     }
6871 
6872     return true;
6873   }
6874 
visitArray(const APValue & Val,QualType Ty,CharUnits Offset)6875   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6876     const auto *CAT =
6877         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6878     if (!CAT)
6879       return false;
6880 
6881     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6882     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6883     unsigned ArraySize = Val.getArraySize();
6884     // First, initialize the initialized elements.
6885     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6886       const APValue &SubObj = Val.getArrayInitializedElt(I);
6887       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6888         return false;
6889     }
6890 
6891     // Next, initialize the rest of the array using the filler.
6892     if (Val.hasArrayFiller()) {
6893       const APValue &Filler = Val.getArrayFiller();
6894       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6895         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6896           return false;
6897       }
6898     }
6899 
6900     return true;
6901   }
6902 
visitInt(const APSInt & Val,QualType Ty,CharUnits Offset)6903   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6904     APSInt AdjustedVal = Val;
6905     unsigned Width = AdjustedVal.getBitWidth();
6906     if (Ty->isBooleanType()) {
6907       Width = Info.Ctx.getTypeSize(Ty);
6908       AdjustedVal = AdjustedVal.extend(Width);
6909     }
6910 
6911     SmallVector<unsigned char, 8> Bytes(Width / 8);
6912     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6913     Buffer.writeObject(Offset, Bytes);
6914     return true;
6915   }
6916 
visitFloat(const APFloat & Val,QualType Ty,CharUnits Offset)6917   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6918     APSInt AsInt(Val.bitcastToAPInt());
6919     return visitInt(AsInt, Ty, Offset);
6920   }
6921 
6922 public:
convert(EvalInfo & Info,const APValue & Src,const CastExpr * BCE)6923   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6924                                          const CastExpr *BCE) {
6925     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6926     APValueToBufferConverter Converter(Info, DstSize, BCE);
6927     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6928       return None;
6929     return Converter.Buffer;
6930   }
6931 };
6932 
6933 /// Write an BitCastBuffer into an APValue.
6934 class BufferToAPValueConverter {
6935   EvalInfo &Info;
6936   const BitCastBuffer &Buffer;
6937   const CastExpr *BCE;
6938 
BufferToAPValueConverter(EvalInfo & Info,const BitCastBuffer & Buffer,const CastExpr * BCE)6939   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6940                            const CastExpr *BCE)
6941       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6942 
6943   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6944   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6945   // Ideally this will be unreachable.
unsupportedType(QualType Ty)6946   llvm::NoneType unsupportedType(QualType Ty) {
6947     Info.FFDiag(BCE->getBeginLoc(),
6948                 diag::note_constexpr_bit_cast_unsupported_type)
6949         << Ty;
6950     return None;
6951   }
6952 
unrepresentableValue(QualType Ty,const APSInt & Val)6953   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6954     Info.FFDiag(BCE->getBeginLoc(),
6955                 diag::note_constexpr_bit_cast_unrepresentable_value)
6956         << Ty << Val.toString(/*Radix=*/10);
6957     return None;
6958   }
6959 
visit(const BuiltinType * T,CharUnits Offset,const EnumType * EnumSugar=nullptr)6960   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6961                           const EnumType *EnumSugar = nullptr) {
6962     if (T->isNullPtrType()) {
6963       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6964       return APValue((Expr *)nullptr,
6965                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6966                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6967     }
6968 
6969     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6970 
6971     // Work around floating point types that contain unused padding bytes. This
6972     // is really just `long double` on x86, which is the only fundamental type
6973     // with padding bytes.
6974     if (T->isRealFloatingType()) {
6975       const llvm::fltSemantics &Semantics =
6976           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6977       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6978       assert(NumBits % 8 == 0);
6979       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6980       if (NumBytes != SizeOf)
6981         SizeOf = NumBytes;
6982     }
6983 
6984     SmallVector<uint8_t, 8> Bytes;
6985     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6986       // If this is std::byte or unsigned char, then its okay to store an
6987       // indeterminate value.
6988       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6989       bool IsUChar =
6990           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6991                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6992       if (!IsStdByte && !IsUChar) {
6993         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6994         Info.FFDiag(BCE->getExprLoc(),
6995                     diag::note_constexpr_bit_cast_indet_dest)
6996             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6997         return None;
6998       }
6999 
7000       return APValue::IndeterminateValue();
7001     }
7002 
7003     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7004     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7005 
7006     if (T->isIntegralOrEnumerationType()) {
7007       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7008 
7009       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7010       if (IntWidth != Val.getBitWidth()) {
7011         APSInt Truncated = Val.trunc(IntWidth);
7012         if (Truncated.extend(Val.getBitWidth()) != Val)
7013           return unrepresentableValue(QualType(T, 0), Val);
7014         Val = Truncated;
7015       }
7016 
7017       return APValue(Val);
7018     }
7019 
7020     if (T->isRealFloatingType()) {
7021       const llvm::fltSemantics &Semantics =
7022           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7023       return APValue(APFloat(Semantics, Val));
7024     }
7025 
7026     return unsupportedType(QualType(T, 0));
7027   }
7028 
visit(const RecordType * RTy,CharUnits Offset)7029   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7030     const RecordDecl *RD = RTy->getAsRecordDecl();
7031     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7032 
7033     unsigned NumBases = 0;
7034     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7035       NumBases = CXXRD->getNumBases();
7036 
7037     APValue ResultVal(APValue::UninitStruct(), NumBases,
7038                       std::distance(RD->field_begin(), RD->field_end()));
7039 
7040     // Visit the base classes.
7041     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7042       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7043         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7044         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7045         if (BaseDecl->isEmpty() ||
7046             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7047           continue;
7048 
7049         Optional<APValue> SubObj = visitType(
7050             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7051         if (!SubObj)
7052           return None;
7053         ResultVal.getStructBase(I) = *SubObj;
7054       }
7055     }
7056 
7057     // Visit the fields.
7058     unsigned FieldIdx = 0;
7059     for (FieldDecl *FD : RD->fields()) {
7060       // FIXME: We don't currently support bit-fields. A lot of the logic for
7061       // this is in CodeGen, so we need to factor it around.
7062       if (FD->isBitField()) {
7063         Info.FFDiag(BCE->getBeginLoc(),
7064                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7065         return None;
7066       }
7067 
7068       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7069       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7070 
7071       CharUnits FieldOffset =
7072           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7073           Offset;
7074       QualType FieldTy = FD->getType();
7075       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7076       if (!SubObj)
7077         return None;
7078       ResultVal.getStructField(FieldIdx) = *SubObj;
7079       ++FieldIdx;
7080     }
7081 
7082     return ResultVal;
7083   }
7084 
visit(const EnumType * Ty,CharUnits Offset)7085   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7086     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7087     assert(!RepresentationType.isNull() &&
7088            "enum forward decl should be caught by Sema");
7089     const auto *AsBuiltin =
7090         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7091     // Recurse into the underlying type. Treat std::byte transparently as
7092     // unsigned char.
7093     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7094   }
7095 
visit(const ConstantArrayType * Ty,CharUnits Offset)7096   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7097     size_t Size = Ty->getSize().getLimitedValue();
7098     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7099 
7100     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7101     for (size_t I = 0; I != Size; ++I) {
7102       Optional<APValue> ElementValue =
7103           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7104       if (!ElementValue)
7105         return None;
7106       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7107     }
7108 
7109     return ArrayValue;
7110   }
7111 
visit(const Type * Ty,CharUnits Offset)7112   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7113     return unsupportedType(QualType(Ty, 0));
7114   }
7115 
visitType(QualType Ty,CharUnits Offset)7116   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7117     QualType Can = Ty.getCanonicalType();
7118 
7119     switch (Can->getTypeClass()) {
7120 #define TYPE(Class, Base)                                                      \
7121   case Type::Class:                                                            \
7122     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7123 #define ABSTRACT_TYPE(Class, Base)
7124 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7125   case Type::Class:                                                            \
7126     llvm_unreachable("non-canonical type should be impossible!");
7127 #define DEPENDENT_TYPE(Class, Base)                                            \
7128   case Type::Class:                                                            \
7129     llvm_unreachable(                                                          \
7130         "dependent types aren't supported in the constant evaluator!");
7131 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7132   case Type::Class:                                                            \
7133     llvm_unreachable("either dependent or not canonical!");
7134 #include "clang/AST/TypeNodes.inc"
7135     }
7136     llvm_unreachable("Unhandled Type::TypeClass");
7137   }
7138 
7139 public:
7140   // Pull out a full value of type DstType.
convert(EvalInfo & Info,BitCastBuffer & Buffer,const CastExpr * BCE)7141   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7142                                    const CastExpr *BCE) {
7143     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7144     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7145   }
7146 };
7147 
checkBitCastConstexprEligibilityType(SourceLocation Loc,QualType Ty,EvalInfo * Info,const ASTContext & Ctx,bool CheckingDest)7148 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7149                                                  QualType Ty, EvalInfo *Info,
7150                                                  const ASTContext &Ctx,
7151                                                  bool CheckingDest) {
7152   Ty = Ty.getCanonicalType();
7153 
7154   auto diag = [&](int Reason) {
7155     if (Info)
7156       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7157           << CheckingDest << (Reason == 4) << Reason;
7158     return false;
7159   };
7160   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7161     if (Info)
7162       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7163           << NoteTy << Construct << Ty;
7164     return false;
7165   };
7166 
7167   if (Ty->isUnionType())
7168     return diag(0);
7169   if (Ty->isPointerType())
7170     return diag(1);
7171   if (Ty->isMemberPointerType())
7172     return diag(2);
7173   if (Ty.isVolatileQualified())
7174     return diag(3);
7175 
7176   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7177     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7178       for (CXXBaseSpecifier &BS : CXXRD->bases())
7179         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7180                                                   CheckingDest))
7181           return note(1, BS.getType(), BS.getBeginLoc());
7182     }
7183     for (FieldDecl *FD : Record->fields()) {
7184       if (FD->getType()->isReferenceType())
7185         return diag(4);
7186       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7187                                                 CheckingDest))
7188         return note(0, FD->getType(), FD->getBeginLoc());
7189     }
7190   }
7191 
7192   if (Ty->isArrayType() &&
7193       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7194                                             Info, Ctx, CheckingDest))
7195     return false;
7196 
7197   return true;
7198 }
7199 
checkBitCastConstexprEligibility(EvalInfo * Info,const ASTContext & Ctx,const CastExpr * BCE)7200 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7201                                              const ASTContext &Ctx,
7202                                              const CastExpr *BCE) {
7203   bool DestOK = checkBitCastConstexprEligibilityType(
7204       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7205   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7206                                 BCE->getBeginLoc(),
7207                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7208   return SourceOK;
7209 }
7210 
handleLValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,APValue & SourceValue,const CastExpr * BCE)7211 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7212                                         APValue &SourceValue,
7213                                         const CastExpr *BCE) {
7214   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7215          "no host or target supports non 8-bit chars");
7216   assert(SourceValue.isLValue() &&
7217          "LValueToRValueBitcast requires an lvalue operand!");
7218 
7219   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7220     return false;
7221 
7222   LValue SourceLValue;
7223   APValue SourceRValue;
7224   SourceLValue.setFrom(Info.Ctx, SourceValue);
7225   if (!handleLValueToRValueConversion(
7226           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7227           SourceRValue, /*WantObjectRepresentation=*/true))
7228     return false;
7229 
7230   // Read out SourceValue into a char buffer.
7231   Optional<BitCastBuffer> Buffer =
7232       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7233   if (!Buffer)
7234     return false;
7235 
7236   // Write out the buffer into a new APValue.
7237   Optional<APValue> MaybeDestValue =
7238       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7239   if (!MaybeDestValue)
7240     return false;
7241 
7242   DestValue = std::move(*MaybeDestValue);
7243   return true;
7244 }
7245 
7246 template <class Derived>
7247 class ExprEvaluatorBase
7248   : public ConstStmtVisitor<Derived, bool> {
7249 private:
getDerived()7250   Derived &getDerived() { return static_cast<Derived&>(*this); }
DerivedSuccess(const APValue & V,const Expr * E)7251   bool DerivedSuccess(const APValue &V, const Expr *E) {
7252     return getDerived().Success(V, E);
7253   }
DerivedZeroInitialization(const Expr * E)7254   bool DerivedZeroInitialization(const Expr *E) {
7255     return getDerived().ZeroInitialization(E);
7256   }
7257 
7258   // Check whether a conditional operator with a non-constant condition is a
7259   // potential constant expression. If neither arm is a potential constant
7260   // expression, then the conditional operator is not either.
7261   template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)7262   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7263     assert(Info.checkingPotentialConstantExpression());
7264 
7265     // Speculatively evaluate both arms.
7266     SmallVector<PartialDiagnosticAt, 8> Diag;
7267     {
7268       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7269       StmtVisitorTy::Visit(E->getFalseExpr());
7270       if (Diag.empty())
7271         return;
7272     }
7273 
7274     {
7275       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7276       Diag.clear();
7277       StmtVisitorTy::Visit(E->getTrueExpr());
7278       if (Diag.empty())
7279         return;
7280     }
7281 
7282     Error(E, diag::note_constexpr_conditional_never_const);
7283   }
7284 
7285 
7286   template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)7287   bool HandleConditionalOperator(const ConditionalOperator *E) {
7288     bool BoolResult;
7289     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7290       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7291         CheckPotentialConstantConditional(E);
7292         return false;
7293       }
7294       if (Info.noteFailure()) {
7295         StmtVisitorTy::Visit(E->getTrueExpr());
7296         StmtVisitorTy::Visit(E->getFalseExpr());
7297       }
7298       return false;
7299     }
7300 
7301     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7302     return StmtVisitorTy::Visit(EvalExpr);
7303   }
7304 
7305 protected:
7306   EvalInfo &Info;
7307   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7308   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7309 
CCEDiag(const Expr * E,diag::kind D)7310   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7311     return Info.CCEDiag(E, D);
7312   }
7313 
ZeroInitialization(const Expr * E)7314   bool ZeroInitialization(const Expr *E) { return Error(E); }
7315 
7316 public:
ExprEvaluatorBase(EvalInfo & Info)7317   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7318 
getEvalInfo()7319   EvalInfo &getEvalInfo() { return Info; }
7320 
7321   /// Report an evaluation error. This should only be called when an error is
7322   /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)7323   bool Error(const Expr *E, diag::kind D) {
7324     Info.FFDiag(E, D);
7325     return false;
7326   }
Error(const Expr * E)7327   bool Error(const Expr *E) {
7328     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7329   }
7330 
VisitStmt(const Stmt *)7331   bool VisitStmt(const Stmt *) {
7332     llvm_unreachable("Expression evaluator should not be called on stmts");
7333   }
VisitExpr(const Expr * E)7334   bool VisitExpr(const Expr *E) {
7335     return Error(E);
7336   }
7337 
VisitConstantExpr(const ConstantExpr * E)7338   bool VisitConstantExpr(const ConstantExpr *E) {
7339     if (E->hasAPValueResult())
7340       return DerivedSuccess(E->getAPValueResult(), E);
7341 
7342     return StmtVisitorTy::Visit(E->getSubExpr());
7343   }
7344 
VisitParenExpr(const ParenExpr * E)7345   bool VisitParenExpr(const ParenExpr *E)
7346     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)7347   bool VisitUnaryExtension(const UnaryOperator *E)
7348     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)7349   bool VisitUnaryPlus(const UnaryOperator *E)
7350     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)7351   bool VisitChooseExpr(const ChooseExpr *E)
7352     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)7353   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7354     { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)7355   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7356     { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)7357   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7358     TempVersionRAII RAII(*Info.CurrentCall);
7359     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7360     return StmtVisitorTy::Visit(E->getExpr());
7361   }
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * E)7362   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7363     TempVersionRAII RAII(*Info.CurrentCall);
7364     // The initializer may not have been parsed yet, or might be erroneous.
7365     if (!E->getExpr())
7366       return Error(E);
7367     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7368     return StmtVisitorTy::Visit(E->getExpr());
7369   }
7370 
VisitExprWithCleanups(const ExprWithCleanups * E)7371   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7372     FullExpressionRAII Scope(Info);
7373     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7374   }
7375 
7376   // Temporaries are registered when created, so we don't care about
7377   // CXXBindTemporaryExpr.
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)7378   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7379     return StmtVisitorTy::Visit(E->getSubExpr());
7380   }
7381 
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)7382   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7383     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7384     return static_cast<Derived*>(this)->VisitCastExpr(E);
7385   }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)7386   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7387     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7388       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7389     return static_cast<Derived*>(this)->VisitCastExpr(E);
7390   }
VisitBuiltinBitCastExpr(const BuiltinBitCastExpr * E)7391   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7392     return static_cast<Derived*>(this)->VisitCastExpr(E);
7393   }
7394 
VisitBinaryOperator(const BinaryOperator * E)7395   bool VisitBinaryOperator(const BinaryOperator *E) {
7396     switch (E->getOpcode()) {
7397     default:
7398       return Error(E);
7399 
7400     case BO_Comma:
7401       VisitIgnoredValue(E->getLHS());
7402       return StmtVisitorTy::Visit(E->getRHS());
7403 
7404     case BO_PtrMemD:
7405     case BO_PtrMemI: {
7406       LValue Obj;
7407       if (!HandleMemberPointerAccess(Info, E, Obj))
7408         return false;
7409       APValue Result;
7410       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7411         return false;
7412       return DerivedSuccess(Result, E);
7413     }
7414     }
7415   }
7416 
VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator * E)7417   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7418     return StmtVisitorTy::Visit(E->getSemanticForm());
7419   }
7420 
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)7421   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7422     // Evaluate and cache the common expression. We treat it as a temporary,
7423     // even though it's not quite the same thing.
7424     LValue CommonLV;
7425     if (!Evaluate(Info.CurrentCall->createTemporary(
7426                       E->getOpaqueValue(),
7427                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7428                       ScopeKind::FullExpression, CommonLV),
7429                   Info, E->getCommon()))
7430       return false;
7431 
7432     return HandleConditionalOperator(E);
7433   }
7434 
VisitConditionalOperator(const ConditionalOperator * E)7435   bool VisitConditionalOperator(const ConditionalOperator *E) {
7436     bool IsBcpCall = false;
7437     // If the condition (ignoring parens) is a __builtin_constant_p call,
7438     // the result is a constant expression if it can be folded without
7439     // side-effects. This is an important GNU extension. See GCC PR38377
7440     // for discussion.
7441     if (const CallExpr *CallCE =
7442           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7443       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7444         IsBcpCall = true;
7445 
7446     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7447     // constant expression; we can't check whether it's potentially foldable.
7448     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7449     // it would return 'false' in this mode.
7450     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7451       return false;
7452 
7453     FoldConstant Fold(Info, IsBcpCall);
7454     if (!HandleConditionalOperator(E)) {
7455       Fold.keepDiagnostics();
7456       return false;
7457     }
7458 
7459     return true;
7460   }
7461 
VisitOpaqueValueExpr(const OpaqueValueExpr * E)7462   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7463     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7464       return DerivedSuccess(*Value, E);
7465 
7466     const Expr *Source = E->getSourceExpr();
7467     if (!Source)
7468       return Error(E);
7469     if (Source == E) { // sanity checking.
7470       assert(0 && "OpaqueValueExpr recursively refers to itself");
7471       return Error(E);
7472     }
7473     return StmtVisitorTy::Visit(Source);
7474   }
7475 
VisitPseudoObjectExpr(const PseudoObjectExpr * E)7476   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7477     for (const Expr *SemE : E->semantics()) {
7478       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7479         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7480         // result expression: there could be two different LValues that would
7481         // refer to the same object in that case, and we can't model that.
7482         if (SemE == E->getResultExpr())
7483           return Error(E);
7484 
7485         // Unique OVEs get evaluated if and when we encounter them when
7486         // emitting the rest of the semantic form, rather than eagerly.
7487         if (OVE->isUnique())
7488           continue;
7489 
7490         LValue LV;
7491         if (!Evaluate(Info.CurrentCall->createTemporary(
7492                           OVE, getStorageType(Info.Ctx, OVE),
7493                           ScopeKind::FullExpression, LV),
7494                       Info, OVE->getSourceExpr()))
7495           return false;
7496       } else if (SemE == E->getResultExpr()) {
7497         if (!StmtVisitorTy::Visit(SemE))
7498           return false;
7499       } else {
7500         if (!EvaluateIgnoredValue(Info, SemE))
7501           return false;
7502       }
7503     }
7504     return true;
7505   }
7506 
VisitCallExpr(const CallExpr * E)7507   bool VisitCallExpr(const CallExpr *E) {
7508     APValue Result;
7509     if (!handleCallExpr(E, Result, nullptr))
7510       return false;
7511     return DerivedSuccess(Result, E);
7512   }
7513 
handleCallExpr(const CallExpr * E,APValue & Result,const LValue * ResultSlot)7514   bool handleCallExpr(const CallExpr *E, APValue &Result,
7515                      const LValue *ResultSlot) {
7516     CallScopeRAII CallScope(Info);
7517 
7518     const Expr *Callee = E->getCallee()->IgnoreParens();
7519     QualType CalleeType = Callee->getType();
7520 
7521     const FunctionDecl *FD = nullptr;
7522     LValue *This = nullptr, ThisVal;
7523     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7524     bool HasQualifier = false;
7525 
7526     CallRef Call;
7527 
7528     // Extract function decl and 'this' pointer from the callee.
7529     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7530       const CXXMethodDecl *Member = nullptr;
7531       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7532         // Explicit bound member calls, such as x.f() or p->g();
7533         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7534           return false;
7535         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7536         if (!Member)
7537           return Error(Callee);
7538         This = &ThisVal;
7539         HasQualifier = ME->hasQualifier();
7540       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7541         // Indirect bound member calls ('.*' or '->*').
7542         const ValueDecl *D =
7543             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7544         if (!D)
7545           return false;
7546         Member = dyn_cast<CXXMethodDecl>(D);
7547         if (!Member)
7548           return Error(Callee);
7549         This = &ThisVal;
7550       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7551         if (!Info.getLangOpts().CPlusPlus20)
7552           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7553         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7554                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7555       } else
7556         return Error(Callee);
7557       FD = Member;
7558     } else if (CalleeType->isFunctionPointerType()) {
7559       LValue CalleeLV;
7560       if (!EvaluatePointer(Callee, CalleeLV, Info))
7561         return false;
7562 
7563       if (!CalleeLV.getLValueOffset().isZero())
7564         return Error(Callee);
7565       FD = dyn_cast_or_null<FunctionDecl>(
7566           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7567       if (!FD)
7568         return Error(Callee);
7569       // Don't call function pointers which have been cast to some other type.
7570       // Per DR (no number yet), the caller and callee can differ in noexcept.
7571       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7572         CalleeType->getPointeeType(), FD->getType())) {
7573         return Error(E);
7574       }
7575 
7576       // For an (overloaded) assignment expression, evaluate the RHS before the
7577       // LHS.
7578       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7579       if (OCE && OCE->isAssignmentOp()) {
7580         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7581         Call = Info.CurrentCall->createCall(FD);
7582         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7583                           Info, FD, /*RightToLeft=*/true))
7584           return false;
7585       }
7586 
7587       // Overloaded operator calls to member functions are represented as normal
7588       // calls with '*this' as the first argument.
7589       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7590       if (MD && !MD->isStatic()) {
7591         // FIXME: When selecting an implicit conversion for an overloaded
7592         // operator delete, we sometimes try to evaluate calls to conversion
7593         // operators without a 'this' parameter!
7594         if (Args.empty())
7595           return Error(E);
7596 
7597         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7598           return false;
7599         This = &ThisVal;
7600         Args = Args.slice(1);
7601       } else if (MD && MD->isLambdaStaticInvoker()) {
7602         // Map the static invoker for the lambda back to the call operator.
7603         // Conveniently, we don't have to slice out the 'this' argument (as is
7604         // being done for the non-static case), since a static member function
7605         // doesn't have an implicit argument passed in.
7606         const CXXRecordDecl *ClosureClass = MD->getParent();
7607         assert(
7608             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7609             "Number of captures must be zero for conversion to function-ptr");
7610 
7611         const CXXMethodDecl *LambdaCallOp =
7612             ClosureClass->getLambdaCallOperator();
7613 
7614         // Set 'FD', the function that will be called below, to the call
7615         // operator.  If the closure object represents a generic lambda, find
7616         // the corresponding specialization of the call operator.
7617 
7618         if (ClosureClass->isGenericLambda()) {
7619           assert(MD->isFunctionTemplateSpecialization() &&
7620                  "A generic lambda's static-invoker function must be a "
7621                  "template specialization");
7622           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7623           FunctionTemplateDecl *CallOpTemplate =
7624               LambdaCallOp->getDescribedFunctionTemplate();
7625           void *InsertPos = nullptr;
7626           FunctionDecl *CorrespondingCallOpSpecialization =
7627               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7628           assert(CorrespondingCallOpSpecialization &&
7629                  "We must always have a function call operator specialization "
7630                  "that corresponds to our static invoker specialization");
7631           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7632         } else
7633           FD = LambdaCallOp;
7634       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7635         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7636             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7637           LValue Ptr;
7638           if (!HandleOperatorNewCall(Info, E, Ptr))
7639             return false;
7640           Ptr.moveInto(Result);
7641           return CallScope.destroy();
7642         } else {
7643           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7644         }
7645       }
7646     } else
7647       return Error(E);
7648 
7649     // Evaluate the arguments now if we've not already done so.
7650     if (!Call) {
7651       Call = Info.CurrentCall->createCall(FD);
7652       if (!EvaluateArgs(Args, Call, Info, FD))
7653         return false;
7654     }
7655 
7656     SmallVector<QualType, 4> CovariantAdjustmentPath;
7657     if (This) {
7658       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7659       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7660         // Perform virtual dispatch, if necessary.
7661         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7662                                    CovariantAdjustmentPath);
7663         if (!FD)
7664           return false;
7665       } else {
7666         // Check that the 'this' pointer points to an object of the right type.
7667         // FIXME: If this is an assignment operator call, we may need to change
7668         // the active union member before we check this.
7669         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7670           return false;
7671       }
7672     }
7673 
7674     // Destructor calls are different enough that they have their own codepath.
7675     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7676       assert(This && "no 'this' pointer for destructor call");
7677       return HandleDestruction(Info, E, *This,
7678                                Info.Ctx.getRecordType(DD->getParent())) &&
7679              CallScope.destroy();
7680     }
7681 
7682     const FunctionDecl *Definition = nullptr;
7683     Stmt *Body = FD->getBody(Definition);
7684 
7685     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7686         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7687                             Body, Info, Result, ResultSlot))
7688       return false;
7689 
7690     if (!CovariantAdjustmentPath.empty() &&
7691         !HandleCovariantReturnAdjustment(Info, E, Result,
7692                                          CovariantAdjustmentPath))
7693       return false;
7694 
7695     return CallScope.destroy();
7696   }
7697 
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)7698   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7699     return StmtVisitorTy::Visit(E->getInitializer());
7700   }
VisitInitListExpr(const InitListExpr * E)7701   bool VisitInitListExpr(const InitListExpr *E) {
7702     if (E->getNumInits() == 0)
7703       return DerivedZeroInitialization(E);
7704     if (E->getNumInits() == 1)
7705       return StmtVisitorTy::Visit(E->getInit(0));
7706     return Error(E);
7707   }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)7708   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7709     return DerivedZeroInitialization(E);
7710   }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)7711   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7712     return DerivedZeroInitialization(E);
7713   }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)7714   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7715     return DerivedZeroInitialization(E);
7716   }
7717 
7718   /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)7719   bool VisitMemberExpr(const MemberExpr *E) {
7720     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7721            "missing temporary materialization conversion");
7722     assert(!E->isArrow() && "missing call to bound member function?");
7723 
7724     APValue Val;
7725     if (!Evaluate(Val, Info, E->getBase()))
7726       return false;
7727 
7728     QualType BaseTy = E->getBase()->getType();
7729 
7730     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7731     if (!FD) return Error(E);
7732     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7733     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7734            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7735 
7736     // Note: there is no lvalue base here. But this case should only ever
7737     // happen in C or in C++98, where we cannot be evaluating a constexpr
7738     // constructor, which is the only case the base matters.
7739     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7740     SubobjectDesignator Designator(BaseTy);
7741     Designator.addDeclUnchecked(FD);
7742 
7743     APValue Result;
7744     return extractSubobject(Info, E, Obj, Designator, Result) &&
7745            DerivedSuccess(Result, E);
7746   }
7747 
VisitExtVectorElementExpr(const ExtVectorElementExpr * E)7748   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7749     APValue Val;
7750     if (!Evaluate(Val, Info, E->getBase()))
7751       return false;
7752 
7753     if (Val.isVector()) {
7754       SmallVector<uint32_t, 4> Indices;
7755       E->getEncodedElementAccess(Indices);
7756       if (Indices.size() == 1) {
7757         // Return scalar.
7758         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7759       } else {
7760         // Construct new APValue vector.
7761         SmallVector<APValue, 4> Elts;
7762         for (unsigned I = 0; I < Indices.size(); ++I) {
7763           Elts.push_back(Val.getVectorElt(Indices[I]));
7764         }
7765         APValue VecResult(Elts.data(), Indices.size());
7766         return DerivedSuccess(VecResult, E);
7767       }
7768     }
7769 
7770     return false;
7771   }
7772 
VisitCastExpr(const CastExpr * E)7773   bool VisitCastExpr(const CastExpr *E) {
7774     switch (E->getCastKind()) {
7775     default:
7776       break;
7777 
7778     case CK_AtomicToNonAtomic: {
7779       APValue AtomicVal;
7780       // This does not need to be done in place even for class/array types:
7781       // atomic-to-non-atomic conversion implies copying the object
7782       // representation.
7783       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7784         return false;
7785       return DerivedSuccess(AtomicVal, E);
7786     }
7787 
7788     case CK_NoOp:
7789     case CK_UserDefinedConversion:
7790       return StmtVisitorTy::Visit(E->getSubExpr());
7791 
7792     case CK_LValueToRValue: {
7793       LValue LVal;
7794       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7795         return false;
7796       APValue RVal;
7797       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7798       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7799                                           LVal, RVal))
7800         return false;
7801       return DerivedSuccess(RVal, E);
7802     }
7803     case CK_LValueToRValueBitCast: {
7804       APValue DestValue, SourceValue;
7805       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7806         return false;
7807       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7808         return false;
7809       return DerivedSuccess(DestValue, E);
7810     }
7811 
7812     case CK_AddressSpaceConversion: {
7813       APValue Value;
7814       if (!Evaluate(Value, Info, E->getSubExpr()))
7815         return false;
7816       return DerivedSuccess(Value, E);
7817     }
7818     }
7819 
7820     return Error(E);
7821   }
7822 
VisitUnaryPostInc(const UnaryOperator * UO)7823   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7824     return VisitUnaryPostIncDec(UO);
7825   }
VisitUnaryPostDec(const UnaryOperator * UO)7826   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7827     return VisitUnaryPostIncDec(UO);
7828   }
VisitUnaryPostIncDec(const UnaryOperator * UO)7829   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7830     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7831       return Error(UO);
7832 
7833     LValue LVal;
7834     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7835       return false;
7836     APValue RVal;
7837     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7838                       UO->isIncrementOp(), &RVal))
7839       return false;
7840     return DerivedSuccess(RVal, UO);
7841   }
7842 
VisitStmtExpr(const StmtExpr * E)7843   bool VisitStmtExpr(const StmtExpr *E) {
7844     // We will have checked the full-expressions inside the statement expression
7845     // when they were completed, and don't need to check them again now.
7846     if (Info.checkingForUndefinedBehavior())
7847       return Error(E);
7848 
7849     const CompoundStmt *CS = E->getSubStmt();
7850     if (CS->body_empty())
7851       return true;
7852 
7853     BlockScopeRAII Scope(Info);
7854     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7855                                            BE = CS->body_end();
7856          /**/; ++BI) {
7857       if (BI + 1 == BE) {
7858         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7859         if (!FinalExpr) {
7860           Info.FFDiag((*BI)->getBeginLoc(),
7861                       diag::note_constexpr_stmt_expr_unsupported);
7862           return false;
7863         }
7864         return this->Visit(FinalExpr) && Scope.destroy();
7865       }
7866 
7867       APValue ReturnValue;
7868       StmtResult Result = { ReturnValue, nullptr };
7869       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7870       if (ESR != ESR_Succeeded) {
7871         // FIXME: If the statement-expression terminated due to 'return',
7872         // 'break', or 'continue', it would be nice to propagate that to
7873         // the outer statement evaluation rather than bailing out.
7874         if (ESR != ESR_Failed)
7875           Info.FFDiag((*BI)->getBeginLoc(),
7876                       diag::note_constexpr_stmt_expr_unsupported);
7877         return false;
7878       }
7879     }
7880 
7881     llvm_unreachable("Return from function from the loop above.");
7882   }
7883 
7884   /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)7885   void VisitIgnoredValue(const Expr *E) {
7886     EvaluateIgnoredValue(Info, E);
7887   }
7888 
7889   /// Potentially visit a MemberExpr's base expression.
VisitIgnoredBaseExpression(const Expr * E)7890   void VisitIgnoredBaseExpression(const Expr *E) {
7891     // While MSVC doesn't evaluate the base expression, it does diagnose the
7892     // presence of side-effecting behavior.
7893     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7894       return;
7895     VisitIgnoredValue(E);
7896   }
7897 };
7898 
7899 } // namespace
7900 
7901 //===----------------------------------------------------------------------===//
7902 // Common base class for lvalue and temporary evaluation.
7903 //===----------------------------------------------------------------------===//
7904 namespace {
7905 template<class Derived>
7906 class LValueExprEvaluatorBase
7907   : public ExprEvaluatorBase<Derived> {
7908 protected:
7909   LValue &Result;
7910   bool InvalidBaseOK;
7911   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7912   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7913 
Success(APValue::LValueBase B)7914   bool Success(APValue::LValueBase B) {
7915     Result.set(B);
7916     return true;
7917   }
7918 
evaluatePointer(const Expr * E,LValue & Result)7919   bool evaluatePointer(const Expr *E, LValue &Result) {
7920     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7921   }
7922 
7923 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)7924   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7925       : ExprEvaluatorBaseTy(Info), Result(Result),
7926         InvalidBaseOK(InvalidBaseOK) {}
7927 
Success(const APValue & V,const Expr * E)7928   bool Success(const APValue &V, const Expr *E) {
7929     Result.setFrom(this->Info.Ctx, V);
7930     return true;
7931   }
7932 
VisitMemberExpr(const MemberExpr * E)7933   bool VisitMemberExpr(const MemberExpr *E) {
7934     // Handle non-static data members.
7935     QualType BaseTy;
7936     bool EvalOK;
7937     if (E->isArrow()) {
7938       EvalOK = evaluatePointer(E->getBase(), Result);
7939       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7940     } else if (E->getBase()->isRValue()) {
7941       assert(E->getBase()->getType()->isRecordType());
7942       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7943       BaseTy = E->getBase()->getType();
7944     } else {
7945       EvalOK = this->Visit(E->getBase());
7946       BaseTy = E->getBase()->getType();
7947     }
7948     if (!EvalOK) {
7949       if (!InvalidBaseOK)
7950         return false;
7951       Result.setInvalid(E);
7952       return true;
7953     }
7954 
7955     const ValueDecl *MD = E->getMemberDecl();
7956     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7957       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7958              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7959       (void)BaseTy;
7960       if (!HandleLValueMember(this->Info, E, Result, FD))
7961         return false;
7962     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7963       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7964         return false;
7965     } else
7966       return this->Error(E);
7967 
7968     if (MD->getType()->isReferenceType()) {
7969       APValue RefValue;
7970       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7971                                           RefValue))
7972         return false;
7973       return Success(RefValue, E);
7974     }
7975     return true;
7976   }
7977 
VisitBinaryOperator(const BinaryOperator * E)7978   bool VisitBinaryOperator(const BinaryOperator *E) {
7979     switch (E->getOpcode()) {
7980     default:
7981       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7982 
7983     case BO_PtrMemD:
7984     case BO_PtrMemI:
7985       return HandleMemberPointerAccess(this->Info, E, Result);
7986     }
7987   }
7988 
VisitCastExpr(const CastExpr * E)7989   bool VisitCastExpr(const CastExpr *E) {
7990     switch (E->getCastKind()) {
7991     default:
7992       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7993 
7994     case CK_DerivedToBase:
7995     case CK_UncheckedDerivedToBase:
7996       if (!this->Visit(E->getSubExpr()))
7997         return false;
7998 
7999       // Now figure out the necessary offset to add to the base LV to get from
8000       // the derived class to the base class.
8001       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8002                                   Result);
8003     }
8004   }
8005 };
8006 }
8007 
8008 //===----------------------------------------------------------------------===//
8009 // LValue Evaluation
8010 //
8011 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8012 // function designators (in C), decl references to void objects (in C), and
8013 // temporaries (if building with -Wno-address-of-temporary).
8014 //
8015 // LValue evaluation produces values comprising a base expression of one of the
8016 // following types:
8017 // - Declarations
8018 //  * VarDecl
8019 //  * FunctionDecl
8020 // - Literals
8021 //  * CompoundLiteralExpr in C (and in global scope in C++)
8022 //  * StringLiteral
8023 //  * PredefinedExpr
8024 //  * ObjCStringLiteralExpr
8025 //  * ObjCEncodeExpr
8026 //  * AddrLabelExpr
8027 //  * BlockExpr
8028 //  * CallExpr for a MakeStringConstant builtin
8029 // - typeid(T) expressions, as TypeInfoLValues
8030 // - Locals and temporaries
8031 //  * MaterializeTemporaryExpr
8032 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8033 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8034 //    from the AST (FIXME).
8035 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8036 //    CallIndex, for a lifetime-extended temporary.
8037 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8038 //    immediate invocation.
8039 // plus an offset in bytes.
8040 //===----------------------------------------------------------------------===//
8041 namespace {
8042 class LValueExprEvaluator
8043   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8044 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8045   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8046     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8047 
8048   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8049   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8050 
8051   bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)8052   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8053   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8054   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8055   bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)8056   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)8057   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8058   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8059   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8060   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8061   bool VisitUnaryDeref(const UnaryOperator *E);
8062   bool VisitUnaryReal(const UnaryOperator *E);
8063   bool VisitUnaryImag(const UnaryOperator *E);
VisitUnaryPreInc(const UnaryOperator * UO)8064   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8065     return VisitUnaryPreIncDec(UO);
8066   }
VisitUnaryPreDec(const UnaryOperator * UO)8067   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8068     return VisitUnaryPreIncDec(UO);
8069   }
8070   bool VisitBinAssign(const BinaryOperator *BO);
8071   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8072 
VisitCastExpr(const CastExpr * E)8073   bool VisitCastExpr(const CastExpr *E) {
8074     switch (E->getCastKind()) {
8075     default:
8076       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8077 
8078     case CK_LValueBitCast:
8079       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8080       if (!Visit(E->getSubExpr()))
8081         return false;
8082       Result.Designator.setInvalid();
8083       return true;
8084 
8085     case CK_BaseToDerived:
8086       if (!Visit(E->getSubExpr()))
8087         return false;
8088       return HandleBaseToDerivedCast(Info, E, Result);
8089 
8090     case CK_Dynamic:
8091       if (!Visit(E->getSubExpr()))
8092         return false;
8093       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8094     }
8095   }
8096 };
8097 } // end anonymous namespace
8098 
8099 /// Evaluate an expression as an lvalue. This can be legitimately called on
8100 /// expressions which are not glvalues, in three cases:
8101 ///  * function designators in C, and
8102 ///  * "extern void" objects
8103 ///  * @selector() expressions in Objective-C
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8104 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8105                            bool InvalidBaseOK) {
8106   assert(!E->isValueDependent());
8107   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8108          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8109   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8110 }
8111 
VisitDeclRefExpr(const DeclRefExpr * E)8112 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8113   const NamedDecl *D = E->getDecl();
8114   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8115     return Success(cast<ValueDecl>(D));
8116   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8117     return VisitVarDecl(E, VD);
8118   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8119     return Visit(BD->getBinding());
8120   return Error(E);
8121 }
8122 
8123 
VisitVarDecl(const Expr * E,const VarDecl * VD)8124 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8125 
8126   // If we are within a lambda's call operator, check whether the 'VD' referred
8127   // to within 'E' actually represents a lambda-capture that maps to a
8128   // data-member/field within the closure object, and if so, evaluate to the
8129   // field or what the field refers to.
8130   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8131       isa<DeclRefExpr>(E) &&
8132       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8133     // We don't always have a complete capture-map when checking or inferring if
8134     // the function call operator meets the requirements of a constexpr function
8135     // - but we don't need to evaluate the captures to determine constexprness
8136     // (dcl.constexpr C++17).
8137     if (Info.checkingPotentialConstantExpression())
8138       return false;
8139 
8140     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8141       // Start with 'Result' referring to the complete closure object...
8142       Result = *Info.CurrentCall->This;
8143       // ... then update it to refer to the field of the closure object
8144       // that represents the capture.
8145       if (!HandleLValueMember(Info, E, Result, FD))
8146         return false;
8147       // And if the field is of reference type, update 'Result' to refer to what
8148       // the field refers to.
8149       if (FD->getType()->isReferenceType()) {
8150         APValue RVal;
8151         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8152                                             RVal))
8153           return false;
8154         Result.setFrom(Info.Ctx, RVal);
8155       }
8156       return true;
8157     }
8158   }
8159 
8160   CallStackFrame *Frame = nullptr;
8161   unsigned Version = 0;
8162   if (VD->hasLocalStorage()) {
8163     // Only if a local variable was declared in the function currently being
8164     // evaluated, do we expect to be able to find its value in the current
8165     // frame. (Otherwise it was likely declared in an enclosing context and
8166     // could either have a valid evaluatable value (for e.g. a constexpr
8167     // variable) or be ill-formed (and trigger an appropriate evaluation
8168     // diagnostic)).
8169     CallStackFrame *CurrFrame = Info.CurrentCall;
8170     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8171       // Function parameters are stored in some caller's frame. (Usually the
8172       // immediate caller, but for an inherited constructor they may be more
8173       // distant.)
8174       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8175         if (CurrFrame->Arguments) {
8176           VD = CurrFrame->Arguments.getOrigParam(PVD);
8177           Frame =
8178               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8179           Version = CurrFrame->Arguments.Version;
8180         }
8181       } else {
8182         Frame = CurrFrame;
8183         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8184       }
8185     }
8186   }
8187 
8188   if (!VD->getType()->isReferenceType()) {
8189     if (Frame) {
8190       Result.set({VD, Frame->Index, Version});
8191       return true;
8192     }
8193     return Success(VD);
8194   }
8195 
8196   if (!Info.getLangOpts().CPlusPlus11) {
8197     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8198         << VD << VD->getType();
8199     Info.Note(VD->getLocation(), diag::note_declared_at);
8200   }
8201 
8202   APValue *V;
8203   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8204     return false;
8205   if (!V->hasValue()) {
8206     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8207     // adjust the diagnostic to say that.
8208     if (!Info.checkingPotentialConstantExpression())
8209       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8210     return false;
8211   }
8212   return Success(*V, E);
8213 }
8214 
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)8215 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8216     const MaterializeTemporaryExpr *E) {
8217   // Walk through the expression to find the materialized temporary itself.
8218   SmallVector<const Expr *, 2> CommaLHSs;
8219   SmallVector<SubobjectAdjustment, 2> Adjustments;
8220   const Expr *Inner =
8221       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8222 
8223   // If we passed any comma operators, evaluate their LHSs.
8224   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8225     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8226       return false;
8227 
8228   // A materialized temporary with static storage duration can appear within the
8229   // result of a constant expression evaluation, so we need to preserve its
8230   // value for use outside this evaluation.
8231   APValue *Value;
8232   if (E->getStorageDuration() == SD_Static) {
8233     // FIXME: What about SD_Thread?
8234     Value = E->getOrCreateValue(true);
8235     *Value = APValue();
8236     Result.set(E);
8237   } else {
8238     Value = &Info.CurrentCall->createTemporary(
8239         E, E->getType(),
8240         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8241                                                      : ScopeKind::Block,
8242         Result);
8243   }
8244 
8245   QualType Type = Inner->getType();
8246 
8247   // Materialize the temporary itself.
8248   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8249     *Value = APValue();
8250     return false;
8251   }
8252 
8253   // Adjust our lvalue to refer to the desired subobject.
8254   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8255     --I;
8256     switch (Adjustments[I].Kind) {
8257     case SubobjectAdjustment::DerivedToBaseAdjustment:
8258       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8259                                 Type, Result))
8260         return false;
8261       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8262       break;
8263 
8264     case SubobjectAdjustment::FieldAdjustment:
8265       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8266         return false;
8267       Type = Adjustments[I].Field->getType();
8268       break;
8269 
8270     case SubobjectAdjustment::MemberPointerAdjustment:
8271       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8272                                      Adjustments[I].Ptr.RHS))
8273         return false;
8274       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8275       break;
8276     }
8277   }
8278 
8279   return true;
8280 }
8281 
8282 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)8283 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8284   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8285          "lvalue compound literal in c++?");
8286   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8287   // only see this when folding in C, so there's no standard to follow here.
8288   return Success(E);
8289 }
8290 
VisitCXXTypeidExpr(const CXXTypeidExpr * E)8291 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8292   TypeInfoLValue TypeInfo;
8293 
8294   if (!E->isPotentiallyEvaluated()) {
8295     if (E->isTypeOperand())
8296       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8297     else
8298       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8299   } else {
8300     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8301       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8302         << E->getExprOperand()->getType()
8303         << E->getExprOperand()->getSourceRange();
8304     }
8305 
8306     if (!Visit(E->getExprOperand()))
8307       return false;
8308 
8309     Optional<DynamicType> DynType =
8310         ComputeDynamicType(Info, E, Result, AK_TypeId);
8311     if (!DynType)
8312       return false;
8313 
8314     TypeInfo =
8315         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8316   }
8317 
8318   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8319 }
8320 
VisitCXXUuidofExpr(const CXXUuidofExpr * E)8321 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8322   return Success(E->getGuidDecl());
8323 }
8324 
VisitMemberExpr(const MemberExpr * E)8325 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8326   // Handle static data members.
8327   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8328     VisitIgnoredBaseExpression(E->getBase());
8329     return VisitVarDecl(E, VD);
8330   }
8331 
8332   // Handle static member functions.
8333   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8334     if (MD->isStatic()) {
8335       VisitIgnoredBaseExpression(E->getBase());
8336       return Success(MD);
8337     }
8338   }
8339 
8340   // Handle non-static data members.
8341   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8342 }
8343 
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)8344 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8345   // FIXME: Deal with vectors as array subscript bases.
8346   if (E->getBase()->getType()->isVectorType())
8347     return Error(E);
8348 
8349   APSInt Index;
8350   bool Success = true;
8351 
8352   // C++17's rules require us to evaluate the LHS first, regardless of which
8353   // side is the base.
8354   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8355     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8356                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8357       if (!Info.noteFailure())
8358         return false;
8359       Success = false;
8360     }
8361   }
8362 
8363   return Success &&
8364          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8365 }
8366 
VisitUnaryDeref(const UnaryOperator * E)8367 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8368   return evaluatePointer(E->getSubExpr(), Result);
8369 }
8370 
VisitUnaryReal(const UnaryOperator * E)8371 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8372   if (!Visit(E->getSubExpr()))
8373     return false;
8374   // __real is a no-op on scalar lvalues.
8375   if (E->getSubExpr()->getType()->isAnyComplexType())
8376     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8377   return true;
8378 }
8379 
VisitUnaryImag(const UnaryOperator * E)8380 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8381   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8382          "lvalue __imag__ on scalar?");
8383   if (!Visit(E->getSubExpr()))
8384     return false;
8385   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8386   return true;
8387 }
8388 
VisitUnaryPreIncDec(const UnaryOperator * UO)8389 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8390   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8391     return Error(UO);
8392 
8393   if (!this->Visit(UO->getSubExpr()))
8394     return false;
8395 
8396   return handleIncDec(
8397       this->Info, UO, Result, UO->getSubExpr()->getType(),
8398       UO->isIncrementOp(), nullptr);
8399 }
8400 
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)8401 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8402     const CompoundAssignOperator *CAO) {
8403   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8404     return Error(CAO);
8405 
8406   bool Success = true;
8407 
8408   // C++17 onwards require that we evaluate the RHS first.
8409   APValue RHS;
8410   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8411     if (!Info.noteFailure())
8412       return false;
8413     Success = false;
8414   }
8415 
8416   // The overall lvalue result is the result of evaluating the LHS.
8417   if (!this->Visit(CAO->getLHS()) || !Success)
8418     return false;
8419 
8420   return handleCompoundAssignment(
8421       this->Info, CAO,
8422       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8423       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8424 }
8425 
VisitBinAssign(const BinaryOperator * E)8426 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8427   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8428     return Error(E);
8429 
8430   bool Success = true;
8431 
8432   // C++17 onwards require that we evaluate the RHS first.
8433   APValue NewVal;
8434   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8435     if (!Info.noteFailure())
8436       return false;
8437     Success = false;
8438   }
8439 
8440   if (!this->Visit(E->getLHS()) || !Success)
8441     return false;
8442 
8443   if (Info.getLangOpts().CPlusPlus20 &&
8444       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8445     return false;
8446 
8447   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8448                           NewVal);
8449 }
8450 
8451 //===----------------------------------------------------------------------===//
8452 // Pointer Evaluation
8453 //===----------------------------------------------------------------------===//
8454 
8455 /// Attempts to compute the number of bytes available at the pointer
8456 /// returned by a function with the alloc_size attribute. Returns true if we
8457 /// were successful. Places an unsigned number into `Result`.
8458 ///
8459 /// This expects the given CallExpr to be a call to a function with an
8460 /// alloc_size attribute.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const CallExpr * Call,llvm::APInt & Result)8461 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8462                                             const CallExpr *Call,
8463                                             llvm::APInt &Result) {
8464   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8465 
8466   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8467   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8468   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8469   if (Call->getNumArgs() <= SizeArgNo)
8470     return false;
8471 
8472   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8473     Expr::EvalResult ExprResult;
8474     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8475       return false;
8476     Into = ExprResult.Val.getInt();
8477     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8478       return false;
8479     Into = Into.zextOrSelf(BitsInSizeT);
8480     return true;
8481   };
8482 
8483   APSInt SizeOfElem;
8484   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8485     return false;
8486 
8487   if (!AllocSize->getNumElemsParam().isValid()) {
8488     Result = std::move(SizeOfElem);
8489     return true;
8490   }
8491 
8492   APSInt NumberOfElems;
8493   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8494   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8495     return false;
8496 
8497   bool Overflow;
8498   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8499   if (Overflow)
8500     return false;
8501 
8502   Result = std::move(BytesAvailable);
8503   return true;
8504 }
8505 
8506 /// Convenience function. LVal's base must be a call to an alloc_size
8507 /// function.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const LValue & LVal,llvm::APInt & Result)8508 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8509                                             const LValue &LVal,
8510                                             llvm::APInt &Result) {
8511   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8512          "Can't get the size of a non alloc_size function");
8513   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8514   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8515   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8516 }
8517 
8518 /// Attempts to evaluate the given LValueBase as the result of a call to
8519 /// a function with the alloc_size attribute. If it was possible to do so, this
8520 /// function will return true, make Result's Base point to said function call,
8521 /// and mark Result's Base as invalid.
evaluateLValueAsAllocSize(EvalInfo & Info,APValue::LValueBase Base,LValue & Result)8522 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8523                                       LValue &Result) {
8524   if (Base.isNull())
8525     return false;
8526 
8527   // Because we do no form of static analysis, we only support const variables.
8528   //
8529   // Additionally, we can't support parameters, nor can we support static
8530   // variables (in the latter case, use-before-assign isn't UB; in the former,
8531   // we have no clue what they'll be assigned to).
8532   const auto *VD =
8533       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8534   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8535     return false;
8536 
8537   const Expr *Init = VD->getAnyInitializer();
8538   if (!Init)
8539     return false;
8540 
8541   const Expr *E = Init->IgnoreParens();
8542   if (!tryUnwrapAllocSizeCall(E))
8543     return false;
8544 
8545   // Store E instead of E unwrapped so that the type of the LValue's base is
8546   // what the user wanted.
8547   Result.setInvalid(E);
8548 
8549   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8550   Result.addUnsizedArray(Info, E, Pointee);
8551   return true;
8552 }
8553 
8554 namespace {
8555 class PointerExprEvaluator
8556   : public ExprEvaluatorBase<PointerExprEvaluator> {
8557   LValue &Result;
8558   bool InvalidBaseOK;
8559 
Success(const Expr * E)8560   bool Success(const Expr *E) {
8561     Result.set(E);
8562     return true;
8563   }
8564 
evaluateLValue(const Expr * E,LValue & Result)8565   bool evaluateLValue(const Expr *E, LValue &Result) {
8566     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8567   }
8568 
evaluatePointer(const Expr * E,LValue & Result)8569   bool evaluatePointer(const Expr *E, LValue &Result) {
8570     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8571   }
8572 
8573   bool visitNonBuiltinCallExpr(const CallExpr *E);
8574 public:
8575 
PointerExprEvaluator(EvalInfo & info,LValue & Result,bool InvalidBaseOK)8576   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8577       : ExprEvaluatorBaseTy(info), Result(Result),
8578         InvalidBaseOK(InvalidBaseOK) {}
8579 
Success(const APValue & V,const Expr * E)8580   bool Success(const APValue &V, const Expr *E) {
8581     Result.setFrom(Info.Ctx, V);
8582     return true;
8583   }
ZeroInitialization(const Expr * E)8584   bool ZeroInitialization(const Expr *E) {
8585     Result.setNull(Info.Ctx, E->getType());
8586     return true;
8587   }
8588 
8589   bool VisitBinaryOperator(const BinaryOperator *E);
8590   bool VisitCastExpr(const CastExpr* E);
8591   bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)8592   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8593       { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)8594   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8595     if (E->isExpressibleAsConstantInitializer())
8596       return Success(E);
8597     if (Info.noteFailure())
8598       EvaluateIgnoredValue(Info, E->getSubExpr());
8599     return Error(E);
8600   }
VisitAddrLabelExpr(const AddrLabelExpr * E)8601   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8602       { return Success(E); }
8603   bool VisitCallExpr(const CallExpr *E);
8604   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
VisitBlockExpr(const BlockExpr * E)8605   bool VisitBlockExpr(const BlockExpr *E) {
8606     if (!E->getBlockDecl()->hasCaptures())
8607       return Success(E);
8608     return Error(E);
8609   }
VisitCXXThisExpr(const CXXThisExpr * E)8610   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8611     // Can't look at 'this' when checking a potential constant expression.
8612     if (Info.checkingPotentialConstantExpression())
8613       return false;
8614     if (!Info.CurrentCall->This) {
8615       if (Info.getLangOpts().CPlusPlus11)
8616         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8617       else
8618         Info.FFDiag(E);
8619       return false;
8620     }
8621     Result = *Info.CurrentCall->This;
8622     // If we are inside a lambda's call operator, the 'this' expression refers
8623     // to the enclosing '*this' object (either by value or reference) which is
8624     // either copied into the closure object's field that represents the '*this'
8625     // or refers to '*this'.
8626     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8627       // Ensure we actually have captured 'this'. (an error will have
8628       // been previously reported if not).
8629       if (!Info.CurrentCall->LambdaThisCaptureField)
8630         return false;
8631 
8632       // Update 'Result' to refer to the data member/field of the closure object
8633       // that represents the '*this' capture.
8634       if (!HandleLValueMember(Info, E, Result,
8635                              Info.CurrentCall->LambdaThisCaptureField))
8636         return false;
8637       // If we captured '*this' by reference, replace the field with its referent.
8638       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8639               ->isPointerType()) {
8640         APValue RVal;
8641         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8642                                             RVal))
8643           return false;
8644 
8645         Result.setFrom(Info.Ctx, RVal);
8646       }
8647     }
8648     return true;
8649   }
8650 
8651   bool VisitCXXNewExpr(const CXXNewExpr *E);
8652 
VisitSourceLocExpr(const SourceLocExpr * E)8653   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8654     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8655     APValue LValResult = E->EvaluateInContext(
8656         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8657     Result.setFrom(Info.Ctx, LValResult);
8658     return true;
8659   }
8660 
8661   // FIXME: Missing: @protocol, @selector
8662 };
8663 } // end anonymous namespace
8664 
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8665 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8666                             bool InvalidBaseOK) {
8667   assert(!E->isValueDependent());
8668   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8669   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8670 }
8671 
VisitBinaryOperator(const BinaryOperator * E)8672 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8673   if (E->getOpcode() != BO_Add &&
8674       E->getOpcode() != BO_Sub)
8675     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8676 
8677   const Expr *PExp = E->getLHS();
8678   const Expr *IExp = E->getRHS();
8679   if (IExp->getType()->isPointerType())
8680     std::swap(PExp, IExp);
8681 
8682   bool EvalPtrOK = evaluatePointer(PExp, Result);
8683   if (!EvalPtrOK && !Info.noteFailure())
8684     return false;
8685 
8686   llvm::APSInt Offset;
8687   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8688     return false;
8689 
8690   if (E->getOpcode() == BO_Sub)
8691     negateAsSigned(Offset);
8692 
8693   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8694   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8695 }
8696 
VisitUnaryAddrOf(const UnaryOperator * E)8697 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8698   return evaluateLValue(E->getSubExpr(), Result);
8699 }
8700 
VisitCastExpr(const CastExpr * E)8701 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8702   const Expr *SubExpr = E->getSubExpr();
8703 
8704   switch (E->getCastKind()) {
8705   default:
8706     break;
8707   case CK_BitCast:
8708   case CK_CPointerToObjCPointerCast:
8709   case CK_BlockPointerToObjCPointerCast:
8710   case CK_AnyPointerToBlockPointerCast:
8711   case CK_AddressSpaceConversion:
8712     if (!Visit(SubExpr))
8713       return false;
8714     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8715     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8716     // also static_casts, but we disallow them as a resolution to DR1312.
8717     if (!E->getType()->isVoidPointerType()) {
8718       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8719           !Result.IsNullPtr &&
8720           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8721                                           E->getType()->getPointeeType()) &&
8722           Info.getStdAllocatorCaller("allocate")) {
8723         // Inside a call to std::allocator::allocate and friends, we permit
8724         // casting from void* back to cv1 T* for a pointer that points to a
8725         // cv2 T.
8726       } else {
8727         Result.Designator.setInvalid();
8728         if (SubExpr->getType()->isVoidPointerType())
8729           CCEDiag(E, diag::note_constexpr_invalid_cast)
8730             << 3 << SubExpr->getType();
8731         else
8732           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8733       }
8734     }
8735     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8736       ZeroInitialization(E);
8737     return true;
8738 
8739   case CK_DerivedToBase:
8740   case CK_UncheckedDerivedToBase:
8741     if (!evaluatePointer(E->getSubExpr(), Result))
8742       return false;
8743     if (!Result.Base && Result.Offset.isZero())
8744       return true;
8745 
8746     // Now figure out the necessary offset to add to the base LV to get from
8747     // the derived class to the base class.
8748     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8749                                   castAs<PointerType>()->getPointeeType(),
8750                                 Result);
8751 
8752   case CK_BaseToDerived:
8753     if (!Visit(E->getSubExpr()))
8754       return false;
8755     if (!Result.Base && Result.Offset.isZero())
8756       return true;
8757     return HandleBaseToDerivedCast(Info, E, Result);
8758 
8759   case CK_Dynamic:
8760     if (!Visit(E->getSubExpr()))
8761       return false;
8762     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8763 
8764   case CK_NullToPointer:
8765     VisitIgnoredValue(E->getSubExpr());
8766     return ZeroInitialization(E);
8767 
8768   case CK_IntegralToPointer: {
8769     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8770 
8771     APValue Value;
8772     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8773       break;
8774 
8775     if (Value.isInt()) {
8776       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8777       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8778       Result.Base = (Expr*)nullptr;
8779       Result.InvalidBase = false;
8780       Result.Offset = CharUnits::fromQuantity(N);
8781       Result.Designator.setInvalid();
8782       Result.IsNullPtr = false;
8783       return true;
8784     } else {
8785       // Cast is of an lvalue, no need to change value.
8786       Result.setFrom(Info.Ctx, Value);
8787       return true;
8788     }
8789   }
8790 
8791   case CK_ArrayToPointerDecay: {
8792     if (SubExpr->isGLValue()) {
8793       if (!evaluateLValue(SubExpr, Result))
8794         return false;
8795     } else {
8796       APValue &Value = Info.CurrentCall->createTemporary(
8797           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8798       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8799         return false;
8800     }
8801     // The result is a pointer to the first element of the array.
8802     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8803     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8804       Result.addArray(Info, E, CAT);
8805     else
8806       Result.addUnsizedArray(Info, E, AT->getElementType());
8807     return true;
8808   }
8809 
8810   case CK_FunctionToPointerDecay:
8811     return evaluateLValue(SubExpr, Result);
8812 
8813   case CK_LValueToRValue: {
8814     LValue LVal;
8815     if (!evaluateLValue(E->getSubExpr(), LVal))
8816       return false;
8817 
8818     APValue RVal;
8819     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8820     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8821                                         LVal, RVal))
8822       return InvalidBaseOK &&
8823              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8824     return Success(RVal, E);
8825   }
8826   }
8827 
8828   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8829 }
8830 
GetAlignOfType(EvalInfo & Info,QualType T,UnaryExprOrTypeTrait ExprKind)8831 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8832                                 UnaryExprOrTypeTrait ExprKind) {
8833   // C++ [expr.alignof]p3:
8834   //     When alignof is applied to a reference type, the result is the
8835   //     alignment of the referenced type.
8836   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8837     T = Ref->getPointeeType();
8838 
8839   if (T.getQualifiers().hasUnaligned())
8840     return CharUnits::One();
8841 
8842   const bool AlignOfReturnsPreferred =
8843       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8844 
8845   // __alignof is defined to return the preferred alignment.
8846   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8847   // as well.
8848   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8849     return Info.Ctx.toCharUnitsFromBits(
8850       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8851   // alignof and _Alignof are defined to return the ABI alignment.
8852   else if (ExprKind == UETT_AlignOf)
8853     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8854   else
8855     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8856 }
8857 
GetAlignOfExpr(EvalInfo & Info,const Expr * E,UnaryExprOrTypeTrait ExprKind)8858 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8859                                 UnaryExprOrTypeTrait ExprKind) {
8860   E = E->IgnoreParens();
8861 
8862   // The kinds of expressions that we have special-case logic here for
8863   // should be kept up to date with the special checks for those
8864   // expressions in Sema.
8865 
8866   // alignof decl is always accepted, even if it doesn't make sense: we default
8867   // to 1 in those cases.
8868   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8869     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8870                                  /*RefAsPointee*/true);
8871 
8872   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8873     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8874                                  /*RefAsPointee*/true);
8875 
8876   return GetAlignOfType(Info, E->getType(), ExprKind);
8877 }
8878 
getBaseAlignment(EvalInfo & Info,const LValue & Value)8879 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8880   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8881     return Info.Ctx.getDeclAlign(VD);
8882   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8883     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8884   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8885 }
8886 
8887 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8888 /// __builtin_is_aligned and __builtin_assume_aligned.
getAlignmentArgument(const Expr * E,QualType ForType,EvalInfo & Info,APSInt & Alignment)8889 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8890                                  EvalInfo &Info, APSInt &Alignment) {
8891   if (!EvaluateInteger(E, Alignment, Info))
8892     return false;
8893   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8894     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8895     return false;
8896   }
8897   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8898   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8899   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8900     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8901         << MaxValue << ForType << Alignment;
8902     return false;
8903   }
8904   // Ensure both alignment and source value have the same bit width so that we
8905   // don't assert when computing the resulting value.
8906   APSInt ExtAlignment =
8907       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8908   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8909          "Alignment should not be changed by ext/trunc");
8910   Alignment = ExtAlignment;
8911   assert(Alignment.getBitWidth() == SrcWidth);
8912   return true;
8913 }
8914 
8915 // To be clear: this happily visits unsupported builtins. Better name welcomed.
visitNonBuiltinCallExpr(const CallExpr * E)8916 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8917   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8918     return true;
8919 
8920   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8921     return false;
8922 
8923   Result.setInvalid(E);
8924   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8925   Result.addUnsizedArray(Info, E, PointeeTy);
8926   return true;
8927 }
8928 
VisitCallExpr(const CallExpr * E)8929 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8930   if (IsStringLiteralCall(E))
8931     return Success(E);
8932 
8933   if (unsigned BuiltinOp = E->getBuiltinCallee())
8934     return VisitBuiltinCallExpr(E, BuiltinOp);
8935 
8936   return visitNonBuiltinCallExpr(E);
8937 }
8938 
8939 // Determine if T is a character type for which we guarantee that
8940 // sizeof(T) == 1.
isOneByteCharacterType(QualType T)8941 static bool isOneByteCharacterType(QualType T) {
8942   return T->isCharType() || T->isChar8Type();
8943 }
8944 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)8945 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8946                                                 unsigned BuiltinOp) {
8947   switch (BuiltinOp) {
8948   case Builtin::BI__builtin_addressof:
8949     return evaluateLValue(E->getArg(0), Result);
8950   case Builtin::BI__builtin_assume_aligned: {
8951     // We need to be very careful here because: if the pointer does not have the
8952     // asserted alignment, then the behavior is undefined, and undefined
8953     // behavior is non-constant.
8954     if (!evaluatePointer(E->getArg(0), Result))
8955       return false;
8956 
8957     LValue OffsetResult(Result);
8958     APSInt Alignment;
8959     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8960                               Alignment))
8961       return false;
8962     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8963 
8964     if (E->getNumArgs() > 2) {
8965       APSInt Offset;
8966       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8967         return false;
8968 
8969       int64_t AdditionalOffset = -Offset.getZExtValue();
8970       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8971     }
8972 
8973     // If there is a base object, then it must have the correct alignment.
8974     if (OffsetResult.Base) {
8975       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8976 
8977       if (BaseAlignment < Align) {
8978         Result.Designator.setInvalid();
8979         // FIXME: Add support to Diagnostic for long / long long.
8980         CCEDiag(E->getArg(0),
8981                 diag::note_constexpr_baa_insufficient_alignment) << 0
8982           << (unsigned)BaseAlignment.getQuantity()
8983           << (unsigned)Align.getQuantity();
8984         return false;
8985       }
8986     }
8987 
8988     // The offset must also have the correct alignment.
8989     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8990       Result.Designator.setInvalid();
8991 
8992       (OffsetResult.Base
8993            ? CCEDiag(E->getArg(0),
8994                      diag::note_constexpr_baa_insufficient_alignment) << 1
8995            : CCEDiag(E->getArg(0),
8996                      diag::note_constexpr_baa_value_insufficient_alignment))
8997         << (int)OffsetResult.Offset.getQuantity()
8998         << (unsigned)Align.getQuantity();
8999       return false;
9000     }
9001 
9002     return true;
9003   }
9004   case Builtin::BI__builtin_align_up:
9005   case Builtin::BI__builtin_align_down: {
9006     if (!evaluatePointer(E->getArg(0), Result))
9007       return false;
9008     APSInt Alignment;
9009     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9010                               Alignment))
9011       return false;
9012     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9013     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9014     // For align_up/align_down, we can return the same value if the alignment
9015     // is known to be greater or equal to the requested value.
9016     if (PtrAlign.getQuantity() >= Alignment)
9017       return true;
9018 
9019     // The alignment could be greater than the minimum at run-time, so we cannot
9020     // infer much about the resulting pointer value. One case is possible:
9021     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9022     // can infer the correct index if the requested alignment is smaller than
9023     // the base alignment so we can perform the computation on the offset.
9024     if (BaseAlignment.getQuantity() >= Alignment) {
9025       assert(Alignment.getBitWidth() <= 64 &&
9026              "Cannot handle > 64-bit address-space");
9027       uint64_t Alignment64 = Alignment.getZExtValue();
9028       CharUnits NewOffset = CharUnits::fromQuantity(
9029           BuiltinOp == Builtin::BI__builtin_align_down
9030               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9031               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9032       Result.adjustOffset(NewOffset - Result.Offset);
9033       // TODO: diagnose out-of-bounds values/only allow for arrays?
9034       return true;
9035     }
9036     // Otherwise, we cannot constant-evaluate the result.
9037     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9038         << Alignment;
9039     return false;
9040   }
9041   case Builtin::BI__builtin_operator_new:
9042     return HandleOperatorNewCall(Info, E, Result);
9043   case Builtin::BI__builtin_launder:
9044     return evaluatePointer(E->getArg(0), Result);
9045   case Builtin::BIstrchr:
9046   case Builtin::BIwcschr:
9047   case Builtin::BImemchr:
9048   case Builtin::BIwmemchr:
9049     if (Info.getLangOpts().CPlusPlus11)
9050       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9051         << /*isConstexpr*/0 << /*isConstructor*/0
9052         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9053     else
9054       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9055     LLVM_FALLTHROUGH;
9056   case Builtin::BI__builtin_strchr:
9057   case Builtin::BI__builtin_wcschr:
9058   case Builtin::BI__builtin_memchr:
9059   case Builtin::BI__builtin_char_memchr:
9060   case Builtin::BI__builtin_wmemchr: {
9061     if (!Visit(E->getArg(0)))
9062       return false;
9063     APSInt Desired;
9064     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9065       return false;
9066     uint64_t MaxLength = uint64_t(-1);
9067     if (BuiltinOp != Builtin::BIstrchr &&
9068         BuiltinOp != Builtin::BIwcschr &&
9069         BuiltinOp != Builtin::BI__builtin_strchr &&
9070         BuiltinOp != Builtin::BI__builtin_wcschr) {
9071       APSInt N;
9072       if (!EvaluateInteger(E->getArg(2), N, Info))
9073         return false;
9074       MaxLength = N.getExtValue();
9075     }
9076     // We cannot find the value if there are no candidates to match against.
9077     if (MaxLength == 0u)
9078       return ZeroInitialization(E);
9079     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9080         Result.Designator.Invalid)
9081       return false;
9082     QualType CharTy = Result.Designator.getType(Info.Ctx);
9083     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9084                      BuiltinOp == Builtin::BI__builtin_memchr;
9085     assert(IsRawByte ||
9086            Info.Ctx.hasSameUnqualifiedType(
9087                CharTy, E->getArg(0)->getType()->getPointeeType()));
9088     // Pointers to const void may point to objects of incomplete type.
9089     if (IsRawByte && CharTy->isIncompleteType()) {
9090       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9091       return false;
9092     }
9093     // Give up on byte-oriented matching against multibyte elements.
9094     // FIXME: We can compare the bytes in the correct order.
9095     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9096       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9097           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9098           << CharTy;
9099       return false;
9100     }
9101     // Figure out what value we're actually looking for (after converting to
9102     // the corresponding unsigned type if necessary).
9103     uint64_t DesiredVal;
9104     bool StopAtNull = false;
9105     switch (BuiltinOp) {
9106     case Builtin::BIstrchr:
9107     case Builtin::BI__builtin_strchr:
9108       // strchr compares directly to the passed integer, and therefore
9109       // always fails if given an int that is not a char.
9110       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9111                                                   E->getArg(1)->getType(),
9112                                                   Desired),
9113                                Desired))
9114         return ZeroInitialization(E);
9115       StopAtNull = true;
9116       LLVM_FALLTHROUGH;
9117     case Builtin::BImemchr:
9118     case Builtin::BI__builtin_memchr:
9119     case Builtin::BI__builtin_char_memchr:
9120       // memchr compares by converting both sides to unsigned char. That's also
9121       // correct for strchr if we get this far (to cope with plain char being
9122       // unsigned in the strchr case).
9123       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9124       break;
9125 
9126     case Builtin::BIwcschr:
9127     case Builtin::BI__builtin_wcschr:
9128       StopAtNull = true;
9129       LLVM_FALLTHROUGH;
9130     case Builtin::BIwmemchr:
9131     case Builtin::BI__builtin_wmemchr:
9132       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9133       DesiredVal = Desired.getZExtValue();
9134       break;
9135     }
9136 
9137     for (; MaxLength; --MaxLength) {
9138       APValue Char;
9139       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9140           !Char.isInt())
9141         return false;
9142       if (Char.getInt().getZExtValue() == DesiredVal)
9143         return true;
9144       if (StopAtNull && !Char.getInt())
9145         break;
9146       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9147         return false;
9148     }
9149     // Not found: return nullptr.
9150     return ZeroInitialization(E);
9151   }
9152 
9153   case Builtin::BImemcpy:
9154   case Builtin::BImemmove:
9155   case Builtin::BIwmemcpy:
9156   case Builtin::BIwmemmove:
9157     if (Info.getLangOpts().CPlusPlus11)
9158       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9159         << /*isConstexpr*/0 << /*isConstructor*/0
9160         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9161     else
9162       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9163     LLVM_FALLTHROUGH;
9164   case Builtin::BI__builtin_memcpy:
9165   case Builtin::BI__builtin_memmove:
9166   case Builtin::BI__builtin_wmemcpy:
9167   case Builtin::BI__builtin_wmemmove: {
9168     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9169                  BuiltinOp == Builtin::BIwmemmove ||
9170                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9171                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9172     bool Move = BuiltinOp == Builtin::BImemmove ||
9173                 BuiltinOp == Builtin::BIwmemmove ||
9174                 BuiltinOp == Builtin::BI__builtin_memmove ||
9175                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9176 
9177     // The result of mem* is the first argument.
9178     if (!Visit(E->getArg(0)))
9179       return false;
9180     LValue Dest = Result;
9181 
9182     LValue Src;
9183     if (!EvaluatePointer(E->getArg(1), Src, Info))
9184       return false;
9185 
9186     APSInt N;
9187     if (!EvaluateInteger(E->getArg(2), N, Info))
9188       return false;
9189     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9190 
9191     // If the size is zero, we treat this as always being a valid no-op.
9192     // (Even if one of the src and dest pointers is null.)
9193     if (!N)
9194       return true;
9195 
9196     // Otherwise, if either of the operands is null, we can't proceed. Don't
9197     // try to determine the type of the copied objects, because there aren't
9198     // any.
9199     if (!Src.Base || !Dest.Base) {
9200       APValue Val;
9201       (!Src.Base ? Src : Dest).moveInto(Val);
9202       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9203           << Move << WChar << !!Src.Base
9204           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9205       return false;
9206     }
9207     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9208       return false;
9209 
9210     // We require that Src and Dest are both pointers to arrays of
9211     // trivially-copyable type. (For the wide version, the designator will be
9212     // invalid if the designated object is not a wchar_t.)
9213     QualType T = Dest.Designator.getType(Info.Ctx);
9214     QualType SrcT = Src.Designator.getType(Info.Ctx);
9215     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9216       // FIXME: Consider using our bit_cast implementation to support this.
9217       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9218       return false;
9219     }
9220     if (T->isIncompleteType()) {
9221       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9222       return false;
9223     }
9224     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9225       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9226       return false;
9227     }
9228 
9229     // Figure out how many T's we're copying.
9230     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9231     if (!WChar) {
9232       uint64_t Remainder;
9233       llvm::APInt OrigN = N;
9234       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9235       if (Remainder) {
9236         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9237             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
9238             << (unsigned)TSize;
9239         return false;
9240       }
9241     }
9242 
9243     // Check that the copying will remain within the arrays, just so that we
9244     // can give a more meaningful diagnostic. This implicitly also checks that
9245     // N fits into 64 bits.
9246     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9247     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9248     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9249       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9250           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9251           << N.toString(10, /*Signed*/false);
9252       return false;
9253     }
9254     uint64_t NElems = N.getZExtValue();
9255     uint64_t NBytes = NElems * TSize;
9256 
9257     // Check for overlap.
9258     int Direction = 1;
9259     if (HasSameBase(Src, Dest)) {
9260       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9261       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9262       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9263         // Dest is inside the source region.
9264         if (!Move) {
9265           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9266           return false;
9267         }
9268         // For memmove and friends, copy backwards.
9269         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9270             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9271           return false;
9272         Direction = -1;
9273       } else if (!Move && SrcOffset >= DestOffset &&
9274                  SrcOffset - DestOffset < NBytes) {
9275         // Src is inside the destination region for memcpy: invalid.
9276         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9277         return false;
9278       }
9279     }
9280 
9281     while (true) {
9282       APValue Val;
9283       // FIXME: Set WantObjectRepresentation to true if we're copying a
9284       // char-like type?
9285       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9286           !handleAssignment(Info, E, Dest, T, Val))
9287         return false;
9288       // Do not iterate past the last element; if we're copying backwards, that
9289       // might take us off the start of the array.
9290       if (--NElems == 0)
9291         return true;
9292       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9293           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9294         return false;
9295     }
9296   }
9297 
9298   default:
9299     break;
9300   }
9301 
9302   return visitNonBuiltinCallExpr(E);
9303 }
9304 
9305 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9306                                      APValue &Result, const InitListExpr *ILE,
9307                                      QualType AllocType);
9308 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9309                                           APValue &Result,
9310                                           const CXXConstructExpr *CCE,
9311                                           QualType AllocType);
9312 
VisitCXXNewExpr(const CXXNewExpr * E)9313 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9314   if (!Info.getLangOpts().CPlusPlus20)
9315     Info.CCEDiag(E, diag::note_constexpr_new);
9316 
9317   // We cannot speculatively evaluate a delete expression.
9318   if (Info.SpeculativeEvaluationDepth)
9319     return false;
9320 
9321   FunctionDecl *OperatorNew = E->getOperatorNew();
9322 
9323   bool IsNothrow = false;
9324   bool IsPlacement = false;
9325   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9326       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9327     // FIXME Support array placement new.
9328     assert(E->getNumPlacementArgs() == 1);
9329     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9330       return false;
9331     if (Result.Designator.Invalid)
9332       return false;
9333     IsPlacement = true;
9334   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9335     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9336         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9337     return false;
9338   } else if (E->getNumPlacementArgs()) {
9339     // The only new-placement list we support is of the form (std::nothrow).
9340     //
9341     // FIXME: There is no restriction on this, but it's not clear that any
9342     // other form makes any sense. We get here for cases such as:
9343     //
9344     //   new (std::align_val_t{N}) X(int)
9345     //
9346     // (which should presumably be valid only if N is a multiple of
9347     // alignof(int), and in any case can't be deallocated unless N is
9348     // alignof(X) and X has new-extended alignment).
9349     if (E->getNumPlacementArgs() != 1 ||
9350         !E->getPlacementArg(0)->getType()->isNothrowT())
9351       return Error(E, diag::note_constexpr_new_placement);
9352 
9353     LValue Nothrow;
9354     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9355       return false;
9356     IsNothrow = true;
9357   }
9358 
9359   const Expr *Init = E->getInitializer();
9360   const InitListExpr *ResizedArrayILE = nullptr;
9361   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9362   bool ValueInit = false;
9363 
9364   QualType AllocType = E->getAllocatedType();
9365   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9366     const Expr *Stripped = *ArraySize;
9367     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9368          Stripped = ICE->getSubExpr())
9369       if (ICE->getCastKind() != CK_NoOp &&
9370           ICE->getCastKind() != CK_IntegralCast)
9371         break;
9372 
9373     llvm::APSInt ArrayBound;
9374     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9375       return false;
9376 
9377     // C++ [expr.new]p9:
9378     //   The expression is erroneous if:
9379     //   -- [...] its value before converting to size_t [or] applying the
9380     //      second standard conversion sequence is less than zero
9381     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9382       if (IsNothrow)
9383         return ZeroInitialization(E);
9384 
9385       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9386           << ArrayBound << (*ArraySize)->getSourceRange();
9387       return false;
9388     }
9389 
9390     //   -- its value is such that the size of the allocated object would
9391     //      exceed the implementation-defined limit
9392     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9393                                                 ArrayBound) >
9394         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9395       if (IsNothrow)
9396         return ZeroInitialization(E);
9397 
9398       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9399         << ArrayBound << (*ArraySize)->getSourceRange();
9400       return false;
9401     }
9402 
9403     //   -- the new-initializer is a braced-init-list and the number of
9404     //      array elements for which initializers are provided [...]
9405     //      exceeds the number of elements to initialize
9406     if (!Init) {
9407       // No initialization is performed.
9408     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9409                isa<ImplicitValueInitExpr>(Init)) {
9410       ValueInit = true;
9411     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9412       ResizedArrayCCE = CCE;
9413     } else {
9414       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9415       assert(CAT && "unexpected type for array initializer");
9416 
9417       unsigned Bits =
9418           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9419       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9420       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9421       if (InitBound.ugt(AllocBound)) {
9422         if (IsNothrow)
9423           return ZeroInitialization(E);
9424 
9425         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9426             << AllocBound.toString(10, /*Signed=*/false)
9427             << InitBound.toString(10, /*Signed=*/false)
9428             << (*ArraySize)->getSourceRange();
9429         return false;
9430       }
9431 
9432       // If the sizes differ, we must have an initializer list, and we need
9433       // special handling for this case when we initialize.
9434       if (InitBound != AllocBound)
9435         ResizedArrayILE = cast<InitListExpr>(Init);
9436     }
9437 
9438     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9439                                               ArrayType::Normal, 0);
9440   } else {
9441     assert(!AllocType->isArrayType() &&
9442            "array allocation with non-array new");
9443   }
9444 
9445   APValue *Val;
9446   if (IsPlacement) {
9447     AccessKinds AK = AK_Construct;
9448     struct FindObjectHandler {
9449       EvalInfo &Info;
9450       const Expr *E;
9451       QualType AllocType;
9452       const AccessKinds AccessKind;
9453       APValue *Value;
9454 
9455       typedef bool result_type;
9456       bool failed() { return false; }
9457       bool found(APValue &Subobj, QualType SubobjType) {
9458         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9459         // old name of the object to be used to name the new object.
9460         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9461           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9462             SubobjType << AllocType;
9463           return false;
9464         }
9465         Value = &Subobj;
9466         return true;
9467       }
9468       bool found(APSInt &Value, QualType SubobjType) {
9469         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9470         return false;
9471       }
9472       bool found(APFloat &Value, QualType SubobjType) {
9473         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9474         return false;
9475       }
9476     } Handler = {Info, E, AllocType, AK, nullptr};
9477 
9478     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9479     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9480       return false;
9481 
9482     Val = Handler.Value;
9483 
9484     // [basic.life]p1:
9485     //   The lifetime of an object o of type T ends when [...] the storage
9486     //   which the object occupies is [...] reused by an object that is not
9487     //   nested within o (6.6.2).
9488     *Val = APValue();
9489   } else {
9490     // Perform the allocation and obtain a pointer to the resulting object.
9491     Val = Info.createHeapAlloc(E, AllocType, Result);
9492     if (!Val)
9493       return false;
9494   }
9495 
9496   if (ValueInit) {
9497     ImplicitValueInitExpr VIE(AllocType);
9498     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9499       return false;
9500   } else if (ResizedArrayILE) {
9501     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9502                                   AllocType))
9503       return false;
9504   } else if (ResizedArrayCCE) {
9505     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9506                                        AllocType))
9507       return false;
9508   } else if (Init) {
9509     if (!EvaluateInPlace(*Val, Info, Result, Init))
9510       return false;
9511   } else if (!getDefaultInitValue(AllocType, *Val)) {
9512     return false;
9513   }
9514 
9515   // Array new returns a pointer to the first element, not a pointer to the
9516   // array.
9517   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9518     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9519 
9520   return true;
9521 }
9522 //===----------------------------------------------------------------------===//
9523 // Member Pointer Evaluation
9524 //===----------------------------------------------------------------------===//
9525 
9526 namespace {
9527 class MemberPointerExprEvaluator
9528   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9529   MemberPtr &Result;
9530 
Success(const ValueDecl * D)9531   bool Success(const ValueDecl *D) {
9532     Result = MemberPtr(D);
9533     return true;
9534   }
9535 public:
9536 
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)9537   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9538     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9539 
Success(const APValue & V,const Expr * E)9540   bool Success(const APValue &V, const Expr *E) {
9541     Result.setFrom(V);
9542     return true;
9543   }
ZeroInitialization(const Expr * E)9544   bool ZeroInitialization(const Expr *E) {
9545     return Success((const ValueDecl*)nullptr);
9546   }
9547 
9548   bool VisitCastExpr(const CastExpr *E);
9549   bool VisitUnaryAddrOf(const UnaryOperator *E);
9550 };
9551 } // end anonymous namespace
9552 
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)9553 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9554                                   EvalInfo &Info) {
9555   assert(!E->isValueDependent());
9556   assert(E->isRValue() && E->getType()->isMemberPointerType());
9557   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9558 }
9559 
VisitCastExpr(const CastExpr * E)9560 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9561   switch (E->getCastKind()) {
9562   default:
9563     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9564 
9565   case CK_NullToMemberPointer:
9566     VisitIgnoredValue(E->getSubExpr());
9567     return ZeroInitialization(E);
9568 
9569   case CK_BaseToDerivedMemberPointer: {
9570     if (!Visit(E->getSubExpr()))
9571       return false;
9572     if (E->path_empty())
9573       return true;
9574     // Base-to-derived member pointer casts store the path in derived-to-base
9575     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9576     // the wrong end of the derived->base arc, so stagger the path by one class.
9577     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9578     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9579          PathI != PathE; ++PathI) {
9580       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9581       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9582       if (!Result.castToDerived(Derived))
9583         return Error(E);
9584     }
9585     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9586     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9587       return Error(E);
9588     return true;
9589   }
9590 
9591   case CK_DerivedToBaseMemberPointer:
9592     if (!Visit(E->getSubExpr()))
9593       return false;
9594     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9595          PathE = E->path_end(); PathI != PathE; ++PathI) {
9596       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9597       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9598       if (!Result.castToBase(Base))
9599         return Error(E);
9600     }
9601     return true;
9602   }
9603 }
9604 
VisitUnaryAddrOf(const UnaryOperator * E)9605 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9606   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9607   // member can be formed.
9608   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9609 }
9610 
9611 //===----------------------------------------------------------------------===//
9612 // Record Evaluation
9613 //===----------------------------------------------------------------------===//
9614 
9615 namespace {
9616   class RecordExprEvaluator
9617   : public ExprEvaluatorBase<RecordExprEvaluator> {
9618     const LValue &This;
9619     APValue &Result;
9620   public:
9621 
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)9622     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9623       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9624 
Success(const APValue & V,const Expr * E)9625     bool Success(const APValue &V, const Expr *E) {
9626       Result = V;
9627       return true;
9628     }
ZeroInitialization(const Expr * E)9629     bool ZeroInitialization(const Expr *E) {
9630       return ZeroInitialization(E, E->getType());
9631     }
9632     bool ZeroInitialization(const Expr *E, QualType T);
9633 
VisitCallExpr(const CallExpr * E)9634     bool VisitCallExpr(const CallExpr *E) {
9635       return handleCallExpr(E, Result, &This);
9636     }
9637     bool VisitCastExpr(const CastExpr *E);
9638     bool VisitInitListExpr(const InitListExpr *E);
VisitCXXConstructExpr(const CXXConstructExpr * E)9639     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9640       return VisitCXXConstructExpr(E, E->getType());
9641     }
9642     bool VisitLambdaExpr(const LambdaExpr *E);
9643     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9644     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9645     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9646     bool VisitBinCmp(const BinaryOperator *E);
9647   };
9648 }
9649 
9650 /// Perform zero-initialization on an object of non-union class type.
9651 /// C++11 [dcl.init]p5:
9652 ///  To zero-initialize an object or reference of type T means:
9653 ///    [...]
9654 ///    -- if T is a (possibly cv-qualified) non-union class type,
9655 ///       each non-static data member and each base-class subobject is
9656 ///       zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)9657 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9658                                           const RecordDecl *RD,
9659                                           const LValue &This, APValue &Result) {
9660   assert(!RD->isUnion() && "Expected non-union class type");
9661   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9662   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9663                    std::distance(RD->field_begin(), RD->field_end()));
9664 
9665   if (RD->isInvalidDecl()) return false;
9666   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9667 
9668   if (CD) {
9669     unsigned Index = 0;
9670     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9671            End = CD->bases_end(); I != End; ++I, ++Index) {
9672       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9673       LValue Subobject = This;
9674       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9675         return false;
9676       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9677                                          Result.getStructBase(Index)))
9678         return false;
9679     }
9680   }
9681 
9682   for (const auto *I : RD->fields()) {
9683     // -- if T is a reference type, no initialization is performed.
9684     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9685       continue;
9686 
9687     LValue Subobject = This;
9688     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9689       return false;
9690 
9691     ImplicitValueInitExpr VIE(I->getType());
9692     if (!EvaluateInPlace(
9693           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9694       return false;
9695   }
9696 
9697   return true;
9698 }
9699 
ZeroInitialization(const Expr * E,QualType T)9700 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9701   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9702   if (RD->isInvalidDecl()) return false;
9703   if (RD->isUnion()) {
9704     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9705     // object's first non-static named data member is zero-initialized
9706     RecordDecl::field_iterator I = RD->field_begin();
9707     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9708       ++I;
9709     if (I == RD->field_end()) {
9710       Result = APValue((const FieldDecl*)nullptr);
9711       return true;
9712     }
9713 
9714     LValue Subobject = This;
9715     if (!HandleLValueMember(Info, E, Subobject, *I))
9716       return false;
9717     Result = APValue(*I);
9718     ImplicitValueInitExpr VIE(I->getType());
9719     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9720   }
9721 
9722   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9723     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9724     return false;
9725   }
9726 
9727   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9728 }
9729 
VisitCastExpr(const CastExpr * E)9730 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9731   switch (E->getCastKind()) {
9732   default:
9733     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9734 
9735   case CK_ConstructorConversion:
9736     return Visit(E->getSubExpr());
9737 
9738   case CK_DerivedToBase:
9739   case CK_UncheckedDerivedToBase: {
9740     APValue DerivedObject;
9741     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9742       return false;
9743     if (!DerivedObject.isStruct())
9744       return Error(E->getSubExpr());
9745 
9746     // Derived-to-base rvalue conversion: just slice off the derived part.
9747     APValue *Value = &DerivedObject;
9748     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9749     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9750          PathE = E->path_end(); PathI != PathE; ++PathI) {
9751       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9752       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9753       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9754       RD = Base;
9755     }
9756     Result = *Value;
9757     return true;
9758   }
9759   }
9760 }
9761 
VisitInitListExpr(const InitListExpr * E)9762 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9763   if (E->isTransparent())
9764     return Visit(E->getInit(0));
9765 
9766   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9767   if (RD->isInvalidDecl()) return false;
9768   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9769   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9770 
9771   EvalInfo::EvaluatingConstructorRAII EvalObj(
9772       Info,
9773       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9774       CXXRD && CXXRD->getNumBases());
9775 
9776   if (RD->isUnion()) {
9777     const FieldDecl *Field = E->getInitializedFieldInUnion();
9778     Result = APValue(Field);
9779     if (!Field)
9780       return true;
9781 
9782     // If the initializer list for a union does not contain any elements, the
9783     // first element of the union is value-initialized.
9784     // FIXME: The element should be initialized from an initializer list.
9785     //        Is this difference ever observable for initializer lists which
9786     //        we don't build?
9787     ImplicitValueInitExpr VIE(Field->getType());
9788     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9789 
9790     LValue Subobject = This;
9791     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9792       return false;
9793 
9794     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9795     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9796                                   isa<CXXDefaultInitExpr>(InitExpr));
9797 
9798     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9799   }
9800 
9801   if (!Result.hasValue())
9802     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9803                      std::distance(RD->field_begin(), RD->field_end()));
9804   unsigned ElementNo = 0;
9805   bool Success = true;
9806 
9807   // Initialize base classes.
9808   if (CXXRD && CXXRD->getNumBases()) {
9809     for (const auto &Base : CXXRD->bases()) {
9810       assert(ElementNo < E->getNumInits() && "missing init for base class");
9811       const Expr *Init = E->getInit(ElementNo);
9812 
9813       LValue Subobject = This;
9814       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9815         return false;
9816 
9817       APValue &FieldVal = Result.getStructBase(ElementNo);
9818       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9819         if (!Info.noteFailure())
9820           return false;
9821         Success = false;
9822       }
9823       ++ElementNo;
9824     }
9825 
9826     EvalObj.finishedConstructingBases();
9827   }
9828 
9829   // Initialize members.
9830   for (const auto *Field : RD->fields()) {
9831     // Anonymous bit-fields are not considered members of the class for
9832     // purposes of aggregate initialization.
9833     if (Field->isUnnamedBitfield())
9834       continue;
9835 
9836     LValue Subobject = This;
9837 
9838     bool HaveInit = ElementNo < E->getNumInits();
9839 
9840     // FIXME: Diagnostics here should point to the end of the initializer
9841     // list, not the start.
9842     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9843                             Subobject, Field, &Layout))
9844       return false;
9845 
9846     // Perform an implicit value-initialization for members beyond the end of
9847     // the initializer list.
9848     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9849     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9850 
9851     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9852     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9853                                   isa<CXXDefaultInitExpr>(Init));
9854 
9855     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9856     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9857         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9858                                                        FieldVal, Field))) {
9859       if (!Info.noteFailure())
9860         return false;
9861       Success = false;
9862     }
9863   }
9864 
9865   EvalObj.finishedConstructingFields();
9866 
9867   return Success;
9868 }
9869 
VisitCXXConstructExpr(const CXXConstructExpr * E,QualType T)9870 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9871                                                 QualType T) {
9872   // Note that E's type is not necessarily the type of our class here; we might
9873   // be initializing an array element instead.
9874   const CXXConstructorDecl *FD = E->getConstructor();
9875   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9876 
9877   bool ZeroInit = E->requiresZeroInitialization();
9878   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9879     // If we've already performed zero-initialization, we're already done.
9880     if (Result.hasValue())
9881       return true;
9882 
9883     if (ZeroInit)
9884       return ZeroInitialization(E, T);
9885 
9886     return getDefaultInitValue(T, Result);
9887   }
9888 
9889   const FunctionDecl *Definition = nullptr;
9890   auto Body = FD->getBody(Definition);
9891 
9892   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9893     return false;
9894 
9895   // Avoid materializing a temporary for an elidable copy/move constructor.
9896   if (E->isElidable() && !ZeroInit)
9897     if (const MaterializeTemporaryExpr *ME
9898           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9899       return Visit(ME->getSubExpr());
9900 
9901   if (ZeroInit && !ZeroInitialization(E, T))
9902     return false;
9903 
9904   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9905   return HandleConstructorCall(E, This, Args,
9906                                cast<CXXConstructorDecl>(Definition), Info,
9907                                Result);
9908 }
9909 
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * E)9910 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9911     const CXXInheritedCtorInitExpr *E) {
9912   if (!Info.CurrentCall) {
9913     assert(Info.checkingPotentialConstantExpression());
9914     return false;
9915   }
9916 
9917   const CXXConstructorDecl *FD = E->getConstructor();
9918   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9919     return false;
9920 
9921   const FunctionDecl *Definition = nullptr;
9922   auto Body = FD->getBody(Definition);
9923 
9924   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9925     return false;
9926 
9927   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9928                                cast<CXXConstructorDecl>(Definition), Info,
9929                                Result);
9930 }
9931 
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)9932 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9933     const CXXStdInitializerListExpr *E) {
9934   const ConstantArrayType *ArrayType =
9935       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9936 
9937   LValue Array;
9938   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9939     return false;
9940 
9941   // Get a pointer to the first element of the array.
9942   Array.addArray(Info, E, ArrayType);
9943 
9944   auto InvalidType = [&] {
9945     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9946       << E->getType();
9947     return false;
9948   };
9949 
9950   // FIXME: Perform the checks on the field types in SemaInit.
9951   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9952   RecordDecl::field_iterator Field = Record->field_begin();
9953   if (Field == Record->field_end())
9954     return InvalidType();
9955 
9956   // Start pointer.
9957   if (!Field->getType()->isPointerType() ||
9958       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9959                             ArrayType->getElementType()))
9960     return InvalidType();
9961 
9962   // FIXME: What if the initializer_list type has base classes, etc?
9963   Result = APValue(APValue::UninitStruct(), 0, 2);
9964   Array.moveInto(Result.getStructField(0));
9965 
9966   if (++Field == Record->field_end())
9967     return InvalidType();
9968 
9969   if (Field->getType()->isPointerType() &&
9970       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9971                            ArrayType->getElementType())) {
9972     // End pointer.
9973     if (!HandleLValueArrayAdjustment(Info, E, Array,
9974                                      ArrayType->getElementType(),
9975                                      ArrayType->getSize().getZExtValue()))
9976       return false;
9977     Array.moveInto(Result.getStructField(1));
9978   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9979     // Length.
9980     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9981   else
9982     return InvalidType();
9983 
9984   if (++Field != Record->field_end())
9985     return InvalidType();
9986 
9987   return true;
9988 }
9989 
VisitLambdaExpr(const LambdaExpr * E)9990 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9991   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9992   if (ClosureClass->isInvalidDecl())
9993     return false;
9994 
9995   const size_t NumFields =
9996       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9997 
9998   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9999                                             E->capture_init_end()) &&
10000          "The number of lambda capture initializers should equal the number of "
10001          "fields within the closure type");
10002 
10003   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10004   // Iterate through all the lambda's closure object's fields and initialize
10005   // them.
10006   auto *CaptureInitIt = E->capture_init_begin();
10007   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10008   bool Success = true;
10009   for (const auto *Field : ClosureClass->fields()) {
10010     assert(CaptureInitIt != E->capture_init_end());
10011     // Get the initializer for this field
10012     Expr *const CurFieldInit = *CaptureInitIt++;
10013 
10014     // If there is no initializer, either this is a VLA or an error has
10015     // occurred.
10016     if (!CurFieldInit)
10017       return Error(E);
10018 
10019     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10020     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
10021       if (!Info.keepEvaluatingAfterFailure())
10022         return false;
10023       Success = false;
10024     }
10025     ++CaptureIt;
10026   }
10027   return Success;
10028 }
10029 
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10030 static bool EvaluateRecord(const Expr *E, const LValue &This,
10031                            APValue &Result, EvalInfo &Info) {
10032   assert(!E->isValueDependent());
10033   assert(E->isRValue() && E->getType()->isRecordType() &&
10034          "can't evaluate expression as a record rvalue");
10035   return RecordExprEvaluator(Info, This, Result).Visit(E);
10036 }
10037 
10038 //===----------------------------------------------------------------------===//
10039 // Temporary Evaluation
10040 //
10041 // Temporaries are represented in the AST as rvalues, but generally behave like
10042 // lvalues. The full-object of which the temporary is a subobject is implicitly
10043 // materialized so that a reference can bind to it.
10044 //===----------------------------------------------------------------------===//
10045 namespace {
10046 class TemporaryExprEvaluator
10047   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10048 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)10049   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10050     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10051 
10052   /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)10053   bool VisitConstructExpr(const Expr *E) {
10054     APValue &Value = Info.CurrentCall->createTemporary(
10055         E, E->getType(), ScopeKind::FullExpression, Result);
10056     return EvaluateInPlace(Value, Info, Result, E);
10057   }
10058 
VisitCastExpr(const CastExpr * E)10059   bool VisitCastExpr(const CastExpr *E) {
10060     switch (E->getCastKind()) {
10061     default:
10062       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10063 
10064     case CK_ConstructorConversion:
10065       return VisitConstructExpr(E->getSubExpr());
10066     }
10067   }
VisitInitListExpr(const InitListExpr * E)10068   bool VisitInitListExpr(const InitListExpr *E) {
10069     return VisitConstructExpr(E);
10070   }
VisitCXXConstructExpr(const CXXConstructExpr * E)10071   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10072     return VisitConstructExpr(E);
10073   }
VisitCallExpr(const CallExpr * E)10074   bool VisitCallExpr(const CallExpr *E) {
10075     return VisitConstructExpr(E);
10076   }
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10077   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10078     return VisitConstructExpr(E);
10079   }
VisitLambdaExpr(const LambdaExpr * E)10080   bool VisitLambdaExpr(const LambdaExpr *E) {
10081     return VisitConstructExpr(E);
10082   }
10083 };
10084 } // end anonymous namespace
10085 
10086 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)10087 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10088   assert(!E->isValueDependent());
10089   assert(E->isRValue() && E->getType()->isRecordType());
10090   return TemporaryExprEvaluator(Info, Result).Visit(E);
10091 }
10092 
10093 //===----------------------------------------------------------------------===//
10094 // Vector Evaluation
10095 //===----------------------------------------------------------------------===//
10096 
10097 namespace {
10098   class VectorExprEvaluator
10099   : public ExprEvaluatorBase<VectorExprEvaluator> {
10100     APValue &Result;
10101   public:
10102 
VectorExprEvaluator(EvalInfo & info,APValue & Result)10103     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10104       : ExprEvaluatorBaseTy(info), Result(Result) {}
10105 
Success(ArrayRef<APValue> V,const Expr * E)10106     bool Success(ArrayRef<APValue> V, const Expr *E) {
10107       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10108       // FIXME: remove this APValue copy.
10109       Result = APValue(V.data(), V.size());
10110       return true;
10111     }
Success(const APValue & V,const Expr * E)10112     bool Success(const APValue &V, const Expr *E) {
10113       assert(V.isVector());
10114       Result = V;
10115       return true;
10116     }
10117     bool ZeroInitialization(const Expr *E);
10118 
VisitUnaryReal(const UnaryOperator * E)10119     bool VisitUnaryReal(const UnaryOperator *E)
10120       { return Visit(E->getSubExpr()); }
10121     bool VisitCastExpr(const CastExpr* E);
10122     bool VisitInitListExpr(const InitListExpr *E);
10123     bool VisitUnaryImag(const UnaryOperator *E);
10124     bool VisitBinaryOperator(const BinaryOperator *E);
10125     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10126     //                 conditional select), shufflevector, ExtVectorElementExpr
10127   };
10128 } // end anonymous namespace
10129 
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)10130 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10131   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
10132   return VectorExprEvaluator(Info, Result).Visit(E);
10133 }
10134 
VisitCastExpr(const CastExpr * E)10135 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10136   const VectorType *VTy = E->getType()->castAs<VectorType>();
10137   unsigned NElts = VTy->getNumElements();
10138 
10139   const Expr *SE = E->getSubExpr();
10140   QualType SETy = SE->getType();
10141 
10142   switch (E->getCastKind()) {
10143   case CK_VectorSplat: {
10144     APValue Val = APValue();
10145     if (SETy->isIntegerType()) {
10146       APSInt IntResult;
10147       if (!EvaluateInteger(SE, IntResult, Info))
10148         return false;
10149       Val = APValue(std::move(IntResult));
10150     } else if (SETy->isRealFloatingType()) {
10151       APFloat FloatResult(0.0);
10152       if (!EvaluateFloat(SE, FloatResult, Info))
10153         return false;
10154       Val = APValue(std::move(FloatResult));
10155     } else {
10156       return Error(E);
10157     }
10158 
10159     // Splat and create vector APValue.
10160     SmallVector<APValue, 4> Elts(NElts, Val);
10161     return Success(Elts, E);
10162   }
10163   case CK_BitCast: {
10164     // Evaluate the operand into an APInt we can extract from.
10165     llvm::APInt SValInt;
10166     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10167       return false;
10168     // Extract the elements
10169     QualType EltTy = VTy->getElementType();
10170     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10171     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10172     SmallVector<APValue, 4> Elts;
10173     if (EltTy->isRealFloatingType()) {
10174       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10175       unsigned FloatEltSize = EltSize;
10176       if (&Sem == &APFloat::x87DoubleExtended())
10177         FloatEltSize = 80;
10178       for (unsigned i = 0; i < NElts; i++) {
10179         llvm::APInt Elt;
10180         if (BigEndian)
10181           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10182         else
10183           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10184         Elts.push_back(APValue(APFloat(Sem, Elt)));
10185       }
10186     } else if (EltTy->isIntegerType()) {
10187       for (unsigned i = 0; i < NElts; i++) {
10188         llvm::APInt Elt;
10189         if (BigEndian)
10190           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10191         else
10192           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10193         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
10194       }
10195     } else {
10196       return Error(E);
10197     }
10198     return Success(Elts, E);
10199   }
10200   default:
10201     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10202   }
10203 }
10204 
10205 bool
VisitInitListExpr(const InitListExpr * E)10206 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10207   const VectorType *VT = E->getType()->castAs<VectorType>();
10208   unsigned NumInits = E->getNumInits();
10209   unsigned NumElements = VT->getNumElements();
10210 
10211   QualType EltTy = VT->getElementType();
10212   SmallVector<APValue, 4> Elements;
10213 
10214   // The number of initializers can be less than the number of
10215   // vector elements. For OpenCL, this can be due to nested vector
10216   // initialization. For GCC compatibility, missing trailing elements
10217   // should be initialized with zeroes.
10218   unsigned CountInits = 0, CountElts = 0;
10219   while (CountElts < NumElements) {
10220     // Handle nested vector initialization.
10221     if (CountInits < NumInits
10222         && E->getInit(CountInits)->getType()->isVectorType()) {
10223       APValue v;
10224       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10225         return Error(E);
10226       unsigned vlen = v.getVectorLength();
10227       for (unsigned j = 0; j < vlen; j++)
10228         Elements.push_back(v.getVectorElt(j));
10229       CountElts += vlen;
10230     } else if (EltTy->isIntegerType()) {
10231       llvm::APSInt sInt(32);
10232       if (CountInits < NumInits) {
10233         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10234           return false;
10235       } else // trailing integer zero.
10236         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10237       Elements.push_back(APValue(sInt));
10238       CountElts++;
10239     } else {
10240       llvm::APFloat f(0.0);
10241       if (CountInits < NumInits) {
10242         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10243           return false;
10244       } else // trailing float zero.
10245         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10246       Elements.push_back(APValue(f));
10247       CountElts++;
10248     }
10249     CountInits++;
10250   }
10251   return Success(Elements, E);
10252 }
10253 
10254 bool
ZeroInitialization(const Expr * E)10255 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10256   const auto *VT = E->getType()->castAs<VectorType>();
10257   QualType EltTy = VT->getElementType();
10258   APValue ZeroElement;
10259   if (EltTy->isIntegerType())
10260     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10261   else
10262     ZeroElement =
10263         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10264 
10265   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10266   return Success(Elements, E);
10267 }
10268 
VisitUnaryImag(const UnaryOperator * E)10269 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10270   VisitIgnoredValue(E->getSubExpr());
10271   return ZeroInitialization(E);
10272 }
10273 
VisitBinaryOperator(const BinaryOperator * E)10274 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10275   BinaryOperatorKind Op = E->getOpcode();
10276   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10277          "Operation not supported on vector types");
10278 
10279   if (Op == BO_Comma)
10280     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10281 
10282   Expr *LHS = E->getLHS();
10283   Expr *RHS = E->getRHS();
10284 
10285   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10286          "Must both be vector types");
10287   // Checking JUST the types are the same would be fine, except shifts don't
10288   // need to have their types be the same (since you always shift by an int).
10289   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
10290              E->getType()->getAs<VectorType>()->getNumElements() &&
10291          RHS->getType()->getAs<VectorType>()->getNumElements() ==
10292              E->getType()->getAs<VectorType>()->getNumElements() &&
10293          "All operands must be the same size.");
10294 
10295   APValue LHSValue;
10296   APValue RHSValue;
10297   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10298   if (!LHSOK && !Info.noteFailure())
10299     return false;
10300   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10301     return false;
10302 
10303   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10304     return false;
10305 
10306   return Success(LHSValue, E);
10307 }
10308 
10309 //===----------------------------------------------------------------------===//
10310 // Array Evaluation
10311 //===----------------------------------------------------------------------===//
10312 
10313 namespace {
10314   class ArrayExprEvaluator
10315   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10316     const LValue &This;
10317     APValue &Result;
10318   public:
10319 
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)10320     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10321       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10322 
Success(const APValue & V,const Expr * E)10323     bool Success(const APValue &V, const Expr *E) {
10324       assert(V.isArray() && "expected array");
10325       Result = V;
10326       return true;
10327     }
10328 
ZeroInitialization(const Expr * E)10329     bool ZeroInitialization(const Expr *E) {
10330       const ConstantArrayType *CAT =
10331           Info.Ctx.getAsConstantArrayType(E->getType());
10332       if (!CAT) {
10333         if (E->getType()->isIncompleteArrayType()) {
10334           // We can be asked to zero-initialize a flexible array member; this
10335           // is represented as an ImplicitValueInitExpr of incomplete array
10336           // type. In this case, the array has zero elements.
10337           Result = APValue(APValue::UninitArray(), 0, 0);
10338           return true;
10339         }
10340         // FIXME: We could handle VLAs here.
10341         return Error(E);
10342       }
10343 
10344       Result = APValue(APValue::UninitArray(), 0,
10345                        CAT->getSize().getZExtValue());
10346       if (!Result.hasArrayFiller()) return true;
10347 
10348       // Zero-initialize all elements.
10349       LValue Subobject = This;
10350       Subobject.addArray(Info, E, CAT);
10351       ImplicitValueInitExpr VIE(CAT->getElementType());
10352       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10353     }
10354 
VisitCallExpr(const CallExpr * E)10355     bool VisitCallExpr(const CallExpr *E) {
10356       return handleCallExpr(E, Result, &This);
10357     }
10358     bool VisitInitListExpr(const InitListExpr *E,
10359                            QualType AllocType = QualType());
10360     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10361     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10362     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10363                                const LValue &Subobject,
10364                                APValue *Value, QualType Type);
VisitStringLiteral(const StringLiteral * E,QualType AllocType=QualType ())10365     bool VisitStringLiteral(const StringLiteral *E,
10366                             QualType AllocType = QualType()) {
10367       expandStringLiteral(Info, E, Result, AllocType);
10368       return true;
10369     }
10370   };
10371 } // end anonymous namespace
10372 
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10373 static bool EvaluateArray(const Expr *E, const LValue &This,
10374                           APValue &Result, EvalInfo &Info) {
10375   assert(!E->isValueDependent());
10376   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10377   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10378 }
10379 
EvaluateArrayNewInitList(EvalInfo & Info,LValue & This,APValue & Result,const InitListExpr * ILE,QualType AllocType)10380 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10381                                      APValue &Result, const InitListExpr *ILE,
10382                                      QualType AllocType) {
10383   assert(!ILE->isValueDependent());
10384   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10385          "not an array rvalue");
10386   return ArrayExprEvaluator(Info, This, Result)
10387       .VisitInitListExpr(ILE, AllocType);
10388 }
10389 
EvaluateArrayNewConstructExpr(EvalInfo & Info,LValue & This,APValue & Result,const CXXConstructExpr * CCE,QualType AllocType)10390 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10391                                           APValue &Result,
10392                                           const CXXConstructExpr *CCE,
10393                                           QualType AllocType) {
10394   assert(!CCE->isValueDependent());
10395   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10396          "not an array rvalue");
10397   return ArrayExprEvaluator(Info, This, Result)
10398       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10399 }
10400 
10401 // Return true iff the given array filler may depend on the element index.
MaybeElementDependentArrayFiller(const Expr * FillerExpr)10402 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10403   // For now, just allow non-class value-initialization and initialization
10404   // lists comprised of them.
10405   if (isa<ImplicitValueInitExpr>(FillerExpr))
10406     return false;
10407   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10408     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10409       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10410         return true;
10411     }
10412     return false;
10413   }
10414   return true;
10415 }
10416 
VisitInitListExpr(const InitListExpr * E,QualType AllocType)10417 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10418                                            QualType AllocType) {
10419   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10420       AllocType.isNull() ? E->getType() : AllocType);
10421   if (!CAT)
10422     return Error(E);
10423 
10424   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10425   // an appropriately-typed string literal enclosed in braces.
10426   if (E->isStringLiteralInit()) {
10427     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10428     // FIXME: Support ObjCEncodeExpr here once we support it in
10429     // ArrayExprEvaluator generally.
10430     if (!SL)
10431       return Error(E);
10432     return VisitStringLiteral(SL, AllocType);
10433   }
10434 
10435   bool Success = true;
10436 
10437   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10438          "zero-initialized array shouldn't have any initialized elts");
10439   APValue Filler;
10440   if (Result.isArray() && Result.hasArrayFiller())
10441     Filler = Result.getArrayFiller();
10442 
10443   unsigned NumEltsToInit = E->getNumInits();
10444   unsigned NumElts = CAT->getSize().getZExtValue();
10445   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10446 
10447   // If the initializer might depend on the array index, run it for each
10448   // array element.
10449   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10450     NumEltsToInit = NumElts;
10451 
10452   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10453                           << NumEltsToInit << ".\n");
10454 
10455   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10456 
10457   // If the array was previously zero-initialized, preserve the
10458   // zero-initialized values.
10459   if (Filler.hasValue()) {
10460     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10461       Result.getArrayInitializedElt(I) = Filler;
10462     if (Result.hasArrayFiller())
10463       Result.getArrayFiller() = Filler;
10464   }
10465 
10466   LValue Subobject = This;
10467   Subobject.addArray(Info, E, CAT);
10468   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10469     const Expr *Init =
10470         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10471     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10472                          Info, Subobject, Init) ||
10473         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10474                                      CAT->getElementType(), 1)) {
10475       if (!Info.noteFailure())
10476         return false;
10477       Success = false;
10478     }
10479   }
10480 
10481   if (!Result.hasArrayFiller())
10482     return Success;
10483 
10484   // If we get here, we have a trivial filler, which we can just evaluate
10485   // once and splat over the rest of the array elements.
10486   assert(FillerExpr && "no array filler for incomplete init list");
10487   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10488                          FillerExpr) && Success;
10489 }
10490 
VisitArrayInitLoopExpr(const ArrayInitLoopExpr * E)10491 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10492   LValue CommonLV;
10493   if (E->getCommonExpr() &&
10494       !Evaluate(Info.CurrentCall->createTemporary(
10495                     E->getCommonExpr(),
10496                     getStorageType(Info.Ctx, E->getCommonExpr()),
10497                     ScopeKind::FullExpression, CommonLV),
10498                 Info, E->getCommonExpr()->getSourceExpr()))
10499     return false;
10500 
10501   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10502 
10503   uint64_t Elements = CAT->getSize().getZExtValue();
10504   Result = APValue(APValue::UninitArray(), Elements, Elements);
10505 
10506   LValue Subobject = This;
10507   Subobject.addArray(Info, E, CAT);
10508 
10509   bool Success = true;
10510   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10511     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10512                          Info, Subobject, E->getSubExpr()) ||
10513         !HandleLValueArrayAdjustment(Info, E, Subobject,
10514                                      CAT->getElementType(), 1)) {
10515       if (!Info.noteFailure())
10516         return false;
10517       Success = false;
10518     }
10519   }
10520 
10521   return Success;
10522 }
10523 
VisitCXXConstructExpr(const CXXConstructExpr * E)10524 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10525   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10526 }
10527 
VisitCXXConstructExpr(const CXXConstructExpr * E,const LValue & Subobject,APValue * Value,QualType Type)10528 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10529                                                const LValue &Subobject,
10530                                                APValue *Value,
10531                                                QualType Type) {
10532   bool HadZeroInit = Value->hasValue();
10533 
10534   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10535     unsigned N = CAT->getSize().getZExtValue();
10536 
10537     // Preserve the array filler if we had prior zero-initialization.
10538     APValue Filler =
10539       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10540                                              : APValue();
10541 
10542     *Value = APValue(APValue::UninitArray(), N, N);
10543 
10544     if (HadZeroInit)
10545       for (unsigned I = 0; I != N; ++I)
10546         Value->getArrayInitializedElt(I) = Filler;
10547 
10548     // Initialize the elements.
10549     LValue ArrayElt = Subobject;
10550     ArrayElt.addArray(Info, E, CAT);
10551     for (unsigned I = 0; I != N; ++I)
10552       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10553                                  CAT->getElementType()) ||
10554           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10555                                        CAT->getElementType(), 1))
10556         return false;
10557 
10558     return true;
10559   }
10560 
10561   if (!Type->isRecordType())
10562     return Error(E);
10563 
10564   return RecordExprEvaluator(Info, Subobject, *Value)
10565              .VisitCXXConstructExpr(E, Type);
10566 }
10567 
10568 //===----------------------------------------------------------------------===//
10569 // Integer Evaluation
10570 //
10571 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10572 // types and back in constant folding. Integer values are thus represented
10573 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10574 //===----------------------------------------------------------------------===//
10575 
10576 namespace {
10577 class IntExprEvaluator
10578         : public ExprEvaluatorBase<IntExprEvaluator> {
10579   APValue &Result;
10580 public:
IntExprEvaluator(EvalInfo & info,APValue & result)10581   IntExprEvaluator(EvalInfo &info, APValue &result)
10582       : ExprEvaluatorBaseTy(info), Result(result) {}
10583 
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)10584   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10585     assert(E->getType()->isIntegralOrEnumerationType() &&
10586            "Invalid evaluation result.");
10587     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10588            "Invalid evaluation result.");
10589     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10590            "Invalid evaluation result.");
10591     Result = APValue(SI);
10592     return true;
10593   }
Success(const llvm::APSInt & SI,const Expr * E)10594   bool Success(const llvm::APSInt &SI, const Expr *E) {
10595     return Success(SI, E, Result);
10596   }
10597 
Success(const llvm::APInt & I,const Expr * E,APValue & Result)10598   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10599     assert(E->getType()->isIntegralOrEnumerationType() &&
10600            "Invalid evaluation result.");
10601     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10602            "Invalid evaluation result.");
10603     Result = APValue(APSInt(I));
10604     Result.getInt().setIsUnsigned(
10605                             E->getType()->isUnsignedIntegerOrEnumerationType());
10606     return true;
10607   }
Success(const llvm::APInt & I,const Expr * E)10608   bool Success(const llvm::APInt &I, const Expr *E) {
10609     return Success(I, E, Result);
10610   }
10611 
Success(uint64_t Value,const Expr * E,APValue & Result)10612   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10613     assert(E->getType()->isIntegralOrEnumerationType() &&
10614            "Invalid evaluation result.");
10615     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10616     return true;
10617   }
Success(uint64_t Value,const Expr * E)10618   bool Success(uint64_t Value, const Expr *E) {
10619     return Success(Value, E, Result);
10620   }
10621 
Success(CharUnits Size,const Expr * E)10622   bool Success(CharUnits Size, const Expr *E) {
10623     return Success(Size.getQuantity(), E);
10624   }
10625 
Success(const APValue & V,const Expr * E)10626   bool Success(const APValue &V, const Expr *E) {
10627     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10628       Result = V;
10629       return true;
10630     }
10631     return Success(V.getInt(), E);
10632   }
10633 
ZeroInitialization(const Expr * E)10634   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10635 
10636   //===--------------------------------------------------------------------===//
10637   //                            Visitor Methods
10638   //===--------------------------------------------------------------------===//
10639 
VisitIntegerLiteral(const IntegerLiteral * E)10640   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10641     return Success(E->getValue(), E);
10642   }
VisitCharacterLiteral(const CharacterLiteral * E)10643   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10644     return Success(E->getValue(), E);
10645   }
10646 
10647   bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)10648   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10649     if (CheckReferencedDecl(E, E->getDecl()))
10650       return true;
10651 
10652     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10653   }
VisitMemberExpr(const MemberExpr * E)10654   bool VisitMemberExpr(const MemberExpr *E) {
10655     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10656       VisitIgnoredBaseExpression(E->getBase());
10657       return true;
10658     }
10659 
10660     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10661   }
10662 
10663   bool VisitCallExpr(const CallExpr *E);
10664   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10665   bool VisitBinaryOperator(const BinaryOperator *E);
10666   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10667   bool VisitUnaryOperator(const UnaryOperator *E);
10668 
10669   bool VisitCastExpr(const CastExpr* E);
10670   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10671 
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)10672   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10673     return Success(E->getValue(), E);
10674   }
10675 
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)10676   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10677     return Success(E->getValue(), E);
10678   }
10679 
VisitArrayInitIndexExpr(const ArrayInitIndexExpr * E)10680   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10681     if (Info.ArrayInitIndex == uint64_t(-1)) {
10682       // We were asked to evaluate this subexpression independent of the
10683       // enclosing ArrayInitLoopExpr. We can't do that.
10684       Info.FFDiag(E);
10685       return false;
10686     }
10687     return Success(Info.ArrayInitIndex, E);
10688   }
10689 
10690   // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)10691   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10692     return ZeroInitialization(E);
10693   }
10694 
VisitTypeTraitExpr(const TypeTraitExpr * E)10695   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10696     return Success(E->getValue(), E);
10697   }
10698 
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)10699   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10700     return Success(E->getValue(), E);
10701   }
10702 
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)10703   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10704     return Success(E->getValue(), E);
10705   }
10706 
10707   bool VisitUnaryReal(const UnaryOperator *E);
10708   bool VisitUnaryImag(const UnaryOperator *E);
10709 
10710   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10711   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10712   bool VisitSourceLocExpr(const SourceLocExpr *E);
10713   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10714   bool VisitRequiresExpr(const RequiresExpr *E);
10715   // FIXME: Missing: array subscript of vector, member of vector
10716 };
10717 
10718 class FixedPointExprEvaluator
10719     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10720   APValue &Result;
10721 
10722  public:
FixedPointExprEvaluator(EvalInfo & info,APValue & result)10723   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10724       : ExprEvaluatorBaseTy(info), Result(result) {}
10725 
Success(const llvm::APInt & I,const Expr * E)10726   bool Success(const llvm::APInt &I, const Expr *E) {
10727     return Success(
10728         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10729   }
10730 
Success(uint64_t Value,const Expr * E)10731   bool Success(uint64_t Value, const Expr *E) {
10732     return Success(
10733         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10734   }
10735 
Success(const APValue & V,const Expr * E)10736   bool Success(const APValue &V, const Expr *E) {
10737     return Success(V.getFixedPoint(), E);
10738   }
10739 
Success(const APFixedPoint & V,const Expr * E)10740   bool Success(const APFixedPoint &V, const Expr *E) {
10741     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10742     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10743            "Invalid evaluation result.");
10744     Result = APValue(V);
10745     return true;
10746   }
10747 
10748   //===--------------------------------------------------------------------===//
10749   //                            Visitor Methods
10750   //===--------------------------------------------------------------------===//
10751 
VisitFixedPointLiteral(const FixedPointLiteral * E)10752   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10753     return Success(E->getValue(), E);
10754   }
10755 
10756   bool VisitCastExpr(const CastExpr *E);
10757   bool VisitUnaryOperator(const UnaryOperator *E);
10758   bool VisitBinaryOperator(const BinaryOperator *E);
10759 };
10760 } // end anonymous namespace
10761 
10762 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10763 /// produce either the integer value or a pointer.
10764 ///
10765 /// GCC has a heinous extension which folds casts between pointer types and
10766 /// pointer-sized integral types. We support this by allowing the evaluation of
10767 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10768 /// Some simple arithmetic on such values is supported (they are treated much
10769 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)10770 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10771                                     EvalInfo &Info) {
10772   assert(!E->isValueDependent());
10773   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10774   return IntExprEvaluator(Info, Result).Visit(E);
10775 }
10776 
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)10777 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10778   assert(!E->isValueDependent());
10779   APValue Val;
10780   if (!EvaluateIntegerOrLValue(E, Val, Info))
10781     return false;
10782   if (!Val.isInt()) {
10783     // FIXME: It would be better to produce the diagnostic for casting
10784     //        a pointer to an integer.
10785     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10786     return false;
10787   }
10788   Result = Val.getInt();
10789   return true;
10790 }
10791 
VisitSourceLocExpr(const SourceLocExpr * E)10792 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10793   APValue Evaluated = E->EvaluateInContext(
10794       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10795   return Success(Evaluated, E);
10796 }
10797 
EvaluateFixedPoint(const Expr * E,APFixedPoint & Result,EvalInfo & Info)10798 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10799                                EvalInfo &Info) {
10800   assert(!E->isValueDependent());
10801   if (E->getType()->isFixedPointType()) {
10802     APValue Val;
10803     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10804       return false;
10805     if (!Val.isFixedPoint())
10806       return false;
10807 
10808     Result = Val.getFixedPoint();
10809     return true;
10810   }
10811   return false;
10812 }
10813 
EvaluateFixedPointOrInteger(const Expr * E,APFixedPoint & Result,EvalInfo & Info)10814 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10815                                         EvalInfo &Info) {
10816   assert(!E->isValueDependent());
10817   if (E->getType()->isIntegerType()) {
10818     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10819     APSInt Val;
10820     if (!EvaluateInteger(E, Val, Info))
10821       return false;
10822     Result = APFixedPoint(Val, FXSema);
10823     return true;
10824   } else if (E->getType()->isFixedPointType()) {
10825     return EvaluateFixedPoint(E, Result, Info);
10826   }
10827   return false;
10828 }
10829 
10830 /// Check whether the given declaration can be directly converted to an integral
10831 /// rvalue. If not, no diagnostic is produced; there are other things we can
10832 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)10833 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10834   // Enums are integer constant exprs.
10835   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10836     // Check for signedness/width mismatches between E type and ECD value.
10837     bool SameSign = (ECD->getInitVal().isSigned()
10838                      == E->getType()->isSignedIntegerOrEnumerationType());
10839     bool SameWidth = (ECD->getInitVal().getBitWidth()
10840                       == Info.Ctx.getIntWidth(E->getType()));
10841     if (SameSign && SameWidth)
10842       return Success(ECD->getInitVal(), E);
10843     else {
10844       // Get rid of mismatch (otherwise Success assertions will fail)
10845       // by computing a new value matching the type of E.
10846       llvm::APSInt Val = ECD->getInitVal();
10847       if (!SameSign)
10848         Val.setIsSigned(!ECD->getInitVal().isSigned());
10849       if (!SameWidth)
10850         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10851       return Success(Val, E);
10852     }
10853   }
10854   return false;
10855 }
10856 
10857 /// Values returned by __builtin_classify_type, chosen to match the values
10858 /// produced by GCC's builtin.
10859 enum class GCCTypeClass {
10860   None = -1,
10861   Void = 0,
10862   Integer = 1,
10863   // GCC reserves 2 for character types, but instead classifies them as
10864   // integers.
10865   Enum = 3,
10866   Bool = 4,
10867   Pointer = 5,
10868   // GCC reserves 6 for references, but appears to never use it (because
10869   // expressions never have reference type, presumably).
10870   PointerToDataMember = 7,
10871   RealFloat = 8,
10872   Complex = 9,
10873   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10874   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10875   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10876   // uses 12 for that purpose, same as for a class or struct. Maybe it
10877   // internally implements a pointer to member as a struct?  Who knows.
10878   PointerToMemberFunction = 12, // Not a bug, see above.
10879   ClassOrStruct = 12,
10880   Union = 13,
10881   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10882   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10883   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10884   // literals.
10885 };
10886 
10887 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10888 /// as GCC.
10889 static GCCTypeClass
EvaluateBuiltinClassifyType(QualType T,const LangOptions & LangOpts)10890 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10891   assert(!T->isDependentType() && "unexpected dependent type");
10892 
10893   QualType CanTy = T.getCanonicalType();
10894   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10895 
10896   switch (CanTy->getTypeClass()) {
10897 #define TYPE(ID, BASE)
10898 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10899 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10900 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10901 #include "clang/AST/TypeNodes.inc"
10902   case Type::Auto:
10903   case Type::DeducedTemplateSpecialization:
10904       llvm_unreachable("unexpected non-canonical or dependent type");
10905 
10906   case Type::Builtin:
10907     switch (BT->getKind()) {
10908 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10909 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10910     case BuiltinType::ID: return GCCTypeClass::Integer;
10911 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10912     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10913 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10914     case BuiltinType::ID: break;
10915 #include "clang/AST/BuiltinTypes.def"
10916     case BuiltinType::Void:
10917       return GCCTypeClass::Void;
10918 
10919     case BuiltinType::Bool:
10920       return GCCTypeClass::Bool;
10921 
10922     case BuiltinType::Char_U:
10923     case BuiltinType::UChar:
10924     case BuiltinType::WChar_U:
10925     case BuiltinType::Char8:
10926     case BuiltinType::Char16:
10927     case BuiltinType::Char32:
10928     case BuiltinType::UShort:
10929     case BuiltinType::UInt:
10930     case BuiltinType::ULong:
10931     case BuiltinType::ULongLong:
10932     case BuiltinType::UInt128:
10933       return GCCTypeClass::Integer;
10934 
10935     case BuiltinType::UShortAccum:
10936     case BuiltinType::UAccum:
10937     case BuiltinType::ULongAccum:
10938     case BuiltinType::UShortFract:
10939     case BuiltinType::UFract:
10940     case BuiltinType::ULongFract:
10941     case BuiltinType::SatUShortAccum:
10942     case BuiltinType::SatUAccum:
10943     case BuiltinType::SatULongAccum:
10944     case BuiltinType::SatUShortFract:
10945     case BuiltinType::SatUFract:
10946     case BuiltinType::SatULongFract:
10947       return GCCTypeClass::None;
10948 
10949     case BuiltinType::NullPtr:
10950 
10951     case BuiltinType::ObjCId:
10952     case BuiltinType::ObjCClass:
10953     case BuiltinType::ObjCSel:
10954 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10955     case BuiltinType::Id:
10956 #include "clang/Basic/OpenCLImageTypes.def"
10957 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10958     case BuiltinType::Id:
10959 #include "clang/Basic/OpenCLExtensionTypes.def"
10960     case BuiltinType::OCLSampler:
10961     case BuiltinType::OCLEvent:
10962     case BuiltinType::OCLClkEvent:
10963     case BuiltinType::OCLQueue:
10964     case BuiltinType::OCLReserveID:
10965 #define SVE_TYPE(Name, Id, SingletonId) \
10966     case BuiltinType::Id:
10967 #include "clang/Basic/AArch64SVEACLETypes.def"
10968 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
10969     case BuiltinType::Id:
10970 #include "clang/Basic/PPCTypes.def"
10971       return GCCTypeClass::None;
10972 
10973     case BuiltinType::Dependent:
10974       llvm_unreachable("unexpected dependent type");
10975     };
10976     llvm_unreachable("unexpected placeholder type");
10977 
10978   case Type::Enum:
10979     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10980 
10981   case Type::Pointer:
10982   case Type::ConstantArray:
10983   case Type::VariableArray:
10984   case Type::IncompleteArray:
10985   case Type::FunctionNoProto:
10986   case Type::FunctionProto:
10987     return GCCTypeClass::Pointer;
10988 
10989   case Type::MemberPointer:
10990     return CanTy->isMemberDataPointerType()
10991                ? GCCTypeClass::PointerToDataMember
10992                : GCCTypeClass::PointerToMemberFunction;
10993 
10994   case Type::Complex:
10995     return GCCTypeClass::Complex;
10996 
10997   case Type::Record:
10998     return CanTy->isUnionType() ? GCCTypeClass::Union
10999                                 : GCCTypeClass::ClassOrStruct;
11000 
11001   case Type::Atomic:
11002     // GCC classifies _Atomic T the same as T.
11003     return EvaluateBuiltinClassifyType(
11004         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11005 
11006   case Type::BlockPointer:
11007   case Type::Vector:
11008   case Type::ExtVector:
11009   case Type::ConstantMatrix:
11010   case Type::ObjCObject:
11011   case Type::ObjCInterface:
11012   case Type::ObjCObjectPointer:
11013   case Type::Pipe:
11014   case Type::ExtInt:
11015     // GCC classifies vectors as None. We follow its lead and classify all
11016     // other types that don't fit into the regular classification the same way.
11017     return GCCTypeClass::None;
11018 
11019   case Type::LValueReference:
11020   case Type::RValueReference:
11021     llvm_unreachable("invalid type for expression");
11022   }
11023 
11024   llvm_unreachable("unexpected type class");
11025 }
11026 
11027 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11028 /// as GCC.
11029 static GCCTypeClass
EvaluateBuiltinClassifyType(const CallExpr * E,const LangOptions & LangOpts)11030 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11031   // If no argument was supplied, default to None. This isn't
11032   // ideal, however it is what gcc does.
11033   if (E->getNumArgs() == 0)
11034     return GCCTypeClass::None;
11035 
11036   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11037   // being an ICE, but still folds it to a constant using the type of the first
11038   // argument.
11039   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11040 }
11041 
11042 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11043 /// __builtin_constant_p when applied to the given pointer.
11044 ///
11045 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11046 /// or it points to the first character of a string literal.
EvaluateBuiltinConstantPForLValue(const APValue & LV)11047 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11048   APValue::LValueBase Base = LV.getLValueBase();
11049   if (Base.isNull()) {
11050     // A null base is acceptable.
11051     return true;
11052   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11053     if (!isa<StringLiteral>(E))
11054       return false;
11055     return LV.getLValueOffset().isZero();
11056   } else if (Base.is<TypeInfoLValue>()) {
11057     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11058     // evaluate to true.
11059     return true;
11060   } else {
11061     // Any other base is not constant enough for GCC.
11062     return false;
11063   }
11064 }
11065 
11066 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11067 /// GCC as we can manage.
EvaluateBuiltinConstantP(EvalInfo & Info,const Expr * Arg)11068 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11069   // This evaluation is not permitted to have side-effects, so evaluate it in
11070   // a speculative evaluation context.
11071   SpeculativeEvaluationRAII SpeculativeEval(Info);
11072 
11073   // Constant-folding is always enabled for the operand of __builtin_constant_p
11074   // (even when the enclosing evaluation context otherwise requires a strict
11075   // language-specific constant expression).
11076   FoldConstant Fold(Info, true);
11077 
11078   QualType ArgType = Arg->getType();
11079 
11080   // __builtin_constant_p always has one operand. The rules which gcc follows
11081   // are not precisely documented, but are as follows:
11082   //
11083   //  - If the operand is of integral, floating, complex or enumeration type,
11084   //    and can be folded to a known value of that type, it returns 1.
11085   //  - If the operand can be folded to a pointer to the first character
11086   //    of a string literal (or such a pointer cast to an integral type)
11087   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11088   //
11089   // Otherwise, it returns 0.
11090   //
11091   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11092   // its support for this did not work prior to GCC 9 and is not yet well
11093   // understood.
11094   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11095       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11096       ArgType->isNullPtrType()) {
11097     APValue V;
11098     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11099       Fold.keepDiagnostics();
11100       return false;
11101     }
11102 
11103     // For a pointer (possibly cast to integer), there are special rules.
11104     if (V.getKind() == APValue::LValue)
11105       return EvaluateBuiltinConstantPForLValue(V);
11106 
11107     // Otherwise, any constant value is good enough.
11108     return V.hasValue();
11109   }
11110 
11111   // Anything else isn't considered to be sufficiently constant.
11112   return false;
11113 }
11114 
11115 /// Retrieves the "underlying object type" of the given expression,
11116 /// as used by __builtin_object_size.
getObjectType(APValue::LValueBase B)11117 static QualType getObjectType(APValue::LValueBase B) {
11118   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11119     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11120       return VD->getType();
11121   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11122     if (isa<CompoundLiteralExpr>(E))
11123       return E->getType();
11124   } else if (B.is<TypeInfoLValue>()) {
11125     return B.getTypeInfoType();
11126   } else if (B.is<DynamicAllocLValue>()) {
11127     return B.getDynamicAllocType();
11128   }
11129 
11130   return QualType();
11131 }
11132 
11133 /// A more selective version of E->IgnoreParenCasts for
11134 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11135 /// to change the type of E.
11136 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11137 ///
11138 /// Always returns an RValue with a pointer representation.
ignorePointerCastsAndParens(const Expr * E)11139 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11140   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
11141 
11142   auto *NoParens = E->IgnoreParens();
11143   auto *Cast = dyn_cast<CastExpr>(NoParens);
11144   if (Cast == nullptr)
11145     return NoParens;
11146 
11147   // We only conservatively allow a few kinds of casts, because this code is
11148   // inherently a simple solution that seeks to support the common case.
11149   auto CastKind = Cast->getCastKind();
11150   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11151       CastKind != CK_AddressSpaceConversion)
11152     return NoParens;
11153 
11154   auto *SubExpr = Cast->getSubExpr();
11155   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
11156     return NoParens;
11157   return ignorePointerCastsAndParens(SubExpr);
11158 }
11159 
11160 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11161 /// record layout. e.g.
11162 ///   struct { struct { int a, b; } fst, snd; } obj;
11163 ///   obj.fst   // no
11164 ///   obj.snd   // yes
11165 ///   obj.fst.a // no
11166 ///   obj.fst.b // no
11167 ///   obj.snd.a // no
11168 ///   obj.snd.b // yes
11169 ///
11170 /// Please note: this function is specialized for how __builtin_object_size
11171 /// views "objects".
11172 ///
11173 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11174 /// correct result, it will always return true.
isDesignatorAtObjectEnd(const ASTContext & Ctx,const LValue & LVal)11175 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11176   assert(!LVal.Designator.Invalid);
11177 
11178   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11179     const RecordDecl *Parent = FD->getParent();
11180     Invalid = Parent->isInvalidDecl();
11181     if (Invalid || Parent->isUnion())
11182       return true;
11183     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11184     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11185   };
11186 
11187   auto &Base = LVal.getLValueBase();
11188   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11189     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11190       bool Invalid;
11191       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11192         return Invalid;
11193     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11194       for (auto *FD : IFD->chain()) {
11195         bool Invalid;
11196         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11197           return Invalid;
11198       }
11199     }
11200   }
11201 
11202   unsigned I = 0;
11203   QualType BaseType = getType(Base);
11204   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11205     // If we don't know the array bound, conservatively assume we're looking at
11206     // the final array element.
11207     ++I;
11208     if (BaseType->isIncompleteArrayType())
11209       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11210     else
11211       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11212   }
11213 
11214   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11215     const auto &Entry = LVal.Designator.Entries[I];
11216     if (BaseType->isArrayType()) {
11217       // Because __builtin_object_size treats arrays as objects, we can ignore
11218       // the index iff this is the last array in the Designator.
11219       if (I + 1 == E)
11220         return true;
11221       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11222       uint64_t Index = Entry.getAsArrayIndex();
11223       if (Index + 1 != CAT->getSize())
11224         return false;
11225       BaseType = CAT->getElementType();
11226     } else if (BaseType->isAnyComplexType()) {
11227       const auto *CT = BaseType->castAs<ComplexType>();
11228       uint64_t Index = Entry.getAsArrayIndex();
11229       if (Index != 1)
11230         return false;
11231       BaseType = CT->getElementType();
11232     } else if (auto *FD = getAsField(Entry)) {
11233       bool Invalid;
11234       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11235         return Invalid;
11236       BaseType = FD->getType();
11237     } else {
11238       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11239       return false;
11240     }
11241   }
11242   return true;
11243 }
11244 
11245 /// Tests to see if the LValue has a user-specified designator (that isn't
11246 /// necessarily valid). Note that this always returns 'true' if the LValue has
11247 /// an unsized array as its first designator entry, because there's currently no
11248 /// way to tell if the user typed *foo or foo[0].
refersToCompleteObject(const LValue & LVal)11249 static bool refersToCompleteObject(const LValue &LVal) {
11250   if (LVal.Designator.Invalid)
11251     return false;
11252 
11253   if (!LVal.Designator.Entries.empty())
11254     return LVal.Designator.isMostDerivedAnUnsizedArray();
11255 
11256   if (!LVal.InvalidBase)
11257     return true;
11258 
11259   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11260   // the LValueBase.
11261   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11262   return !E || !isa<MemberExpr>(E);
11263 }
11264 
11265 /// Attempts to detect a user writing into a piece of memory that's impossible
11266 /// to figure out the size of by just using types.
isUserWritingOffTheEnd(const ASTContext & Ctx,const LValue & LVal)11267 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11268   const SubobjectDesignator &Designator = LVal.Designator;
11269   // Notes:
11270   // - Users can only write off of the end when we have an invalid base. Invalid
11271   //   bases imply we don't know where the memory came from.
11272   // - We used to be a bit more aggressive here; we'd only be conservative if
11273   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11274   //   broke some common standard library extensions (PR30346), but was
11275   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11276   //   with some sort of list. OTOH, it seems that GCC is always
11277   //   conservative with the last element in structs (if it's an array), so our
11278   //   current behavior is more compatible than an explicit list approach would
11279   //   be.
11280   return LVal.InvalidBase &&
11281          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11282          Designator.MostDerivedIsArrayElement &&
11283          isDesignatorAtObjectEnd(Ctx, LVal);
11284 }
11285 
11286 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11287 /// Fails if the conversion would cause loss of precision.
convertUnsignedAPIntToCharUnits(const llvm::APInt & Int,CharUnits & Result)11288 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11289                                             CharUnits &Result) {
11290   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11291   if (Int.ugt(CharUnitsMax))
11292     return false;
11293   Result = CharUnits::fromQuantity(Int.getZExtValue());
11294   return true;
11295 }
11296 
11297 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11298 /// determine how many bytes exist from the beginning of the object to either
11299 /// the end of the current subobject, or the end of the object itself, depending
11300 /// on what the LValue looks like + the value of Type.
11301 ///
11302 /// If this returns false, the value of Result is undefined.
determineEndOffset(EvalInfo & Info,SourceLocation ExprLoc,unsigned Type,const LValue & LVal,CharUnits & EndOffset)11303 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11304                                unsigned Type, const LValue &LVal,
11305                                CharUnits &EndOffset) {
11306   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11307 
11308   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11309     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11310       return false;
11311     return HandleSizeof(Info, ExprLoc, Ty, Result);
11312   };
11313 
11314   // We want to evaluate the size of the entire object. This is a valid fallback
11315   // for when Type=1 and the designator is invalid, because we're asked for an
11316   // upper-bound.
11317   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11318     // Type=3 wants a lower bound, so we can't fall back to this.
11319     if (Type == 3 && !DetermineForCompleteObject)
11320       return false;
11321 
11322     llvm::APInt APEndOffset;
11323     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11324         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11325       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11326 
11327     if (LVal.InvalidBase)
11328       return false;
11329 
11330     QualType BaseTy = getObjectType(LVal.getLValueBase());
11331     return CheckedHandleSizeof(BaseTy, EndOffset);
11332   }
11333 
11334   // We want to evaluate the size of a subobject.
11335   const SubobjectDesignator &Designator = LVal.Designator;
11336 
11337   // The following is a moderately common idiom in C:
11338   //
11339   // struct Foo { int a; char c[1]; };
11340   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11341   // strcpy(&F->c[0], Bar);
11342   //
11343   // In order to not break too much legacy code, we need to support it.
11344   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11345     // If we can resolve this to an alloc_size call, we can hand that back,
11346     // because we know for certain how many bytes there are to write to.
11347     llvm::APInt APEndOffset;
11348     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11349         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11350       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11351 
11352     // If we cannot determine the size of the initial allocation, then we can't
11353     // given an accurate upper-bound. However, we are still able to give
11354     // conservative lower-bounds for Type=3.
11355     if (Type == 1)
11356       return false;
11357   }
11358 
11359   CharUnits BytesPerElem;
11360   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11361     return false;
11362 
11363   // According to the GCC documentation, we want the size of the subobject
11364   // denoted by the pointer. But that's not quite right -- what we actually
11365   // want is the size of the immediately-enclosing array, if there is one.
11366   int64_t ElemsRemaining;
11367   if (Designator.MostDerivedIsArrayElement &&
11368       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11369     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11370     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11371     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11372   } else {
11373     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11374   }
11375 
11376   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11377   return true;
11378 }
11379 
11380 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11381 /// returns true and stores the result in @p Size.
11382 ///
11383 /// If @p WasError is non-null, this will report whether the failure to evaluate
11384 /// is to be treated as an Error in IntExprEvaluator.
tryEvaluateBuiltinObjectSize(const Expr * E,unsigned Type,EvalInfo & Info,uint64_t & Size)11385 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11386                                          EvalInfo &Info, uint64_t &Size) {
11387   // Determine the denoted object.
11388   LValue LVal;
11389   {
11390     // The operand of __builtin_object_size is never evaluated for side-effects.
11391     // If there are any, but we can determine the pointed-to object anyway, then
11392     // ignore the side-effects.
11393     SpeculativeEvaluationRAII SpeculativeEval(Info);
11394     IgnoreSideEffectsRAII Fold(Info);
11395 
11396     if (E->isGLValue()) {
11397       // It's possible for us to be given GLValues if we're called via
11398       // Expr::tryEvaluateObjectSize.
11399       APValue RVal;
11400       if (!EvaluateAsRValue(Info, E, RVal))
11401         return false;
11402       LVal.setFrom(Info.Ctx, RVal);
11403     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11404                                 /*InvalidBaseOK=*/true))
11405       return false;
11406   }
11407 
11408   // If we point to before the start of the object, there are no accessible
11409   // bytes.
11410   if (LVal.getLValueOffset().isNegative()) {
11411     Size = 0;
11412     return true;
11413   }
11414 
11415   CharUnits EndOffset;
11416   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11417     return false;
11418 
11419   // If we've fallen outside of the end offset, just pretend there's nothing to
11420   // write to/read from.
11421   if (EndOffset <= LVal.getLValueOffset())
11422     Size = 0;
11423   else
11424     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11425   return true;
11426 }
11427 
VisitCallExpr(const CallExpr * E)11428 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11429   if (unsigned BuiltinOp = E->getBuiltinCallee())
11430     return VisitBuiltinCallExpr(E, BuiltinOp);
11431 
11432   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11433 }
11434 
getBuiltinAlignArguments(const CallExpr * E,EvalInfo & Info,APValue & Val,APSInt & Alignment)11435 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11436                                      APValue &Val, APSInt &Alignment) {
11437   QualType SrcTy = E->getArg(0)->getType();
11438   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11439     return false;
11440   // Even though we are evaluating integer expressions we could get a pointer
11441   // argument for the __builtin_is_aligned() case.
11442   if (SrcTy->isPointerType()) {
11443     LValue Ptr;
11444     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11445       return false;
11446     Ptr.moveInto(Val);
11447   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11448     Info.FFDiag(E->getArg(0));
11449     return false;
11450   } else {
11451     APSInt SrcInt;
11452     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11453       return false;
11454     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11455            "Bit widths must be the same");
11456     Val = APValue(SrcInt);
11457   }
11458   assert(Val.hasValue());
11459   return true;
11460 }
11461 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)11462 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11463                                             unsigned BuiltinOp) {
11464   switch (BuiltinOp) {
11465   default:
11466     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11467 
11468   case Builtin::BI__builtin_dynamic_object_size:
11469   case Builtin::BI__builtin_object_size: {
11470     // The type was checked when we built the expression.
11471     unsigned Type =
11472         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11473     assert(Type <= 3 && "unexpected type");
11474 
11475     uint64_t Size;
11476     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11477       return Success(Size, E);
11478 
11479     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11480       return Success((Type & 2) ? 0 : -1, E);
11481 
11482     // Expression had no side effects, but we couldn't statically determine the
11483     // size of the referenced object.
11484     switch (Info.EvalMode) {
11485     case EvalInfo::EM_ConstantExpression:
11486     case EvalInfo::EM_ConstantFold:
11487     case EvalInfo::EM_IgnoreSideEffects:
11488       // Leave it to IR generation.
11489       return Error(E);
11490     case EvalInfo::EM_ConstantExpressionUnevaluated:
11491       // Reduce it to a constant now.
11492       return Success((Type & 2) ? 0 : -1, E);
11493     }
11494 
11495     llvm_unreachable("unexpected EvalMode");
11496   }
11497 
11498   case Builtin::BI__builtin_os_log_format_buffer_size: {
11499     analyze_os_log::OSLogBufferLayout Layout;
11500     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11501     return Success(Layout.size().getQuantity(), E);
11502   }
11503 
11504   case Builtin::BI__builtin_is_aligned: {
11505     APValue Src;
11506     APSInt Alignment;
11507     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11508       return false;
11509     if (Src.isLValue()) {
11510       // If we evaluated a pointer, check the minimum known alignment.
11511       LValue Ptr;
11512       Ptr.setFrom(Info.Ctx, Src);
11513       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11514       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11515       // We can return true if the known alignment at the computed offset is
11516       // greater than the requested alignment.
11517       assert(PtrAlign.isPowerOfTwo());
11518       assert(Alignment.isPowerOf2());
11519       if (PtrAlign.getQuantity() >= Alignment)
11520         return Success(1, E);
11521       // If the alignment is not known to be sufficient, some cases could still
11522       // be aligned at run time. However, if the requested alignment is less or
11523       // equal to the base alignment and the offset is not aligned, we know that
11524       // the run-time value can never be aligned.
11525       if (BaseAlignment.getQuantity() >= Alignment &&
11526           PtrAlign.getQuantity() < Alignment)
11527         return Success(0, E);
11528       // Otherwise we can't infer whether the value is sufficiently aligned.
11529       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11530       //  in cases where we can't fully evaluate the pointer.
11531       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11532           << Alignment;
11533       return false;
11534     }
11535     assert(Src.isInt());
11536     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11537   }
11538   case Builtin::BI__builtin_align_up: {
11539     APValue Src;
11540     APSInt Alignment;
11541     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11542       return false;
11543     if (!Src.isInt())
11544       return Error(E);
11545     APSInt AlignedVal =
11546         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11547                Src.getInt().isUnsigned());
11548     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11549     return Success(AlignedVal, E);
11550   }
11551   case Builtin::BI__builtin_align_down: {
11552     APValue Src;
11553     APSInt Alignment;
11554     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11555       return false;
11556     if (!Src.isInt())
11557       return Error(E);
11558     APSInt AlignedVal =
11559         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11560     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11561     return Success(AlignedVal, E);
11562   }
11563 
11564   case Builtin::BI__builtin_bitreverse8:
11565   case Builtin::BI__builtin_bitreverse16:
11566   case Builtin::BI__builtin_bitreverse32:
11567   case Builtin::BI__builtin_bitreverse64: {
11568     APSInt Val;
11569     if (!EvaluateInteger(E->getArg(0), Val, Info))
11570       return false;
11571 
11572     return Success(Val.reverseBits(), E);
11573   }
11574 
11575   case Builtin::BI__builtin_bswap16:
11576   case Builtin::BI__builtin_bswap32:
11577   case Builtin::BI__builtin_bswap64: {
11578     APSInt Val;
11579     if (!EvaluateInteger(E->getArg(0), Val, Info))
11580       return false;
11581 
11582     return Success(Val.byteSwap(), E);
11583   }
11584 
11585   case Builtin::BI__builtin_classify_type:
11586     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11587 
11588   case Builtin::BI__builtin_clrsb:
11589   case Builtin::BI__builtin_clrsbl:
11590   case Builtin::BI__builtin_clrsbll: {
11591     APSInt Val;
11592     if (!EvaluateInteger(E->getArg(0), Val, Info))
11593       return false;
11594 
11595     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11596   }
11597 
11598   case Builtin::BI__builtin_clz:
11599   case Builtin::BI__builtin_clzl:
11600   case Builtin::BI__builtin_clzll:
11601   case Builtin::BI__builtin_clzs: {
11602     APSInt Val;
11603     if (!EvaluateInteger(E->getArg(0), Val, Info))
11604       return false;
11605     if (!Val)
11606       return Error(E);
11607 
11608     return Success(Val.countLeadingZeros(), E);
11609   }
11610 
11611   case Builtin::BI__builtin_constant_p: {
11612     const Expr *Arg = E->getArg(0);
11613     if (EvaluateBuiltinConstantP(Info, Arg))
11614       return Success(true, E);
11615     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11616       // Outside a constant context, eagerly evaluate to false in the presence
11617       // of side-effects in order to avoid -Wunsequenced false-positives in
11618       // a branch on __builtin_constant_p(expr).
11619       return Success(false, E);
11620     }
11621     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11622     return false;
11623   }
11624 
11625   case Builtin::BI__builtin_is_constant_evaluated: {
11626     const auto *Callee = Info.CurrentCall->getCallee();
11627     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11628         (Info.CallStackDepth == 1 ||
11629          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11630           Callee->getIdentifier() &&
11631           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11632       // FIXME: Find a better way to avoid duplicated diagnostics.
11633       if (Info.EvalStatus.Diag)
11634         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11635                                                : Info.CurrentCall->CallLoc,
11636                     diag::warn_is_constant_evaluated_always_true_constexpr)
11637             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11638                                          : "std::is_constant_evaluated");
11639     }
11640 
11641     return Success(Info.InConstantContext, E);
11642   }
11643 
11644   case Builtin::BI__builtin_ctz:
11645   case Builtin::BI__builtin_ctzl:
11646   case Builtin::BI__builtin_ctzll:
11647   case Builtin::BI__builtin_ctzs: {
11648     APSInt Val;
11649     if (!EvaluateInteger(E->getArg(0), Val, Info))
11650       return false;
11651     if (!Val)
11652       return Error(E);
11653 
11654     return Success(Val.countTrailingZeros(), E);
11655   }
11656 
11657   case Builtin::BI__builtin_eh_return_data_regno: {
11658     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11659     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11660     return Success(Operand, E);
11661   }
11662 
11663   case Builtin::BI__builtin_expect:
11664   case Builtin::BI__builtin_expect_with_probability:
11665     return Visit(E->getArg(0));
11666 
11667   case Builtin::BI__builtin_ffs:
11668   case Builtin::BI__builtin_ffsl:
11669   case Builtin::BI__builtin_ffsll: {
11670     APSInt Val;
11671     if (!EvaluateInteger(E->getArg(0), Val, Info))
11672       return false;
11673 
11674     unsigned N = Val.countTrailingZeros();
11675     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11676   }
11677 
11678   case Builtin::BI__builtin_fpclassify: {
11679     APFloat Val(0.0);
11680     if (!EvaluateFloat(E->getArg(5), Val, Info))
11681       return false;
11682     unsigned Arg;
11683     switch (Val.getCategory()) {
11684     case APFloat::fcNaN: Arg = 0; break;
11685     case APFloat::fcInfinity: Arg = 1; break;
11686     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11687     case APFloat::fcZero: Arg = 4; break;
11688     }
11689     return Visit(E->getArg(Arg));
11690   }
11691 
11692   case Builtin::BI__builtin_isinf_sign: {
11693     APFloat Val(0.0);
11694     return EvaluateFloat(E->getArg(0), Val, Info) &&
11695            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11696   }
11697 
11698   case Builtin::BI__builtin_isinf: {
11699     APFloat Val(0.0);
11700     return EvaluateFloat(E->getArg(0), Val, Info) &&
11701            Success(Val.isInfinity() ? 1 : 0, E);
11702   }
11703 
11704   case Builtin::BI__builtin_isfinite: {
11705     APFloat Val(0.0);
11706     return EvaluateFloat(E->getArg(0), Val, Info) &&
11707            Success(Val.isFinite() ? 1 : 0, E);
11708   }
11709 
11710   case Builtin::BI__builtin_isnan: {
11711     APFloat Val(0.0);
11712     return EvaluateFloat(E->getArg(0), Val, Info) &&
11713            Success(Val.isNaN() ? 1 : 0, E);
11714   }
11715 
11716   case Builtin::BI__builtin_isnormal: {
11717     APFloat Val(0.0);
11718     return EvaluateFloat(E->getArg(0), Val, Info) &&
11719            Success(Val.isNormal() ? 1 : 0, E);
11720   }
11721 
11722   case Builtin::BI__builtin_parity:
11723   case Builtin::BI__builtin_parityl:
11724   case Builtin::BI__builtin_parityll: {
11725     APSInt Val;
11726     if (!EvaluateInteger(E->getArg(0), Val, Info))
11727       return false;
11728 
11729     return Success(Val.countPopulation() % 2, E);
11730   }
11731 
11732   case Builtin::BI__builtin_popcount:
11733   case Builtin::BI__builtin_popcountl:
11734   case Builtin::BI__builtin_popcountll: {
11735     APSInt Val;
11736     if (!EvaluateInteger(E->getArg(0), Val, Info))
11737       return false;
11738 
11739     return Success(Val.countPopulation(), E);
11740   }
11741 
11742   case Builtin::BI__builtin_rotateleft8:
11743   case Builtin::BI__builtin_rotateleft16:
11744   case Builtin::BI__builtin_rotateleft32:
11745   case Builtin::BI__builtin_rotateleft64:
11746   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11747   case Builtin::BI_rotl16:
11748   case Builtin::BI_rotl:
11749   case Builtin::BI_lrotl:
11750   case Builtin::BI_rotl64: {
11751     APSInt Val, Amt;
11752     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11753         !EvaluateInteger(E->getArg(1), Amt, Info))
11754       return false;
11755 
11756     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11757   }
11758 
11759   case Builtin::BI__builtin_rotateright8:
11760   case Builtin::BI__builtin_rotateright16:
11761   case Builtin::BI__builtin_rotateright32:
11762   case Builtin::BI__builtin_rotateright64:
11763   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11764   case Builtin::BI_rotr16:
11765   case Builtin::BI_rotr:
11766   case Builtin::BI_lrotr:
11767   case Builtin::BI_rotr64: {
11768     APSInt Val, Amt;
11769     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11770         !EvaluateInteger(E->getArg(1), Amt, Info))
11771       return false;
11772 
11773     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11774   }
11775 
11776   case Builtin::BIstrlen:
11777   case Builtin::BIwcslen:
11778     // A call to strlen is not a constant expression.
11779     if (Info.getLangOpts().CPlusPlus11)
11780       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11781         << /*isConstexpr*/0 << /*isConstructor*/0
11782         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11783     else
11784       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11785     LLVM_FALLTHROUGH;
11786   case Builtin::BI__builtin_strlen:
11787   case Builtin::BI__builtin_wcslen: {
11788     // As an extension, we support __builtin_strlen() as a constant expression,
11789     // and support folding strlen() to a constant.
11790     LValue String;
11791     if (!EvaluatePointer(E->getArg(0), String, Info))
11792       return false;
11793 
11794     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11795 
11796     // Fast path: if it's a string literal, search the string value.
11797     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11798             String.getLValueBase().dyn_cast<const Expr *>())) {
11799       // The string literal may have embedded null characters. Find the first
11800       // one and truncate there.
11801       StringRef Str = S->getBytes();
11802       int64_t Off = String.Offset.getQuantity();
11803       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11804           S->getCharByteWidth() == 1 &&
11805           // FIXME: Add fast-path for wchar_t too.
11806           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11807         Str = Str.substr(Off);
11808 
11809         StringRef::size_type Pos = Str.find(0);
11810         if (Pos != StringRef::npos)
11811           Str = Str.substr(0, Pos);
11812 
11813         return Success(Str.size(), E);
11814       }
11815 
11816       // Fall through to slow path to issue appropriate diagnostic.
11817     }
11818 
11819     // Slow path: scan the bytes of the string looking for the terminating 0.
11820     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11821       APValue Char;
11822       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11823           !Char.isInt())
11824         return false;
11825       if (!Char.getInt())
11826         return Success(Strlen, E);
11827       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11828         return false;
11829     }
11830   }
11831 
11832   case Builtin::BIstrcmp:
11833   case Builtin::BIwcscmp:
11834   case Builtin::BIstrncmp:
11835   case Builtin::BIwcsncmp:
11836   case Builtin::BImemcmp:
11837   case Builtin::BIbcmp:
11838   case Builtin::BIwmemcmp:
11839     // A call to strlen is not a constant expression.
11840     if (Info.getLangOpts().CPlusPlus11)
11841       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11842         << /*isConstexpr*/0 << /*isConstructor*/0
11843         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11844     else
11845       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11846     LLVM_FALLTHROUGH;
11847   case Builtin::BI__builtin_strcmp:
11848   case Builtin::BI__builtin_wcscmp:
11849   case Builtin::BI__builtin_strncmp:
11850   case Builtin::BI__builtin_wcsncmp:
11851   case Builtin::BI__builtin_memcmp:
11852   case Builtin::BI__builtin_bcmp:
11853   case Builtin::BI__builtin_wmemcmp: {
11854     LValue String1, String2;
11855     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11856         !EvaluatePointer(E->getArg(1), String2, Info))
11857       return false;
11858 
11859     uint64_t MaxLength = uint64_t(-1);
11860     if (BuiltinOp != Builtin::BIstrcmp &&
11861         BuiltinOp != Builtin::BIwcscmp &&
11862         BuiltinOp != Builtin::BI__builtin_strcmp &&
11863         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11864       APSInt N;
11865       if (!EvaluateInteger(E->getArg(2), N, Info))
11866         return false;
11867       MaxLength = N.getExtValue();
11868     }
11869 
11870     // Empty substrings compare equal by definition.
11871     if (MaxLength == 0u)
11872       return Success(0, E);
11873 
11874     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11875         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11876         String1.Designator.Invalid || String2.Designator.Invalid)
11877       return false;
11878 
11879     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11880     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11881 
11882     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11883                      BuiltinOp == Builtin::BIbcmp ||
11884                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11885                      BuiltinOp == Builtin::BI__builtin_bcmp;
11886 
11887     assert(IsRawByte ||
11888            (Info.Ctx.hasSameUnqualifiedType(
11889                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11890             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11891 
11892     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11893     // 'char8_t', but no other types.
11894     if (IsRawByte &&
11895         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11896       // FIXME: Consider using our bit_cast implementation to support this.
11897       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11898           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11899           << CharTy1 << CharTy2;
11900       return false;
11901     }
11902 
11903     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11904       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11905              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11906              Char1.isInt() && Char2.isInt();
11907     };
11908     const auto &AdvanceElems = [&] {
11909       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11910              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11911     };
11912 
11913     bool StopAtNull =
11914         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11915          BuiltinOp != Builtin::BIwmemcmp &&
11916          BuiltinOp != Builtin::BI__builtin_memcmp &&
11917          BuiltinOp != Builtin::BI__builtin_bcmp &&
11918          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11919     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11920                   BuiltinOp == Builtin::BIwcsncmp ||
11921                   BuiltinOp == Builtin::BIwmemcmp ||
11922                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11923                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11924                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11925 
11926     for (; MaxLength; --MaxLength) {
11927       APValue Char1, Char2;
11928       if (!ReadCurElems(Char1, Char2))
11929         return false;
11930       if (Char1.getInt().ne(Char2.getInt())) {
11931         if (IsWide) // wmemcmp compares with wchar_t signedness.
11932           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11933         // memcmp always compares unsigned chars.
11934         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11935       }
11936       if (StopAtNull && !Char1.getInt())
11937         return Success(0, E);
11938       assert(!(StopAtNull && !Char2.getInt()));
11939       if (!AdvanceElems())
11940         return false;
11941     }
11942     // We hit the strncmp / memcmp limit.
11943     return Success(0, E);
11944   }
11945 
11946   case Builtin::BI__atomic_always_lock_free:
11947   case Builtin::BI__atomic_is_lock_free:
11948   case Builtin::BI__c11_atomic_is_lock_free: {
11949     APSInt SizeVal;
11950     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11951       return false;
11952 
11953     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11954     // of two less than or equal to the maximum inline atomic width, we know it
11955     // is lock-free.  If the size isn't a power of two, or greater than the
11956     // maximum alignment where we promote atomics, we know it is not lock-free
11957     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11958     // the answer can only be determined at runtime; for example, 16-byte
11959     // atomics have lock-free implementations on some, but not all,
11960     // x86-64 processors.
11961 
11962     // Check power-of-two.
11963     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11964     if (Size.isPowerOfTwo()) {
11965       // Check against inlining width.
11966       unsigned InlineWidthBits =
11967           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11968       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11969         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11970             Size == CharUnits::One() ||
11971             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11972                                                 Expr::NPC_NeverValueDependent))
11973           // OK, we will inline appropriately-aligned operations of this size,
11974           // and _Atomic(T) is appropriately-aligned.
11975           return Success(1, E);
11976 
11977         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11978           castAs<PointerType>()->getPointeeType();
11979         if (!PointeeType->isIncompleteType() &&
11980             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11981           // OK, we will inline operations on this object.
11982           return Success(1, E);
11983         }
11984       }
11985     }
11986 
11987     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11988         Success(0, E) : Error(E);
11989   }
11990   case Builtin::BIomp_is_initial_device:
11991     // We can decide statically which value the runtime would return if called.
11992     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11993   case Builtin::BI__builtin_add_overflow:
11994   case Builtin::BI__builtin_sub_overflow:
11995   case Builtin::BI__builtin_mul_overflow:
11996   case Builtin::BI__builtin_sadd_overflow:
11997   case Builtin::BI__builtin_uadd_overflow:
11998   case Builtin::BI__builtin_uaddl_overflow:
11999   case Builtin::BI__builtin_uaddll_overflow:
12000   case Builtin::BI__builtin_usub_overflow:
12001   case Builtin::BI__builtin_usubl_overflow:
12002   case Builtin::BI__builtin_usubll_overflow:
12003   case Builtin::BI__builtin_umul_overflow:
12004   case Builtin::BI__builtin_umull_overflow:
12005   case Builtin::BI__builtin_umulll_overflow:
12006   case Builtin::BI__builtin_saddl_overflow:
12007   case Builtin::BI__builtin_saddll_overflow:
12008   case Builtin::BI__builtin_ssub_overflow:
12009   case Builtin::BI__builtin_ssubl_overflow:
12010   case Builtin::BI__builtin_ssubll_overflow:
12011   case Builtin::BI__builtin_smul_overflow:
12012   case Builtin::BI__builtin_smull_overflow:
12013   case Builtin::BI__builtin_smulll_overflow: {
12014     LValue ResultLValue;
12015     APSInt LHS, RHS;
12016 
12017     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12018     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12019         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12020         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12021       return false;
12022 
12023     APSInt Result;
12024     bool DidOverflow = false;
12025 
12026     // If the types don't have to match, enlarge all 3 to the largest of them.
12027     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12028         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12029         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12030       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12031                       ResultType->isSignedIntegerOrEnumerationType();
12032       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12033                       ResultType->isSignedIntegerOrEnumerationType();
12034       uint64_t LHSSize = LHS.getBitWidth();
12035       uint64_t RHSSize = RHS.getBitWidth();
12036       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12037       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12038 
12039       // Add an additional bit if the signedness isn't uniformly agreed to. We
12040       // could do this ONLY if there is a signed and an unsigned that both have
12041       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12042       // caught in the shrink-to-result later anyway.
12043       if (IsSigned && !AllSigned)
12044         ++MaxBits;
12045 
12046       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12047       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12048       Result = APSInt(MaxBits, !IsSigned);
12049     }
12050 
12051     // Find largest int.
12052     switch (BuiltinOp) {
12053     default:
12054       llvm_unreachable("Invalid value for BuiltinOp");
12055     case Builtin::BI__builtin_add_overflow:
12056     case Builtin::BI__builtin_sadd_overflow:
12057     case Builtin::BI__builtin_saddl_overflow:
12058     case Builtin::BI__builtin_saddll_overflow:
12059     case Builtin::BI__builtin_uadd_overflow:
12060     case Builtin::BI__builtin_uaddl_overflow:
12061     case Builtin::BI__builtin_uaddll_overflow:
12062       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12063                               : LHS.uadd_ov(RHS, DidOverflow);
12064       break;
12065     case Builtin::BI__builtin_sub_overflow:
12066     case Builtin::BI__builtin_ssub_overflow:
12067     case Builtin::BI__builtin_ssubl_overflow:
12068     case Builtin::BI__builtin_ssubll_overflow:
12069     case Builtin::BI__builtin_usub_overflow:
12070     case Builtin::BI__builtin_usubl_overflow:
12071     case Builtin::BI__builtin_usubll_overflow:
12072       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12073                               : LHS.usub_ov(RHS, DidOverflow);
12074       break;
12075     case Builtin::BI__builtin_mul_overflow:
12076     case Builtin::BI__builtin_smul_overflow:
12077     case Builtin::BI__builtin_smull_overflow:
12078     case Builtin::BI__builtin_smulll_overflow:
12079     case Builtin::BI__builtin_umul_overflow:
12080     case Builtin::BI__builtin_umull_overflow:
12081     case Builtin::BI__builtin_umulll_overflow:
12082       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12083                               : LHS.umul_ov(RHS, DidOverflow);
12084       break;
12085     }
12086 
12087     // In the case where multiple sizes are allowed, truncate and see if
12088     // the values are the same.
12089     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12090         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12091         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12092       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12093       // since it will give us the behavior of a TruncOrSelf in the case where
12094       // its parameter <= its size.  We previously set Result to be at least the
12095       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12096       // will work exactly like TruncOrSelf.
12097       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12098       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12099 
12100       if (!APSInt::isSameValue(Temp, Result))
12101         DidOverflow = true;
12102       Result = Temp;
12103     }
12104 
12105     APValue APV{Result};
12106     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12107       return false;
12108     return Success(DidOverflow, E);
12109   }
12110   }
12111 }
12112 
12113 /// Determine whether this is a pointer past the end of the complete
12114 /// object referred to by the lvalue.
isOnePastTheEndOfCompleteObject(const ASTContext & Ctx,const LValue & LV)12115 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12116                                             const LValue &LV) {
12117   // A null pointer can be viewed as being "past the end" but we don't
12118   // choose to look at it that way here.
12119   if (!LV.getLValueBase())
12120     return false;
12121 
12122   // If the designator is valid and refers to a subobject, we're not pointing
12123   // past the end.
12124   if (!LV.getLValueDesignator().Invalid &&
12125       !LV.getLValueDesignator().isOnePastTheEnd())
12126     return false;
12127 
12128   // A pointer to an incomplete type might be past-the-end if the type's size is
12129   // zero.  We cannot tell because the type is incomplete.
12130   QualType Ty = getType(LV.getLValueBase());
12131   if (Ty->isIncompleteType())
12132     return true;
12133 
12134   // We're a past-the-end pointer if we point to the byte after the object,
12135   // no matter what our type or path is.
12136   auto Size = Ctx.getTypeSizeInChars(Ty);
12137   return LV.getLValueOffset() == Size;
12138 }
12139 
12140 namespace {
12141 
12142 /// Data recursive integer evaluator of certain binary operators.
12143 ///
12144 /// We use a data recursive algorithm for binary operators so that we are able
12145 /// to handle extreme cases of chained binary operators without causing stack
12146 /// overflow.
12147 class DataRecursiveIntBinOpEvaluator {
12148   struct EvalResult {
12149     APValue Val;
12150     bool Failed;
12151 
EvalResult__anona656c3112811::DataRecursiveIntBinOpEvaluator::EvalResult12152     EvalResult() : Failed(false) { }
12153 
swap__anona656c3112811::DataRecursiveIntBinOpEvaluator::EvalResult12154     void swap(EvalResult &RHS) {
12155       Val.swap(RHS.Val);
12156       Failed = RHS.Failed;
12157       RHS.Failed = false;
12158     }
12159   };
12160 
12161   struct Job {
12162     const Expr *E;
12163     EvalResult LHSResult; // meaningful only for binary operator expression.
12164     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12165 
12166     Job() = default;
12167     Job(Job &&) = default;
12168 
startSpeculativeEval__anona656c3112811::DataRecursiveIntBinOpEvaluator::Job12169     void startSpeculativeEval(EvalInfo &Info) {
12170       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12171     }
12172 
12173   private:
12174     SpeculativeEvaluationRAII SpecEvalRAII;
12175   };
12176 
12177   SmallVector<Job, 16> Queue;
12178 
12179   IntExprEvaluator &IntEval;
12180   EvalInfo &Info;
12181   APValue &FinalResult;
12182 
12183 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)12184   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12185     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12186 
12187   /// True if \param E is a binary operator that we are going to handle
12188   /// data recursively.
12189   /// We handle binary operators that are comma, logical, or that have operands
12190   /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)12191   static bool shouldEnqueue(const BinaryOperator *E) {
12192     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12193            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
12194             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12195             E->getRHS()->getType()->isIntegralOrEnumerationType());
12196   }
12197 
Traverse(const BinaryOperator * E)12198   bool Traverse(const BinaryOperator *E) {
12199     enqueue(E);
12200     EvalResult PrevResult;
12201     while (!Queue.empty())
12202       process(PrevResult);
12203 
12204     if (PrevResult.Failed) return false;
12205 
12206     FinalResult.swap(PrevResult.Val);
12207     return true;
12208   }
12209 
12210 private:
Success(uint64_t Value,const Expr * E,APValue & Result)12211   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12212     return IntEval.Success(Value, E, Result);
12213   }
Success(const APSInt & Value,const Expr * E,APValue & Result)12214   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12215     return IntEval.Success(Value, E, Result);
12216   }
Error(const Expr * E)12217   bool Error(const Expr *E) {
12218     return IntEval.Error(E);
12219   }
Error(const Expr * E,diag::kind D)12220   bool Error(const Expr *E, diag::kind D) {
12221     return IntEval.Error(E, D);
12222   }
12223 
CCEDiag(const Expr * E,diag::kind D)12224   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12225     return Info.CCEDiag(E, D);
12226   }
12227 
12228   // Returns true if visiting the RHS is necessary, false otherwise.
12229   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12230                          bool &SuppressRHSDiags);
12231 
12232   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12233                   const BinaryOperator *E, APValue &Result);
12234 
EvaluateExpr(const Expr * E,EvalResult & Result)12235   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12236     Result.Failed = !Evaluate(Result.Val, Info, E);
12237     if (Result.Failed)
12238       Result.Val = APValue();
12239   }
12240 
12241   void process(EvalResult &Result);
12242 
enqueue(const Expr * E)12243   void enqueue(const Expr *E) {
12244     E = E->IgnoreParens();
12245     Queue.resize(Queue.size()+1);
12246     Queue.back().E = E;
12247     Queue.back().Kind = Job::AnyExprKind;
12248   }
12249 };
12250 
12251 }
12252 
12253 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)12254        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12255                          bool &SuppressRHSDiags) {
12256   if (E->getOpcode() == BO_Comma) {
12257     // Ignore LHS but note if we could not evaluate it.
12258     if (LHSResult.Failed)
12259       return Info.noteSideEffect();
12260     return true;
12261   }
12262 
12263   if (E->isLogicalOp()) {
12264     bool LHSAsBool;
12265     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12266       // We were able to evaluate the LHS, see if we can get away with not
12267       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12268       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12269         Success(LHSAsBool, E, LHSResult.Val);
12270         return false; // Ignore RHS
12271       }
12272     } else {
12273       LHSResult.Failed = true;
12274 
12275       // Since we weren't able to evaluate the left hand side, it
12276       // might have had side effects.
12277       if (!Info.noteSideEffect())
12278         return false;
12279 
12280       // We can't evaluate the LHS; however, sometimes the result
12281       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12282       // Don't ignore RHS and suppress diagnostics from this arm.
12283       SuppressRHSDiags = true;
12284     }
12285 
12286     return true;
12287   }
12288 
12289   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12290          E->getRHS()->getType()->isIntegralOrEnumerationType());
12291 
12292   if (LHSResult.Failed && !Info.noteFailure())
12293     return false; // Ignore RHS;
12294 
12295   return true;
12296 }
12297 
addOrSubLValueAsInteger(APValue & LVal,const APSInt & Index,bool IsSub)12298 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12299                                     bool IsSub) {
12300   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12301   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12302   // offsets.
12303   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12304   CharUnits &Offset = LVal.getLValueOffset();
12305   uint64_t Offset64 = Offset.getQuantity();
12306   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12307   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12308                                          : Offset64 + Index64);
12309 }
12310 
12311 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)12312        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12313                   const BinaryOperator *E, APValue &Result) {
12314   if (E->getOpcode() == BO_Comma) {
12315     if (RHSResult.Failed)
12316       return false;
12317     Result = RHSResult.Val;
12318     return true;
12319   }
12320 
12321   if (E->isLogicalOp()) {
12322     bool lhsResult, rhsResult;
12323     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12324     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12325 
12326     if (LHSIsOK) {
12327       if (RHSIsOK) {
12328         if (E->getOpcode() == BO_LOr)
12329           return Success(lhsResult || rhsResult, E, Result);
12330         else
12331           return Success(lhsResult && rhsResult, E, Result);
12332       }
12333     } else {
12334       if (RHSIsOK) {
12335         // We can't evaluate the LHS; however, sometimes the result
12336         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12337         if (rhsResult == (E->getOpcode() == BO_LOr))
12338           return Success(rhsResult, E, Result);
12339       }
12340     }
12341 
12342     return false;
12343   }
12344 
12345   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12346          E->getRHS()->getType()->isIntegralOrEnumerationType());
12347 
12348   if (LHSResult.Failed || RHSResult.Failed)
12349     return false;
12350 
12351   const APValue &LHSVal = LHSResult.Val;
12352   const APValue &RHSVal = RHSResult.Val;
12353 
12354   // Handle cases like (unsigned long)&a + 4.
12355   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12356     Result = LHSVal;
12357     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12358     return true;
12359   }
12360 
12361   // Handle cases like 4 + (unsigned long)&a
12362   if (E->getOpcode() == BO_Add &&
12363       RHSVal.isLValue() && LHSVal.isInt()) {
12364     Result = RHSVal;
12365     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12366     return true;
12367   }
12368 
12369   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12370     // Handle (intptr_t)&&A - (intptr_t)&&B.
12371     if (!LHSVal.getLValueOffset().isZero() ||
12372         !RHSVal.getLValueOffset().isZero())
12373       return false;
12374     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12375     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12376     if (!LHSExpr || !RHSExpr)
12377       return false;
12378     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12379     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12380     if (!LHSAddrExpr || !RHSAddrExpr)
12381       return false;
12382     // Make sure both labels come from the same function.
12383     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12384         RHSAddrExpr->getLabel()->getDeclContext())
12385       return false;
12386     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12387     return true;
12388   }
12389 
12390   // All the remaining cases expect both operands to be an integer
12391   if (!LHSVal.isInt() || !RHSVal.isInt())
12392     return Error(E);
12393 
12394   // Set up the width and signedness manually, in case it can't be deduced
12395   // from the operation we're performing.
12396   // FIXME: Don't do this in the cases where we can deduce it.
12397   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12398                E->getType()->isUnsignedIntegerOrEnumerationType());
12399   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12400                          RHSVal.getInt(), Value))
12401     return false;
12402   return Success(Value, E, Result);
12403 }
12404 
process(EvalResult & Result)12405 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12406   Job &job = Queue.back();
12407 
12408   switch (job.Kind) {
12409     case Job::AnyExprKind: {
12410       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12411         if (shouldEnqueue(Bop)) {
12412           job.Kind = Job::BinOpKind;
12413           enqueue(Bop->getLHS());
12414           return;
12415         }
12416       }
12417 
12418       EvaluateExpr(job.E, Result);
12419       Queue.pop_back();
12420       return;
12421     }
12422 
12423     case Job::BinOpKind: {
12424       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12425       bool SuppressRHSDiags = false;
12426       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12427         Queue.pop_back();
12428         return;
12429       }
12430       if (SuppressRHSDiags)
12431         job.startSpeculativeEval(Info);
12432       job.LHSResult.swap(Result);
12433       job.Kind = Job::BinOpVisitedLHSKind;
12434       enqueue(Bop->getRHS());
12435       return;
12436     }
12437 
12438     case Job::BinOpVisitedLHSKind: {
12439       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12440       EvalResult RHS;
12441       RHS.swap(Result);
12442       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12443       Queue.pop_back();
12444       return;
12445     }
12446   }
12447 
12448   llvm_unreachable("Invalid Job::Kind!");
12449 }
12450 
12451 namespace {
12452 /// Used when we determine that we should fail, but can keep evaluating prior to
12453 /// noting that we had a failure.
12454 class DelayedNoteFailureRAII {
12455   EvalInfo &Info;
12456   bool NoteFailure;
12457 
12458 public:
DelayedNoteFailureRAII(EvalInfo & Info,bool NoteFailure=true)12459   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12460       : Info(Info), NoteFailure(NoteFailure) {}
~DelayedNoteFailureRAII()12461   ~DelayedNoteFailureRAII() {
12462     if (NoteFailure) {
12463       bool ContinueAfterFailure = Info.noteFailure();
12464       (void)ContinueAfterFailure;
12465       assert(ContinueAfterFailure &&
12466              "Shouldn't have kept evaluating on failure.");
12467     }
12468   }
12469 };
12470 
12471 enum class CmpResult {
12472   Unequal,
12473   Less,
12474   Equal,
12475   Greater,
12476   Unordered,
12477 };
12478 }
12479 
12480 template <class SuccessCB, class AfterCB>
12481 static bool
EvaluateComparisonBinaryOperator(EvalInfo & Info,const BinaryOperator * E,SuccessCB && Success,AfterCB && DoAfter)12482 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12483                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12484   assert(!E->isValueDependent());
12485   assert(E->isComparisonOp() && "expected comparison operator");
12486   assert((E->getOpcode() == BO_Cmp ||
12487           E->getType()->isIntegralOrEnumerationType()) &&
12488          "unsupported binary expression evaluation");
12489   auto Error = [&](const Expr *E) {
12490     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12491     return false;
12492   };
12493 
12494   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12495   bool IsEquality = E->isEqualityOp();
12496 
12497   QualType LHSTy = E->getLHS()->getType();
12498   QualType RHSTy = E->getRHS()->getType();
12499 
12500   if (LHSTy->isIntegralOrEnumerationType() &&
12501       RHSTy->isIntegralOrEnumerationType()) {
12502     APSInt LHS, RHS;
12503     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12504     if (!LHSOK && !Info.noteFailure())
12505       return false;
12506     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12507       return false;
12508     if (LHS < RHS)
12509       return Success(CmpResult::Less, E);
12510     if (LHS > RHS)
12511       return Success(CmpResult::Greater, E);
12512     return Success(CmpResult::Equal, E);
12513   }
12514 
12515   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12516     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12517     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12518 
12519     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12520     if (!LHSOK && !Info.noteFailure())
12521       return false;
12522     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12523       return false;
12524     if (LHSFX < RHSFX)
12525       return Success(CmpResult::Less, E);
12526     if (LHSFX > RHSFX)
12527       return Success(CmpResult::Greater, E);
12528     return Success(CmpResult::Equal, E);
12529   }
12530 
12531   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12532     ComplexValue LHS, RHS;
12533     bool LHSOK;
12534     if (E->isAssignmentOp()) {
12535       LValue LV;
12536       EvaluateLValue(E->getLHS(), LV, Info);
12537       LHSOK = false;
12538     } else if (LHSTy->isRealFloatingType()) {
12539       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12540       if (LHSOK) {
12541         LHS.makeComplexFloat();
12542         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12543       }
12544     } else {
12545       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12546     }
12547     if (!LHSOK && !Info.noteFailure())
12548       return false;
12549 
12550     if (E->getRHS()->getType()->isRealFloatingType()) {
12551       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12552         return false;
12553       RHS.makeComplexFloat();
12554       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12555     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12556       return false;
12557 
12558     if (LHS.isComplexFloat()) {
12559       APFloat::cmpResult CR_r =
12560         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12561       APFloat::cmpResult CR_i =
12562         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12563       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12564       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12565     } else {
12566       assert(IsEquality && "invalid complex comparison");
12567       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12568                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12569       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12570     }
12571   }
12572 
12573   if (LHSTy->isRealFloatingType() &&
12574       RHSTy->isRealFloatingType()) {
12575     APFloat RHS(0.0), LHS(0.0);
12576 
12577     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12578     if (!LHSOK && !Info.noteFailure())
12579       return false;
12580 
12581     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12582       return false;
12583 
12584     assert(E->isComparisonOp() && "Invalid binary operator!");
12585     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12586     if (!Info.InConstantContext &&
12587         APFloatCmpResult == APFloat::cmpUnordered &&
12588         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12589       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12590       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12591       return false;
12592     }
12593     auto GetCmpRes = [&]() {
12594       switch (APFloatCmpResult) {
12595       case APFloat::cmpEqual:
12596         return CmpResult::Equal;
12597       case APFloat::cmpLessThan:
12598         return CmpResult::Less;
12599       case APFloat::cmpGreaterThan:
12600         return CmpResult::Greater;
12601       case APFloat::cmpUnordered:
12602         return CmpResult::Unordered;
12603       }
12604       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12605     };
12606     return Success(GetCmpRes(), E);
12607   }
12608 
12609   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12610     LValue LHSValue, RHSValue;
12611 
12612     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12613     if (!LHSOK && !Info.noteFailure())
12614       return false;
12615 
12616     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12617       return false;
12618 
12619     // Reject differing bases from the normal codepath; we special-case
12620     // comparisons to null.
12621     if (!HasSameBase(LHSValue, RHSValue)) {
12622       // Inequalities and subtractions between unrelated pointers have
12623       // unspecified or undefined behavior.
12624       if (!IsEquality) {
12625         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12626         return false;
12627       }
12628       // A constant address may compare equal to the address of a symbol.
12629       // The one exception is that address of an object cannot compare equal
12630       // to a null pointer constant.
12631       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12632           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12633         return Error(E);
12634       // It's implementation-defined whether distinct literals will have
12635       // distinct addresses. In clang, the result of such a comparison is
12636       // unspecified, so it is not a constant expression. However, we do know
12637       // that the address of a literal will be non-null.
12638       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12639           LHSValue.Base && RHSValue.Base)
12640         return Error(E);
12641       // We can't tell whether weak symbols will end up pointing to the same
12642       // object.
12643       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12644         return Error(E);
12645       // We can't compare the address of the start of one object with the
12646       // past-the-end address of another object, per C++ DR1652.
12647       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12648            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12649           (RHSValue.Base && RHSValue.Offset.isZero() &&
12650            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12651         return Error(E);
12652       // We can't tell whether an object is at the same address as another
12653       // zero sized object.
12654       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12655           (LHSValue.Base && isZeroSized(RHSValue)))
12656         return Error(E);
12657       return Success(CmpResult::Unequal, E);
12658     }
12659 
12660     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12661     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12662 
12663     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12664     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12665 
12666     // C++11 [expr.rel]p3:
12667     //   Pointers to void (after pointer conversions) can be compared, with a
12668     //   result defined as follows: If both pointers represent the same
12669     //   address or are both the null pointer value, the result is true if the
12670     //   operator is <= or >= and false otherwise; otherwise the result is
12671     //   unspecified.
12672     // We interpret this as applying to pointers to *cv* void.
12673     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12674       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12675 
12676     // C++11 [expr.rel]p2:
12677     // - If two pointers point to non-static data members of the same object,
12678     //   or to subobjects or array elements fo such members, recursively, the
12679     //   pointer to the later declared member compares greater provided the
12680     //   two members have the same access control and provided their class is
12681     //   not a union.
12682     //   [...]
12683     // - Otherwise pointer comparisons are unspecified.
12684     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12685       bool WasArrayIndex;
12686       unsigned Mismatch = FindDesignatorMismatch(
12687           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12688       // At the point where the designators diverge, the comparison has a
12689       // specified value if:
12690       //  - we are comparing array indices
12691       //  - we are comparing fields of a union, or fields with the same access
12692       // Otherwise, the result is unspecified and thus the comparison is not a
12693       // constant expression.
12694       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12695           Mismatch < RHSDesignator.Entries.size()) {
12696         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12697         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12698         if (!LF && !RF)
12699           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12700         else if (!LF)
12701           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12702               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12703               << RF->getParent() << RF;
12704         else if (!RF)
12705           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12706               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12707               << LF->getParent() << LF;
12708         else if (!LF->getParent()->isUnion() &&
12709                  LF->getAccess() != RF->getAccess())
12710           Info.CCEDiag(E,
12711                        diag::note_constexpr_pointer_comparison_differing_access)
12712               << LF << LF->getAccess() << RF << RF->getAccess()
12713               << LF->getParent();
12714       }
12715     }
12716 
12717     // The comparison here must be unsigned, and performed with the same
12718     // width as the pointer.
12719     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12720     uint64_t CompareLHS = LHSOffset.getQuantity();
12721     uint64_t CompareRHS = RHSOffset.getQuantity();
12722     assert(PtrSize <= 64 && "Unexpected pointer width");
12723     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12724     CompareLHS &= Mask;
12725     CompareRHS &= Mask;
12726 
12727     // If there is a base and this is a relational operator, we can only
12728     // compare pointers within the object in question; otherwise, the result
12729     // depends on where the object is located in memory.
12730     if (!LHSValue.Base.isNull() && IsRelational) {
12731       QualType BaseTy = getType(LHSValue.Base);
12732       if (BaseTy->isIncompleteType())
12733         return Error(E);
12734       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12735       uint64_t OffsetLimit = Size.getQuantity();
12736       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12737         return Error(E);
12738     }
12739 
12740     if (CompareLHS < CompareRHS)
12741       return Success(CmpResult::Less, E);
12742     if (CompareLHS > CompareRHS)
12743       return Success(CmpResult::Greater, E);
12744     return Success(CmpResult::Equal, E);
12745   }
12746 
12747   if (LHSTy->isMemberPointerType()) {
12748     assert(IsEquality && "unexpected member pointer operation");
12749     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12750 
12751     MemberPtr LHSValue, RHSValue;
12752 
12753     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12754     if (!LHSOK && !Info.noteFailure())
12755       return false;
12756 
12757     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12758       return false;
12759 
12760     // C++11 [expr.eq]p2:
12761     //   If both operands are null, they compare equal. Otherwise if only one is
12762     //   null, they compare unequal.
12763     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12764       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12765       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12766     }
12767 
12768     //   Otherwise if either is a pointer to a virtual member function, the
12769     //   result is unspecified.
12770     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12771       if (MD->isVirtual())
12772         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12773     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12774       if (MD->isVirtual())
12775         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12776 
12777     //   Otherwise they compare equal if and only if they would refer to the
12778     //   same member of the same most derived object or the same subobject if
12779     //   they were dereferenced with a hypothetical object of the associated
12780     //   class type.
12781     bool Equal = LHSValue == RHSValue;
12782     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12783   }
12784 
12785   if (LHSTy->isNullPtrType()) {
12786     assert(E->isComparisonOp() && "unexpected nullptr operation");
12787     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12788     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12789     // are compared, the result is true of the operator is <=, >= or ==, and
12790     // false otherwise.
12791     return Success(CmpResult::Equal, E);
12792   }
12793 
12794   return DoAfter();
12795 }
12796 
VisitBinCmp(const BinaryOperator * E)12797 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12798   if (!CheckLiteralType(Info, E))
12799     return false;
12800 
12801   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12802     ComparisonCategoryResult CCR;
12803     switch (CR) {
12804     case CmpResult::Unequal:
12805       llvm_unreachable("should never produce Unequal for three-way comparison");
12806     case CmpResult::Less:
12807       CCR = ComparisonCategoryResult::Less;
12808       break;
12809     case CmpResult::Equal:
12810       CCR = ComparisonCategoryResult::Equal;
12811       break;
12812     case CmpResult::Greater:
12813       CCR = ComparisonCategoryResult::Greater;
12814       break;
12815     case CmpResult::Unordered:
12816       CCR = ComparisonCategoryResult::Unordered;
12817       break;
12818     }
12819     // Evaluation succeeded. Lookup the information for the comparison category
12820     // type and fetch the VarDecl for the result.
12821     const ComparisonCategoryInfo &CmpInfo =
12822         Info.Ctx.CompCategories.getInfoForType(E->getType());
12823     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12824     // Check and evaluate the result as a constant expression.
12825     LValue LV;
12826     LV.set(VD);
12827     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12828       return false;
12829     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12830                                    ConstantExprKind::Normal);
12831   };
12832   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12833     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12834   });
12835 }
12836 
VisitBinaryOperator(const BinaryOperator * E)12837 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12838   // We don't call noteFailure immediately because the assignment happens after
12839   // we evaluate LHS and RHS.
12840   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12841     return Error(E);
12842 
12843   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12844   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12845     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12846 
12847   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12848           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12849          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12850 
12851   if (E->isComparisonOp()) {
12852     // Evaluate builtin binary comparisons by evaluating them as three-way
12853     // comparisons and then translating the result.
12854     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12855       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12856              "should only produce Unequal for equality comparisons");
12857       bool IsEqual   = CR == CmpResult::Equal,
12858            IsLess    = CR == CmpResult::Less,
12859            IsGreater = CR == CmpResult::Greater;
12860       auto Op = E->getOpcode();
12861       switch (Op) {
12862       default:
12863         llvm_unreachable("unsupported binary operator");
12864       case BO_EQ:
12865       case BO_NE:
12866         return Success(IsEqual == (Op == BO_EQ), E);
12867       case BO_LT:
12868         return Success(IsLess, E);
12869       case BO_GT:
12870         return Success(IsGreater, E);
12871       case BO_LE:
12872         return Success(IsEqual || IsLess, E);
12873       case BO_GE:
12874         return Success(IsEqual || IsGreater, E);
12875       }
12876     };
12877     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12878       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12879     });
12880   }
12881 
12882   QualType LHSTy = E->getLHS()->getType();
12883   QualType RHSTy = E->getRHS()->getType();
12884 
12885   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12886       E->getOpcode() == BO_Sub) {
12887     LValue LHSValue, RHSValue;
12888 
12889     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12890     if (!LHSOK && !Info.noteFailure())
12891       return false;
12892 
12893     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12894       return false;
12895 
12896     // Reject differing bases from the normal codepath; we special-case
12897     // comparisons to null.
12898     if (!HasSameBase(LHSValue, RHSValue)) {
12899       // Handle &&A - &&B.
12900       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12901         return Error(E);
12902       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12903       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12904       if (!LHSExpr || !RHSExpr)
12905         return Error(E);
12906       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12907       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12908       if (!LHSAddrExpr || !RHSAddrExpr)
12909         return Error(E);
12910       // Make sure both labels come from the same function.
12911       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12912           RHSAddrExpr->getLabel()->getDeclContext())
12913         return Error(E);
12914       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12915     }
12916     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12917     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12918 
12919     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12920     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12921 
12922     // C++11 [expr.add]p6:
12923     //   Unless both pointers point to elements of the same array object, or
12924     //   one past the last element of the array object, the behavior is
12925     //   undefined.
12926     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12927         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12928                                 RHSDesignator))
12929       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12930 
12931     QualType Type = E->getLHS()->getType();
12932     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12933 
12934     CharUnits ElementSize;
12935     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12936       return false;
12937 
12938     // As an extension, a type may have zero size (empty struct or union in
12939     // C, array of zero length). Pointer subtraction in such cases has
12940     // undefined behavior, so is not constant.
12941     if (ElementSize.isZero()) {
12942       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12943           << ElementType;
12944       return false;
12945     }
12946 
12947     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12948     // and produce incorrect results when it overflows. Such behavior
12949     // appears to be non-conforming, but is common, so perhaps we should
12950     // assume the standard intended for such cases to be undefined behavior
12951     // and check for them.
12952 
12953     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12954     // overflow in the final conversion to ptrdiff_t.
12955     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12956     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12957     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12958                     false);
12959     APSInt TrueResult = (LHS - RHS) / ElemSize;
12960     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12961 
12962     if (Result.extend(65) != TrueResult &&
12963         !HandleOverflow(Info, E, TrueResult, E->getType()))
12964       return false;
12965     return Success(Result, E);
12966   }
12967 
12968   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12969 }
12970 
12971 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12972 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)12973 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12974                                     const UnaryExprOrTypeTraitExpr *E) {
12975   switch(E->getKind()) {
12976   case UETT_PreferredAlignOf:
12977   case UETT_AlignOf: {
12978     if (E->isArgumentType())
12979       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12980                      E);
12981     else
12982       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12983                      E);
12984   }
12985 
12986   case UETT_VecStep: {
12987     QualType Ty = E->getTypeOfArgument();
12988 
12989     if (Ty->isVectorType()) {
12990       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12991 
12992       // The vec_step built-in functions that take a 3-component
12993       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12994       if (n == 3)
12995         n = 4;
12996 
12997       return Success(n, E);
12998     } else
12999       return Success(1, E);
13000   }
13001 
13002   case UETT_SizeOf: {
13003     QualType SrcTy = E->getTypeOfArgument();
13004     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13005     //   the result is the size of the referenced type."
13006     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13007       SrcTy = Ref->getPointeeType();
13008 
13009     CharUnits Sizeof;
13010     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13011       return false;
13012     return Success(Sizeof, E);
13013   }
13014   case UETT_OpenMPRequiredSimdAlign:
13015     assert(E->isArgumentType());
13016     return Success(
13017         Info.Ctx.toCharUnitsFromBits(
13018                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13019             .getQuantity(),
13020         E);
13021   }
13022 
13023   llvm_unreachable("unknown expr/type trait");
13024 }
13025 
VisitOffsetOfExpr(const OffsetOfExpr * OOE)13026 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13027   CharUnits Result;
13028   unsigned n = OOE->getNumComponents();
13029   if (n == 0)
13030     return Error(OOE);
13031   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13032   for (unsigned i = 0; i != n; ++i) {
13033     OffsetOfNode ON = OOE->getComponent(i);
13034     switch (ON.getKind()) {
13035     case OffsetOfNode::Array: {
13036       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13037       APSInt IdxResult;
13038       if (!EvaluateInteger(Idx, IdxResult, Info))
13039         return false;
13040       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13041       if (!AT)
13042         return Error(OOE);
13043       CurrentType = AT->getElementType();
13044       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13045       Result += IdxResult.getSExtValue() * ElementSize;
13046       break;
13047     }
13048 
13049     case OffsetOfNode::Field: {
13050       FieldDecl *MemberDecl = ON.getField();
13051       const RecordType *RT = CurrentType->getAs<RecordType>();
13052       if (!RT)
13053         return Error(OOE);
13054       RecordDecl *RD = RT->getDecl();
13055       if (RD->isInvalidDecl()) return false;
13056       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13057       unsigned i = MemberDecl->getFieldIndex();
13058       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13059       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13060       CurrentType = MemberDecl->getType().getNonReferenceType();
13061       break;
13062     }
13063 
13064     case OffsetOfNode::Identifier:
13065       llvm_unreachable("dependent __builtin_offsetof");
13066 
13067     case OffsetOfNode::Base: {
13068       CXXBaseSpecifier *BaseSpec = ON.getBase();
13069       if (BaseSpec->isVirtual())
13070         return Error(OOE);
13071 
13072       // Find the layout of the class whose base we are looking into.
13073       const RecordType *RT = CurrentType->getAs<RecordType>();
13074       if (!RT)
13075         return Error(OOE);
13076       RecordDecl *RD = RT->getDecl();
13077       if (RD->isInvalidDecl()) return false;
13078       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13079 
13080       // Find the base class itself.
13081       CurrentType = BaseSpec->getType();
13082       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13083       if (!BaseRT)
13084         return Error(OOE);
13085 
13086       // Add the offset to the base.
13087       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13088       break;
13089     }
13090     }
13091   }
13092   return Success(Result, OOE);
13093 }
13094 
VisitUnaryOperator(const UnaryOperator * E)13095 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13096   switch (E->getOpcode()) {
13097   default:
13098     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13099     // See C99 6.6p3.
13100     return Error(E);
13101   case UO_Extension:
13102     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13103     // If so, we could clear the diagnostic ID.
13104     return Visit(E->getSubExpr());
13105   case UO_Plus:
13106     // The result is just the value.
13107     return Visit(E->getSubExpr());
13108   case UO_Minus: {
13109     if (!Visit(E->getSubExpr()))
13110       return false;
13111     if (!Result.isInt()) return Error(E);
13112     const APSInt &Value = Result.getInt();
13113     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13114         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13115                         E->getType()))
13116       return false;
13117     return Success(-Value, E);
13118   }
13119   case UO_Not: {
13120     if (!Visit(E->getSubExpr()))
13121       return false;
13122     if (!Result.isInt()) return Error(E);
13123     return Success(~Result.getInt(), E);
13124   }
13125   case UO_LNot: {
13126     bool bres;
13127     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13128       return false;
13129     return Success(!bres, E);
13130   }
13131   }
13132 }
13133 
13134 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13135 /// result type is integer.
VisitCastExpr(const CastExpr * E)13136 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13137   const Expr *SubExpr = E->getSubExpr();
13138   QualType DestType = E->getType();
13139   QualType SrcType = SubExpr->getType();
13140 
13141   switch (E->getCastKind()) {
13142   case CK_BaseToDerived:
13143   case CK_DerivedToBase:
13144   case CK_UncheckedDerivedToBase:
13145   case CK_Dynamic:
13146   case CK_ToUnion:
13147   case CK_ArrayToPointerDecay:
13148   case CK_FunctionToPointerDecay:
13149   case CK_NullToPointer:
13150   case CK_NullToMemberPointer:
13151   case CK_BaseToDerivedMemberPointer:
13152   case CK_DerivedToBaseMemberPointer:
13153   case CK_ReinterpretMemberPointer:
13154   case CK_ConstructorConversion:
13155   case CK_IntegralToPointer:
13156   case CK_ToVoid:
13157   case CK_VectorSplat:
13158   case CK_IntegralToFloating:
13159   case CK_FloatingCast:
13160   case CK_CPointerToObjCPointerCast:
13161   case CK_BlockPointerToObjCPointerCast:
13162   case CK_AnyPointerToBlockPointerCast:
13163   case CK_ObjCObjectLValueCast:
13164   case CK_FloatingRealToComplex:
13165   case CK_FloatingComplexToReal:
13166   case CK_FloatingComplexCast:
13167   case CK_FloatingComplexToIntegralComplex:
13168   case CK_IntegralRealToComplex:
13169   case CK_IntegralComplexCast:
13170   case CK_IntegralComplexToFloatingComplex:
13171   case CK_BuiltinFnToFnPtr:
13172   case CK_ZeroToOCLOpaqueType:
13173   case CK_NonAtomicToAtomic:
13174   case CK_AddressSpaceConversion:
13175   case CK_IntToOCLSampler:
13176   case CK_FloatingToFixedPoint:
13177   case CK_FixedPointToFloating:
13178   case CK_FixedPointCast:
13179   case CK_IntegralToFixedPoint:
13180     llvm_unreachable("invalid cast kind for integral value");
13181 
13182   case CK_BitCast:
13183   case CK_Dependent:
13184   case CK_LValueBitCast:
13185   case CK_ARCProduceObject:
13186   case CK_ARCConsumeObject:
13187   case CK_ARCReclaimReturnedObject:
13188   case CK_ARCExtendBlockObject:
13189   case CK_CopyAndAutoreleaseBlockObject:
13190     return Error(E);
13191 
13192   case CK_UserDefinedConversion:
13193   case CK_LValueToRValue:
13194   case CK_AtomicToNonAtomic:
13195   case CK_NoOp:
13196   case CK_LValueToRValueBitCast:
13197     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13198 
13199   case CK_MemberPointerToBoolean:
13200   case CK_PointerToBoolean:
13201   case CK_IntegralToBoolean:
13202   case CK_FloatingToBoolean:
13203   case CK_BooleanToSignedIntegral:
13204   case CK_FloatingComplexToBoolean:
13205   case CK_IntegralComplexToBoolean: {
13206     bool BoolResult;
13207     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13208       return false;
13209     uint64_t IntResult = BoolResult;
13210     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13211       IntResult = (uint64_t)-1;
13212     return Success(IntResult, E);
13213   }
13214 
13215   case CK_FixedPointToIntegral: {
13216     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13217     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13218       return false;
13219     bool Overflowed;
13220     llvm::APSInt Result = Src.convertToInt(
13221         Info.Ctx.getIntWidth(DestType),
13222         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13223     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13224       return false;
13225     return Success(Result, E);
13226   }
13227 
13228   case CK_FixedPointToBoolean: {
13229     // Unsigned padding does not affect this.
13230     APValue Val;
13231     if (!Evaluate(Val, Info, SubExpr))
13232       return false;
13233     return Success(Val.getFixedPoint().getBoolValue(), E);
13234   }
13235 
13236   case CK_IntegralCast: {
13237     if (!Visit(SubExpr))
13238       return false;
13239 
13240     if (!Result.isInt()) {
13241       // Allow casts of address-of-label differences if they are no-ops
13242       // or narrowing.  (The narrowing case isn't actually guaranteed to
13243       // be constant-evaluatable except in some narrow cases which are hard
13244       // to detect here.  We let it through on the assumption the user knows
13245       // what they are doing.)
13246       if (Result.isAddrLabelDiff())
13247         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13248       // Only allow casts of lvalues if they are lossless.
13249       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13250     }
13251 
13252     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13253                                       Result.getInt()), E);
13254   }
13255 
13256   case CK_PointerToIntegral: {
13257     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13258 
13259     LValue LV;
13260     if (!EvaluatePointer(SubExpr, LV, Info))
13261       return false;
13262 
13263     if (LV.getLValueBase()) {
13264       // Only allow based lvalue casts if they are lossless.
13265       // FIXME: Allow a larger integer size than the pointer size, and allow
13266       // narrowing back down to pointer width in subsequent integral casts.
13267       // FIXME: Check integer type's active bits, not its type size.
13268       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13269         return Error(E);
13270 
13271       LV.Designator.setInvalid();
13272       LV.moveInto(Result);
13273       return true;
13274     }
13275 
13276     APSInt AsInt;
13277     APValue V;
13278     LV.moveInto(V);
13279     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13280       llvm_unreachable("Can't cast this!");
13281 
13282     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13283   }
13284 
13285   case CK_IntegralComplexToReal: {
13286     ComplexValue C;
13287     if (!EvaluateComplex(SubExpr, C, Info))
13288       return false;
13289     return Success(C.getComplexIntReal(), E);
13290   }
13291 
13292   case CK_FloatingToIntegral: {
13293     APFloat F(0.0);
13294     if (!EvaluateFloat(SubExpr, F, Info))
13295       return false;
13296 
13297     APSInt Value;
13298     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13299       return false;
13300     return Success(Value, E);
13301   }
13302   }
13303 
13304   llvm_unreachable("unknown cast resulting in integral value");
13305 }
13306 
VisitUnaryReal(const UnaryOperator * E)13307 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13308   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13309     ComplexValue LV;
13310     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13311       return false;
13312     if (!LV.isComplexInt())
13313       return Error(E);
13314     return Success(LV.getComplexIntReal(), E);
13315   }
13316 
13317   return Visit(E->getSubExpr());
13318 }
13319 
VisitUnaryImag(const UnaryOperator * E)13320 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13321   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13322     ComplexValue LV;
13323     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13324       return false;
13325     if (!LV.isComplexInt())
13326       return Error(E);
13327     return Success(LV.getComplexIntImag(), E);
13328   }
13329 
13330   VisitIgnoredValue(E->getSubExpr());
13331   return Success(0, E);
13332 }
13333 
VisitSizeOfPackExpr(const SizeOfPackExpr * E)13334 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13335   return Success(E->getPackLength(), E);
13336 }
13337 
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)13338 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13339   return Success(E->getValue(), E);
13340 }
13341 
VisitConceptSpecializationExpr(const ConceptSpecializationExpr * E)13342 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13343        const ConceptSpecializationExpr *E) {
13344   return Success(E->isSatisfied(), E);
13345 }
13346 
VisitRequiresExpr(const RequiresExpr * E)13347 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13348   return Success(E->isSatisfied(), E);
13349 }
13350 
VisitUnaryOperator(const UnaryOperator * E)13351 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13352   switch (E->getOpcode()) {
13353     default:
13354       // Invalid unary operators
13355       return Error(E);
13356     case UO_Plus:
13357       // The result is just the value.
13358       return Visit(E->getSubExpr());
13359     case UO_Minus: {
13360       if (!Visit(E->getSubExpr())) return false;
13361       if (!Result.isFixedPoint())
13362         return Error(E);
13363       bool Overflowed;
13364       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13365       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13366         return false;
13367       return Success(Negated, E);
13368     }
13369     case UO_LNot: {
13370       bool bres;
13371       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13372         return false;
13373       return Success(!bres, E);
13374     }
13375   }
13376 }
13377 
VisitCastExpr(const CastExpr * E)13378 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13379   const Expr *SubExpr = E->getSubExpr();
13380   QualType DestType = E->getType();
13381   assert(DestType->isFixedPointType() &&
13382          "Expected destination type to be a fixed point type");
13383   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13384 
13385   switch (E->getCastKind()) {
13386   case CK_FixedPointCast: {
13387     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13388     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13389       return false;
13390     bool Overflowed;
13391     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13392     if (Overflowed) {
13393       if (Info.checkingForUndefinedBehavior())
13394         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13395                                          diag::warn_fixedpoint_constant_overflow)
13396           << Result.toString() << E->getType();
13397       else if (!HandleOverflow(Info, E, Result, E->getType()))
13398         return false;
13399     }
13400     return Success(Result, E);
13401   }
13402   case CK_IntegralToFixedPoint: {
13403     APSInt Src;
13404     if (!EvaluateInteger(SubExpr, Src, Info))
13405       return false;
13406 
13407     bool Overflowed;
13408     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13409         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13410 
13411     if (Overflowed) {
13412       if (Info.checkingForUndefinedBehavior())
13413         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13414                                          diag::warn_fixedpoint_constant_overflow)
13415           << IntResult.toString() << E->getType();
13416       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13417         return false;
13418     }
13419 
13420     return Success(IntResult, E);
13421   }
13422   case CK_FloatingToFixedPoint: {
13423     APFloat Src(0.0);
13424     if (!EvaluateFloat(SubExpr, Src, Info))
13425       return false;
13426 
13427     bool Overflowed;
13428     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13429         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13430 
13431     if (Overflowed) {
13432       if (Info.checkingForUndefinedBehavior())
13433         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13434                                          diag::warn_fixedpoint_constant_overflow)
13435           << Result.toString() << E->getType();
13436       else if (!HandleOverflow(Info, E, Result, E->getType()))
13437         return false;
13438     }
13439 
13440     return Success(Result, E);
13441   }
13442   case CK_NoOp:
13443   case CK_LValueToRValue:
13444     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13445   default:
13446     return Error(E);
13447   }
13448 }
13449 
VisitBinaryOperator(const BinaryOperator * E)13450 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13451   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13452     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13453 
13454   const Expr *LHS = E->getLHS();
13455   const Expr *RHS = E->getRHS();
13456   FixedPointSemantics ResultFXSema =
13457       Info.Ctx.getFixedPointSemantics(E->getType());
13458 
13459   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13460   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13461     return false;
13462   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13463   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13464     return false;
13465 
13466   bool OpOverflow = false, ConversionOverflow = false;
13467   APFixedPoint Result(LHSFX.getSemantics());
13468   switch (E->getOpcode()) {
13469   case BO_Add: {
13470     Result = LHSFX.add(RHSFX, &OpOverflow)
13471                   .convert(ResultFXSema, &ConversionOverflow);
13472     break;
13473   }
13474   case BO_Sub: {
13475     Result = LHSFX.sub(RHSFX, &OpOverflow)
13476                   .convert(ResultFXSema, &ConversionOverflow);
13477     break;
13478   }
13479   case BO_Mul: {
13480     Result = LHSFX.mul(RHSFX, &OpOverflow)
13481                   .convert(ResultFXSema, &ConversionOverflow);
13482     break;
13483   }
13484   case BO_Div: {
13485     if (RHSFX.getValue() == 0) {
13486       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13487       return false;
13488     }
13489     Result = LHSFX.div(RHSFX, &OpOverflow)
13490                   .convert(ResultFXSema, &ConversionOverflow);
13491     break;
13492   }
13493   case BO_Shl:
13494   case BO_Shr: {
13495     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13496     llvm::APSInt RHSVal = RHSFX.getValue();
13497 
13498     unsigned ShiftBW =
13499         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13500     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13501     // Embedded-C 4.1.6.2.2:
13502     //   The right operand must be nonnegative and less than the total number
13503     //   of (nonpadding) bits of the fixed-point operand ...
13504     if (RHSVal.isNegative())
13505       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13506     else if (Amt != RHSVal)
13507       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13508           << RHSVal << E->getType() << ShiftBW;
13509 
13510     if (E->getOpcode() == BO_Shl)
13511       Result = LHSFX.shl(Amt, &OpOverflow);
13512     else
13513       Result = LHSFX.shr(Amt, &OpOverflow);
13514     break;
13515   }
13516   default:
13517     return false;
13518   }
13519   if (OpOverflow || ConversionOverflow) {
13520     if (Info.checkingForUndefinedBehavior())
13521       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13522                                        diag::warn_fixedpoint_constant_overflow)
13523         << Result.toString() << E->getType();
13524     else if (!HandleOverflow(Info, E, Result, E->getType()))
13525       return false;
13526   }
13527   return Success(Result, E);
13528 }
13529 
13530 //===----------------------------------------------------------------------===//
13531 // Float Evaluation
13532 //===----------------------------------------------------------------------===//
13533 
13534 namespace {
13535 class FloatExprEvaluator
13536   : public ExprEvaluatorBase<FloatExprEvaluator> {
13537   APFloat &Result;
13538 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)13539   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13540     : ExprEvaluatorBaseTy(info), Result(result) {}
13541 
Success(const APValue & V,const Expr * e)13542   bool Success(const APValue &V, const Expr *e) {
13543     Result = V.getFloat();
13544     return true;
13545   }
13546 
ZeroInitialization(const Expr * E)13547   bool ZeroInitialization(const Expr *E) {
13548     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13549     return true;
13550   }
13551 
13552   bool VisitCallExpr(const CallExpr *E);
13553 
13554   bool VisitUnaryOperator(const UnaryOperator *E);
13555   bool VisitBinaryOperator(const BinaryOperator *E);
13556   bool VisitFloatingLiteral(const FloatingLiteral *E);
13557   bool VisitCastExpr(const CastExpr *E);
13558 
13559   bool VisitUnaryReal(const UnaryOperator *E);
13560   bool VisitUnaryImag(const UnaryOperator *E);
13561 
13562   // FIXME: Missing: array subscript of vector, member of vector
13563 };
13564 } // end anonymous namespace
13565 
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)13566 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13567   assert(!E->isValueDependent());
13568   assert(E->isRValue() && E->getType()->isRealFloatingType());
13569   return FloatExprEvaluator(Info, Result).Visit(E);
13570 }
13571 
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)13572 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13573                                   QualType ResultTy,
13574                                   const Expr *Arg,
13575                                   bool SNaN,
13576                                   llvm::APFloat &Result) {
13577   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13578   if (!S) return false;
13579 
13580   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13581 
13582   llvm::APInt fill;
13583 
13584   // Treat empty strings as if they were zero.
13585   if (S->getString().empty())
13586     fill = llvm::APInt(32, 0);
13587   else if (S->getString().getAsInteger(0, fill))
13588     return false;
13589 
13590   if (Context.getTargetInfo().isNan2008()) {
13591     if (SNaN)
13592       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13593     else
13594       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13595   } else {
13596     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13597     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13598     // a different encoding to what became a standard in 2008, and for pre-
13599     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13600     // sNaN. This is now known as "legacy NaN" encoding.
13601     if (SNaN)
13602       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13603     else
13604       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13605   }
13606 
13607   return true;
13608 }
13609 
VisitCallExpr(const CallExpr * E)13610 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13611   switch (E->getBuiltinCallee()) {
13612   default:
13613     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13614 
13615   case Builtin::BI__builtin_huge_val:
13616   case Builtin::BI__builtin_huge_valf:
13617   case Builtin::BI__builtin_huge_vall:
13618   case Builtin::BI__builtin_huge_valf128:
13619   case Builtin::BI__builtin_inf:
13620   case Builtin::BI__builtin_inff:
13621   case Builtin::BI__builtin_infl:
13622   case Builtin::BI__builtin_inff128: {
13623     const llvm::fltSemantics &Sem =
13624       Info.Ctx.getFloatTypeSemantics(E->getType());
13625     Result = llvm::APFloat::getInf(Sem);
13626     return true;
13627   }
13628 
13629   case Builtin::BI__builtin_nans:
13630   case Builtin::BI__builtin_nansf:
13631   case Builtin::BI__builtin_nansl:
13632   case Builtin::BI__builtin_nansf128:
13633     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13634                                true, Result))
13635       return Error(E);
13636     return true;
13637 
13638   case Builtin::BI__builtin_nan:
13639   case Builtin::BI__builtin_nanf:
13640   case Builtin::BI__builtin_nanl:
13641   case Builtin::BI__builtin_nanf128:
13642     // If this is __builtin_nan() turn this into a nan, otherwise we
13643     // can't constant fold it.
13644     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13645                                false, Result))
13646       return Error(E);
13647     return true;
13648 
13649   case Builtin::BI__builtin_fabs:
13650   case Builtin::BI__builtin_fabsf:
13651   case Builtin::BI__builtin_fabsl:
13652   case Builtin::BI__builtin_fabsf128:
13653     // The C standard says "fabs raises no floating-point exceptions,
13654     // even if x is a signaling NaN. The returned value is independent of
13655     // the current rounding direction mode."  Therefore constant folding can
13656     // proceed without regard to the floating point settings.
13657     // Reference, WG14 N2478 F.10.4.3
13658     if (!EvaluateFloat(E->getArg(0), Result, Info))
13659       return false;
13660 
13661     if (Result.isNegative())
13662       Result.changeSign();
13663     return true;
13664 
13665   // FIXME: Builtin::BI__builtin_powi
13666   // FIXME: Builtin::BI__builtin_powif
13667   // FIXME: Builtin::BI__builtin_powil
13668 
13669   case Builtin::BI__builtin_copysign:
13670   case Builtin::BI__builtin_copysignf:
13671   case Builtin::BI__builtin_copysignl:
13672   case Builtin::BI__builtin_copysignf128: {
13673     APFloat RHS(0.);
13674     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13675         !EvaluateFloat(E->getArg(1), RHS, Info))
13676       return false;
13677     Result.copySign(RHS);
13678     return true;
13679   }
13680   }
13681 }
13682 
VisitUnaryReal(const UnaryOperator * E)13683 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13684   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13685     ComplexValue CV;
13686     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13687       return false;
13688     Result = CV.FloatReal;
13689     return true;
13690   }
13691 
13692   return Visit(E->getSubExpr());
13693 }
13694 
VisitUnaryImag(const UnaryOperator * E)13695 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13696   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13697     ComplexValue CV;
13698     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13699       return false;
13700     Result = CV.FloatImag;
13701     return true;
13702   }
13703 
13704   VisitIgnoredValue(E->getSubExpr());
13705   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13706   Result = llvm::APFloat::getZero(Sem);
13707   return true;
13708 }
13709 
VisitUnaryOperator(const UnaryOperator * E)13710 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13711   switch (E->getOpcode()) {
13712   default: return Error(E);
13713   case UO_Plus:
13714     return EvaluateFloat(E->getSubExpr(), Result, Info);
13715   case UO_Minus:
13716     // In C standard, WG14 N2478 F.3 p4
13717     // "the unary - raises no floating point exceptions,
13718     // even if the operand is signalling."
13719     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13720       return false;
13721     Result.changeSign();
13722     return true;
13723   }
13724 }
13725 
VisitBinaryOperator(const BinaryOperator * E)13726 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13727   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13728     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13729 
13730   APFloat RHS(0.0);
13731   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13732   if (!LHSOK && !Info.noteFailure())
13733     return false;
13734   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13735          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13736 }
13737 
VisitFloatingLiteral(const FloatingLiteral * E)13738 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13739   Result = E->getValue();
13740   return true;
13741 }
13742 
VisitCastExpr(const CastExpr * E)13743 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13744   const Expr* SubExpr = E->getSubExpr();
13745 
13746   switch (E->getCastKind()) {
13747   default:
13748     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13749 
13750   case CK_IntegralToFloating: {
13751     APSInt IntResult;
13752     const FPOptions FPO = E->getFPFeaturesInEffect(
13753                                   Info.Ctx.getLangOpts());
13754     return EvaluateInteger(SubExpr, IntResult, Info) &&
13755            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13756                                 IntResult, E->getType(), Result);
13757   }
13758 
13759   case CK_FixedPointToFloating: {
13760     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13761     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13762       return false;
13763     Result =
13764         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13765     return true;
13766   }
13767 
13768   case CK_FloatingCast: {
13769     if (!Visit(SubExpr))
13770       return false;
13771     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13772                                   Result);
13773   }
13774 
13775   case CK_FloatingComplexToReal: {
13776     ComplexValue V;
13777     if (!EvaluateComplex(SubExpr, V, Info))
13778       return false;
13779     Result = V.getComplexFloatReal();
13780     return true;
13781   }
13782   }
13783 }
13784 
13785 //===----------------------------------------------------------------------===//
13786 // Complex Evaluation (for float and integer)
13787 //===----------------------------------------------------------------------===//
13788 
13789 namespace {
13790 class ComplexExprEvaluator
13791   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13792   ComplexValue &Result;
13793 
13794 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)13795   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13796     : ExprEvaluatorBaseTy(info), Result(Result) {}
13797 
Success(const APValue & V,const Expr * e)13798   bool Success(const APValue &V, const Expr *e) {
13799     Result.setFrom(V);
13800     return true;
13801   }
13802 
13803   bool ZeroInitialization(const Expr *E);
13804 
13805   //===--------------------------------------------------------------------===//
13806   //                            Visitor Methods
13807   //===--------------------------------------------------------------------===//
13808 
13809   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13810   bool VisitCastExpr(const CastExpr *E);
13811   bool VisitBinaryOperator(const BinaryOperator *E);
13812   bool VisitUnaryOperator(const UnaryOperator *E);
13813   bool VisitInitListExpr(const InitListExpr *E);
13814   bool VisitCallExpr(const CallExpr *E);
13815 };
13816 } // end anonymous namespace
13817 
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)13818 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13819                             EvalInfo &Info) {
13820   assert(!E->isValueDependent());
13821   assert(E->isRValue() && E->getType()->isAnyComplexType());
13822   return ComplexExprEvaluator(Info, Result).Visit(E);
13823 }
13824 
ZeroInitialization(const Expr * E)13825 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13826   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13827   if (ElemTy->isRealFloatingType()) {
13828     Result.makeComplexFloat();
13829     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13830     Result.FloatReal = Zero;
13831     Result.FloatImag = Zero;
13832   } else {
13833     Result.makeComplexInt();
13834     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13835     Result.IntReal = Zero;
13836     Result.IntImag = Zero;
13837   }
13838   return true;
13839 }
13840 
VisitImaginaryLiteral(const ImaginaryLiteral * E)13841 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13842   const Expr* SubExpr = E->getSubExpr();
13843 
13844   if (SubExpr->getType()->isRealFloatingType()) {
13845     Result.makeComplexFloat();
13846     APFloat &Imag = Result.FloatImag;
13847     if (!EvaluateFloat(SubExpr, Imag, Info))
13848       return false;
13849 
13850     Result.FloatReal = APFloat(Imag.getSemantics());
13851     return true;
13852   } else {
13853     assert(SubExpr->getType()->isIntegerType() &&
13854            "Unexpected imaginary literal.");
13855 
13856     Result.makeComplexInt();
13857     APSInt &Imag = Result.IntImag;
13858     if (!EvaluateInteger(SubExpr, Imag, Info))
13859       return false;
13860 
13861     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13862     return true;
13863   }
13864 }
13865 
VisitCastExpr(const CastExpr * E)13866 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13867 
13868   switch (E->getCastKind()) {
13869   case CK_BitCast:
13870   case CK_BaseToDerived:
13871   case CK_DerivedToBase:
13872   case CK_UncheckedDerivedToBase:
13873   case CK_Dynamic:
13874   case CK_ToUnion:
13875   case CK_ArrayToPointerDecay:
13876   case CK_FunctionToPointerDecay:
13877   case CK_NullToPointer:
13878   case CK_NullToMemberPointer:
13879   case CK_BaseToDerivedMemberPointer:
13880   case CK_DerivedToBaseMemberPointer:
13881   case CK_MemberPointerToBoolean:
13882   case CK_ReinterpretMemberPointer:
13883   case CK_ConstructorConversion:
13884   case CK_IntegralToPointer:
13885   case CK_PointerToIntegral:
13886   case CK_PointerToBoolean:
13887   case CK_ToVoid:
13888   case CK_VectorSplat:
13889   case CK_IntegralCast:
13890   case CK_BooleanToSignedIntegral:
13891   case CK_IntegralToBoolean:
13892   case CK_IntegralToFloating:
13893   case CK_FloatingToIntegral:
13894   case CK_FloatingToBoolean:
13895   case CK_FloatingCast:
13896   case CK_CPointerToObjCPointerCast:
13897   case CK_BlockPointerToObjCPointerCast:
13898   case CK_AnyPointerToBlockPointerCast:
13899   case CK_ObjCObjectLValueCast:
13900   case CK_FloatingComplexToReal:
13901   case CK_FloatingComplexToBoolean:
13902   case CK_IntegralComplexToReal:
13903   case CK_IntegralComplexToBoolean:
13904   case CK_ARCProduceObject:
13905   case CK_ARCConsumeObject:
13906   case CK_ARCReclaimReturnedObject:
13907   case CK_ARCExtendBlockObject:
13908   case CK_CopyAndAutoreleaseBlockObject:
13909   case CK_BuiltinFnToFnPtr:
13910   case CK_ZeroToOCLOpaqueType:
13911   case CK_NonAtomicToAtomic:
13912   case CK_AddressSpaceConversion:
13913   case CK_IntToOCLSampler:
13914   case CK_FloatingToFixedPoint:
13915   case CK_FixedPointToFloating:
13916   case CK_FixedPointCast:
13917   case CK_FixedPointToBoolean:
13918   case CK_FixedPointToIntegral:
13919   case CK_IntegralToFixedPoint:
13920     llvm_unreachable("invalid cast kind for complex value");
13921 
13922   case CK_LValueToRValue:
13923   case CK_AtomicToNonAtomic:
13924   case CK_NoOp:
13925   case CK_LValueToRValueBitCast:
13926     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13927 
13928   case CK_Dependent:
13929   case CK_LValueBitCast:
13930   case CK_UserDefinedConversion:
13931     return Error(E);
13932 
13933   case CK_FloatingRealToComplex: {
13934     APFloat &Real = Result.FloatReal;
13935     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13936       return false;
13937 
13938     Result.makeComplexFloat();
13939     Result.FloatImag = APFloat(Real.getSemantics());
13940     return true;
13941   }
13942 
13943   case CK_FloatingComplexCast: {
13944     if (!Visit(E->getSubExpr()))
13945       return false;
13946 
13947     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13948     QualType From
13949       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13950 
13951     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13952            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13953   }
13954 
13955   case CK_FloatingComplexToIntegralComplex: {
13956     if (!Visit(E->getSubExpr()))
13957       return false;
13958 
13959     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13960     QualType From
13961       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13962     Result.makeComplexInt();
13963     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13964                                 To, Result.IntReal) &&
13965            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13966                                 To, Result.IntImag);
13967   }
13968 
13969   case CK_IntegralRealToComplex: {
13970     APSInt &Real = Result.IntReal;
13971     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13972       return false;
13973 
13974     Result.makeComplexInt();
13975     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13976     return true;
13977   }
13978 
13979   case CK_IntegralComplexCast: {
13980     if (!Visit(E->getSubExpr()))
13981       return false;
13982 
13983     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13984     QualType From
13985       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13986 
13987     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13988     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13989     return true;
13990   }
13991 
13992   case CK_IntegralComplexToFloatingComplex: {
13993     if (!Visit(E->getSubExpr()))
13994       return false;
13995 
13996     const FPOptions FPO = E->getFPFeaturesInEffect(
13997                                   Info.Ctx.getLangOpts());
13998     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13999     QualType From
14000       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14001     Result.makeComplexFloat();
14002     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14003                                 To, Result.FloatReal) &&
14004            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14005                                 To, Result.FloatImag);
14006   }
14007   }
14008 
14009   llvm_unreachable("unknown cast resulting in complex value");
14010 }
14011 
VisitBinaryOperator(const BinaryOperator * E)14012 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14013   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14014     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14015 
14016   // Track whether the LHS or RHS is real at the type system level. When this is
14017   // the case we can simplify our evaluation strategy.
14018   bool LHSReal = false, RHSReal = false;
14019 
14020   bool LHSOK;
14021   if (E->getLHS()->getType()->isRealFloatingType()) {
14022     LHSReal = true;
14023     APFloat &Real = Result.FloatReal;
14024     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14025     if (LHSOK) {
14026       Result.makeComplexFloat();
14027       Result.FloatImag = APFloat(Real.getSemantics());
14028     }
14029   } else {
14030     LHSOK = Visit(E->getLHS());
14031   }
14032   if (!LHSOK && !Info.noteFailure())
14033     return false;
14034 
14035   ComplexValue RHS;
14036   if (E->getRHS()->getType()->isRealFloatingType()) {
14037     RHSReal = true;
14038     APFloat &Real = RHS.FloatReal;
14039     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14040       return false;
14041     RHS.makeComplexFloat();
14042     RHS.FloatImag = APFloat(Real.getSemantics());
14043   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14044     return false;
14045 
14046   assert(!(LHSReal && RHSReal) &&
14047          "Cannot have both operands of a complex operation be real.");
14048   switch (E->getOpcode()) {
14049   default: return Error(E);
14050   case BO_Add:
14051     if (Result.isComplexFloat()) {
14052       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14053                                        APFloat::rmNearestTiesToEven);
14054       if (LHSReal)
14055         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14056       else if (!RHSReal)
14057         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14058                                          APFloat::rmNearestTiesToEven);
14059     } else {
14060       Result.getComplexIntReal() += RHS.getComplexIntReal();
14061       Result.getComplexIntImag() += RHS.getComplexIntImag();
14062     }
14063     break;
14064   case BO_Sub:
14065     if (Result.isComplexFloat()) {
14066       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14067                                             APFloat::rmNearestTiesToEven);
14068       if (LHSReal) {
14069         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14070         Result.getComplexFloatImag().changeSign();
14071       } else if (!RHSReal) {
14072         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14073                                               APFloat::rmNearestTiesToEven);
14074       }
14075     } else {
14076       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14077       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14078     }
14079     break;
14080   case BO_Mul:
14081     if (Result.isComplexFloat()) {
14082       // This is an implementation of complex multiplication according to the
14083       // constraints laid out in C11 Annex G. The implementation uses the
14084       // following naming scheme:
14085       //   (a + ib) * (c + id)
14086       ComplexValue LHS = Result;
14087       APFloat &A = LHS.getComplexFloatReal();
14088       APFloat &B = LHS.getComplexFloatImag();
14089       APFloat &C = RHS.getComplexFloatReal();
14090       APFloat &D = RHS.getComplexFloatImag();
14091       APFloat &ResR = Result.getComplexFloatReal();
14092       APFloat &ResI = Result.getComplexFloatImag();
14093       if (LHSReal) {
14094         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14095         ResR = A * C;
14096         ResI = A * D;
14097       } else if (RHSReal) {
14098         ResR = C * A;
14099         ResI = C * B;
14100       } else {
14101         // In the fully general case, we need to handle NaNs and infinities
14102         // robustly.
14103         APFloat AC = A * C;
14104         APFloat BD = B * D;
14105         APFloat AD = A * D;
14106         APFloat BC = B * C;
14107         ResR = AC - BD;
14108         ResI = AD + BC;
14109         if (ResR.isNaN() && ResI.isNaN()) {
14110           bool Recalc = false;
14111           if (A.isInfinity() || B.isInfinity()) {
14112             A = APFloat::copySign(
14113                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14114             B = APFloat::copySign(
14115                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14116             if (C.isNaN())
14117               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14118             if (D.isNaN())
14119               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14120             Recalc = true;
14121           }
14122           if (C.isInfinity() || D.isInfinity()) {
14123             C = APFloat::copySign(
14124                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14125             D = APFloat::copySign(
14126                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14127             if (A.isNaN())
14128               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14129             if (B.isNaN())
14130               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14131             Recalc = true;
14132           }
14133           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14134                           AD.isInfinity() || BC.isInfinity())) {
14135             if (A.isNaN())
14136               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14137             if (B.isNaN())
14138               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14139             if (C.isNaN())
14140               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14141             if (D.isNaN())
14142               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14143             Recalc = true;
14144           }
14145           if (Recalc) {
14146             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14147             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14148           }
14149         }
14150       }
14151     } else {
14152       ComplexValue LHS = Result;
14153       Result.getComplexIntReal() =
14154         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14155          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14156       Result.getComplexIntImag() =
14157         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14158          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14159     }
14160     break;
14161   case BO_Div:
14162     if (Result.isComplexFloat()) {
14163       // This is an implementation of complex division according to the
14164       // constraints laid out in C11 Annex G. The implementation uses the
14165       // following naming scheme:
14166       //   (a + ib) / (c + id)
14167       ComplexValue LHS = Result;
14168       APFloat &A = LHS.getComplexFloatReal();
14169       APFloat &B = LHS.getComplexFloatImag();
14170       APFloat &C = RHS.getComplexFloatReal();
14171       APFloat &D = RHS.getComplexFloatImag();
14172       APFloat &ResR = Result.getComplexFloatReal();
14173       APFloat &ResI = Result.getComplexFloatImag();
14174       if (RHSReal) {
14175         ResR = A / C;
14176         ResI = B / C;
14177       } else {
14178         if (LHSReal) {
14179           // No real optimizations we can do here, stub out with zero.
14180           B = APFloat::getZero(A.getSemantics());
14181         }
14182         int DenomLogB = 0;
14183         APFloat MaxCD = maxnum(abs(C), abs(D));
14184         if (MaxCD.isFinite()) {
14185           DenomLogB = ilogb(MaxCD);
14186           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14187           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14188         }
14189         APFloat Denom = C * C + D * D;
14190         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14191                       APFloat::rmNearestTiesToEven);
14192         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14193                       APFloat::rmNearestTiesToEven);
14194         if (ResR.isNaN() && ResI.isNaN()) {
14195           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14196             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14197             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14198           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14199                      D.isFinite()) {
14200             A = APFloat::copySign(
14201                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14202             B = APFloat::copySign(
14203                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14204             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14205             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14206           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14207             C = APFloat::copySign(
14208                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14209             D = APFloat::copySign(
14210                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14211             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14212             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14213           }
14214         }
14215       }
14216     } else {
14217       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14218         return Error(E, diag::note_expr_divide_by_zero);
14219 
14220       ComplexValue LHS = Result;
14221       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14222         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14223       Result.getComplexIntReal() =
14224         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14225          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14226       Result.getComplexIntImag() =
14227         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14228          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14229     }
14230     break;
14231   }
14232 
14233   return true;
14234 }
14235 
VisitUnaryOperator(const UnaryOperator * E)14236 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14237   // Get the operand value into 'Result'.
14238   if (!Visit(E->getSubExpr()))
14239     return false;
14240 
14241   switch (E->getOpcode()) {
14242   default:
14243     return Error(E);
14244   case UO_Extension:
14245     return true;
14246   case UO_Plus:
14247     // The result is always just the subexpr.
14248     return true;
14249   case UO_Minus:
14250     if (Result.isComplexFloat()) {
14251       Result.getComplexFloatReal().changeSign();
14252       Result.getComplexFloatImag().changeSign();
14253     }
14254     else {
14255       Result.getComplexIntReal() = -Result.getComplexIntReal();
14256       Result.getComplexIntImag() = -Result.getComplexIntImag();
14257     }
14258     return true;
14259   case UO_Not:
14260     if (Result.isComplexFloat())
14261       Result.getComplexFloatImag().changeSign();
14262     else
14263       Result.getComplexIntImag() = -Result.getComplexIntImag();
14264     return true;
14265   }
14266 }
14267 
VisitInitListExpr(const InitListExpr * E)14268 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14269   if (E->getNumInits() == 2) {
14270     if (E->getType()->isComplexType()) {
14271       Result.makeComplexFloat();
14272       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14273         return false;
14274       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14275         return false;
14276     } else {
14277       Result.makeComplexInt();
14278       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14279         return false;
14280       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14281         return false;
14282     }
14283     return true;
14284   }
14285   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14286 }
14287 
VisitCallExpr(const CallExpr * E)14288 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14289   switch (E->getBuiltinCallee()) {
14290   case Builtin::BI__builtin_complex:
14291     Result.makeComplexFloat();
14292     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14293       return false;
14294     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14295       return false;
14296     return true;
14297 
14298   default:
14299     break;
14300   }
14301 
14302   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14303 }
14304 
14305 //===----------------------------------------------------------------------===//
14306 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14307 // implicit conversion.
14308 //===----------------------------------------------------------------------===//
14309 
14310 namespace {
14311 class AtomicExprEvaluator :
14312     public ExprEvaluatorBase<AtomicExprEvaluator> {
14313   const LValue *This;
14314   APValue &Result;
14315 public:
AtomicExprEvaluator(EvalInfo & Info,const LValue * This,APValue & Result)14316   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14317       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14318 
Success(const APValue & V,const Expr * E)14319   bool Success(const APValue &V, const Expr *E) {
14320     Result = V;
14321     return true;
14322   }
14323 
ZeroInitialization(const Expr * E)14324   bool ZeroInitialization(const Expr *E) {
14325     ImplicitValueInitExpr VIE(
14326         E->getType()->castAs<AtomicType>()->getValueType());
14327     // For atomic-qualified class (and array) types in C++, initialize the
14328     // _Atomic-wrapped subobject directly, in-place.
14329     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14330                 : Evaluate(Result, Info, &VIE);
14331   }
14332 
VisitCastExpr(const CastExpr * E)14333   bool VisitCastExpr(const CastExpr *E) {
14334     switch (E->getCastKind()) {
14335     default:
14336       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14337     case CK_NonAtomicToAtomic:
14338       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14339                   : Evaluate(Result, Info, E->getSubExpr());
14340     }
14341   }
14342 };
14343 } // end anonymous namespace
14344 
EvaluateAtomic(const Expr * E,const LValue * This,APValue & Result,EvalInfo & Info)14345 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14346                            EvalInfo &Info) {
14347   assert(!E->isValueDependent());
14348   assert(E->isRValue() && E->getType()->isAtomicType());
14349   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14350 }
14351 
14352 //===----------------------------------------------------------------------===//
14353 // Void expression evaluation, primarily for a cast to void on the LHS of a
14354 // comma operator
14355 //===----------------------------------------------------------------------===//
14356 
14357 namespace {
14358 class VoidExprEvaluator
14359   : public ExprEvaluatorBase<VoidExprEvaluator> {
14360 public:
VoidExprEvaluator(EvalInfo & Info)14361   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14362 
Success(const APValue & V,const Expr * e)14363   bool Success(const APValue &V, const Expr *e) { return true; }
14364 
ZeroInitialization(const Expr * E)14365   bool ZeroInitialization(const Expr *E) { return true; }
14366 
VisitCastExpr(const CastExpr * E)14367   bool VisitCastExpr(const CastExpr *E) {
14368     switch (E->getCastKind()) {
14369     default:
14370       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14371     case CK_ToVoid:
14372       VisitIgnoredValue(E->getSubExpr());
14373       return true;
14374     }
14375   }
14376 
VisitCallExpr(const CallExpr * E)14377   bool VisitCallExpr(const CallExpr *E) {
14378     switch (E->getBuiltinCallee()) {
14379     case Builtin::BI__assume:
14380     case Builtin::BI__builtin_assume:
14381       // The argument is not evaluated!
14382       return true;
14383 
14384     case Builtin::BI__builtin_operator_delete:
14385       return HandleOperatorDeleteCall(Info, E);
14386 
14387     default:
14388       break;
14389     }
14390 
14391     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14392   }
14393 
14394   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14395 };
14396 } // end anonymous namespace
14397 
VisitCXXDeleteExpr(const CXXDeleteExpr * E)14398 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14399   // We cannot speculatively evaluate a delete expression.
14400   if (Info.SpeculativeEvaluationDepth)
14401     return false;
14402 
14403   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14404   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14405     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14406         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14407     return false;
14408   }
14409 
14410   const Expr *Arg = E->getArgument();
14411 
14412   LValue Pointer;
14413   if (!EvaluatePointer(Arg, Pointer, Info))
14414     return false;
14415   if (Pointer.Designator.Invalid)
14416     return false;
14417 
14418   // Deleting a null pointer has no effect.
14419   if (Pointer.isNullPointer()) {
14420     // This is the only case where we need to produce an extension warning:
14421     // the only other way we can succeed is if we find a dynamic allocation,
14422     // and we will have warned when we allocated it in that case.
14423     if (!Info.getLangOpts().CPlusPlus20)
14424       Info.CCEDiag(E, diag::note_constexpr_new);
14425     return true;
14426   }
14427 
14428   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14429       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14430   if (!Alloc)
14431     return false;
14432   QualType AllocType = Pointer.Base.getDynamicAllocType();
14433 
14434   // For the non-array case, the designator must be empty if the static type
14435   // does not have a virtual destructor.
14436   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14437       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14438     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14439         << Arg->getType()->getPointeeType() << AllocType;
14440     return false;
14441   }
14442 
14443   // For a class type with a virtual destructor, the selected operator delete
14444   // is the one looked up when building the destructor.
14445   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14446     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14447     if (VirtualDelete &&
14448         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14449       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14450           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14451       return false;
14452     }
14453   }
14454 
14455   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14456                          (*Alloc)->Value, AllocType))
14457     return false;
14458 
14459   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14460     // The element was already erased. This means the destructor call also
14461     // deleted the object.
14462     // FIXME: This probably results in undefined behavior before we get this
14463     // far, and should be diagnosed elsewhere first.
14464     Info.FFDiag(E, diag::note_constexpr_double_delete);
14465     return false;
14466   }
14467 
14468   return true;
14469 }
14470 
EvaluateVoid(const Expr * E,EvalInfo & Info)14471 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14472   assert(!E->isValueDependent());
14473   assert(E->isRValue() && E->getType()->isVoidType());
14474   return VoidExprEvaluator(Info).Visit(E);
14475 }
14476 
14477 //===----------------------------------------------------------------------===//
14478 // Top level Expr::EvaluateAsRValue method.
14479 //===----------------------------------------------------------------------===//
14480 
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)14481 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14482   assert(!E->isValueDependent());
14483   // In C, function designators are not lvalues, but we evaluate them as if they
14484   // are.
14485   QualType T = E->getType();
14486   if (E->isGLValue() || T->isFunctionType()) {
14487     LValue LV;
14488     if (!EvaluateLValue(E, LV, Info))
14489       return false;
14490     LV.moveInto(Result);
14491   } else if (T->isVectorType()) {
14492     if (!EvaluateVector(E, Result, Info))
14493       return false;
14494   } else if (T->isIntegralOrEnumerationType()) {
14495     if (!IntExprEvaluator(Info, Result).Visit(E))
14496       return false;
14497   } else if (T->hasPointerRepresentation()) {
14498     LValue LV;
14499     if (!EvaluatePointer(E, LV, Info))
14500       return false;
14501     LV.moveInto(Result);
14502   } else if (T->isRealFloatingType()) {
14503     llvm::APFloat F(0.0);
14504     if (!EvaluateFloat(E, F, Info))
14505       return false;
14506     Result = APValue(F);
14507   } else if (T->isAnyComplexType()) {
14508     ComplexValue C;
14509     if (!EvaluateComplex(E, C, Info))
14510       return false;
14511     C.moveInto(Result);
14512   } else if (T->isFixedPointType()) {
14513     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14514   } else if (T->isMemberPointerType()) {
14515     MemberPtr P;
14516     if (!EvaluateMemberPointer(E, P, Info))
14517       return false;
14518     P.moveInto(Result);
14519     return true;
14520   } else if (T->isArrayType()) {
14521     LValue LV;
14522     APValue &Value =
14523         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14524     if (!EvaluateArray(E, LV, Value, Info))
14525       return false;
14526     Result = Value;
14527   } else if (T->isRecordType()) {
14528     LValue LV;
14529     APValue &Value =
14530         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14531     if (!EvaluateRecord(E, LV, Value, Info))
14532       return false;
14533     Result = Value;
14534   } else if (T->isVoidType()) {
14535     if (!Info.getLangOpts().CPlusPlus11)
14536       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14537         << E->getType();
14538     if (!EvaluateVoid(E, Info))
14539       return false;
14540   } else if (T->isAtomicType()) {
14541     QualType Unqual = T.getAtomicUnqualifiedType();
14542     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14543       LValue LV;
14544       APValue &Value = Info.CurrentCall->createTemporary(
14545           E, Unqual, ScopeKind::FullExpression, LV);
14546       if (!EvaluateAtomic(E, &LV, Value, Info))
14547         return false;
14548     } else {
14549       if (!EvaluateAtomic(E, nullptr, Result, Info))
14550         return false;
14551     }
14552   } else if (Info.getLangOpts().CPlusPlus11) {
14553     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14554     return false;
14555   } else {
14556     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14557     return false;
14558   }
14559 
14560   return true;
14561 }
14562 
14563 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14564 /// cases, the in-place evaluation is essential, since later initializers for
14565 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,bool AllowNonLiteralTypes)14566 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14567                             const Expr *E, bool AllowNonLiteralTypes) {
14568   assert(!E->isValueDependent());
14569 
14570   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14571     return false;
14572 
14573   if (E->isRValue()) {
14574     // Evaluate arrays and record types in-place, so that later initializers can
14575     // refer to earlier-initialized members of the object.
14576     QualType T = E->getType();
14577     if (T->isArrayType())
14578       return EvaluateArray(E, This, Result, Info);
14579     else if (T->isRecordType())
14580       return EvaluateRecord(E, This, Result, Info);
14581     else if (T->isAtomicType()) {
14582       QualType Unqual = T.getAtomicUnqualifiedType();
14583       if (Unqual->isArrayType() || Unqual->isRecordType())
14584         return EvaluateAtomic(E, &This, Result, Info);
14585     }
14586   }
14587 
14588   // For any other type, in-place evaluation is unimportant.
14589   return Evaluate(Result, Info, E);
14590 }
14591 
14592 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14593 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)14594 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14595   assert(!E->isValueDependent());
14596   if (Info.EnableNewConstInterp) {
14597     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14598       return false;
14599   } else {
14600     if (E->getType().isNull())
14601       return false;
14602 
14603     if (!CheckLiteralType(Info, E))
14604       return false;
14605 
14606     if (!::Evaluate(Result, Info, E))
14607       return false;
14608 
14609     if (E->isGLValue()) {
14610       LValue LV;
14611       LV.setFrom(Info.Ctx, Result);
14612       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14613         return false;
14614     }
14615   }
14616 
14617   // Check this core constant expression is a constant expression.
14618   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14619                                  ConstantExprKind::Normal) &&
14620          CheckMemoryLeaks(Info);
14621 }
14622 
FastEvaluateAsRValue(const Expr * Exp,Expr::EvalResult & Result,const ASTContext & Ctx,bool & IsConst)14623 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14624                                  const ASTContext &Ctx, bool &IsConst) {
14625   // Fast-path evaluations of integer literals, since we sometimes see files
14626   // containing vast quantities of these.
14627   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14628     Result.Val = APValue(APSInt(L->getValue(),
14629                                 L->getType()->isUnsignedIntegerType()));
14630     IsConst = true;
14631     return true;
14632   }
14633 
14634   // This case should be rare, but we need to check it before we check on
14635   // the type below.
14636   if (Exp->getType().isNull()) {
14637     IsConst = false;
14638     return true;
14639   }
14640 
14641   // FIXME: Evaluating values of large array and record types can cause
14642   // performance problems. Only do so in C++11 for now.
14643   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14644                           Exp->getType()->isRecordType()) &&
14645       !Ctx.getLangOpts().CPlusPlus11) {
14646     IsConst = false;
14647     return true;
14648   }
14649   return false;
14650 }
14651 
hasUnacceptableSideEffect(Expr::EvalStatus & Result,Expr::SideEffectsKind SEK)14652 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14653                                       Expr::SideEffectsKind SEK) {
14654   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14655          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14656 }
14657 
EvaluateAsRValue(const Expr * E,Expr::EvalResult & Result,const ASTContext & Ctx,EvalInfo & Info)14658 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14659                              const ASTContext &Ctx, EvalInfo &Info) {
14660   assert(!E->isValueDependent());
14661   bool IsConst;
14662   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14663     return IsConst;
14664 
14665   return EvaluateAsRValue(Info, E, Result.Val);
14666 }
14667 
EvaluateAsInt(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14668 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14669                           const ASTContext &Ctx,
14670                           Expr::SideEffectsKind AllowSideEffects,
14671                           EvalInfo &Info) {
14672   assert(!E->isValueDependent());
14673   if (!E->getType()->isIntegralOrEnumerationType())
14674     return false;
14675 
14676   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14677       !ExprResult.Val.isInt() ||
14678       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14679     return false;
14680 
14681   return true;
14682 }
14683 
EvaluateAsFixedPoint(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14684 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14685                                  const ASTContext &Ctx,
14686                                  Expr::SideEffectsKind AllowSideEffects,
14687                                  EvalInfo &Info) {
14688   assert(!E->isValueDependent());
14689   if (!E->getType()->isFixedPointType())
14690     return false;
14691 
14692   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14693     return false;
14694 
14695   if (!ExprResult.Val.isFixedPoint() ||
14696       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14697     return false;
14698 
14699   return true;
14700 }
14701 
14702 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14703 /// any crazy technique (that has nothing to do with language standards) that
14704 /// we want to.  If this function returns true, it returns the folded constant
14705 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14706 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const14707 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14708                             bool InConstantContext) const {
14709   assert(!isValueDependent() &&
14710          "Expression evaluator can't be called on a dependent expression.");
14711   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14712   Info.InConstantContext = InConstantContext;
14713   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14714 }
14715 
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx,bool InConstantContext) const14716 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14717                                       bool InConstantContext) const {
14718   assert(!isValueDependent() &&
14719          "Expression evaluator can't be called on a dependent expression.");
14720   EvalResult Scratch;
14721   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14722          HandleConversionToBool(Scratch.Val, Result);
14723 }
14724 
EvaluateAsInt(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14725 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14726                          SideEffectsKind AllowSideEffects,
14727                          bool InConstantContext) const {
14728   assert(!isValueDependent() &&
14729          "Expression evaluator can't be called on a dependent expression.");
14730   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14731   Info.InConstantContext = InConstantContext;
14732   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14733 }
14734 
EvaluateAsFixedPoint(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14735 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14736                                 SideEffectsKind AllowSideEffects,
14737                                 bool InConstantContext) const {
14738   assert(!isValueDependent() &&
14739          "Expression evaluator can't be called on a dependent expression.");
14740   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14741   Info.InConstantContext = InConstantContext;
14742   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14743 }
14744 
EvaluateAsFloat(APFloat & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14745 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14746                            SideEffectsKind AllowSideEffects,
14747                            bool InConstantContext) const {
14748   assert(!isValueDependent() &&
14749          "Expression evaluator can't be called on a dependent expression.");
14750 
14751   if (!getType()->isRealFloatingType())
14752     return false;
14753 
14754   EvalResult ExprResult;
14755   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14756       !ExprResult.Val.isFloat() ||
14757       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14758     return false;
14759 
14760   Result = ExprResult.Val.getFloat();
14761   return true;
14762 }
14763 
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const14764 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14765                             bool InConstantContext) const {
14766   assert(!isValueDependent() &&
14767          "Expression evaluator can't be called on a dependent expression.");
14768 
14769   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14770   Info.InConstantContext = InConstantContext;
14771   LValue LV;
14772   CheckedTemporaries CheckedTemps;
14773   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14774       Result.HasSideEffects ||
14775       !CheckLValueConstantExpression(Info, getExprLoc(),
14776                                      Ctx.getLValueReferenceType(getType()), LV,
14777                                      ConstantExprKind::Normal, CheckedTemps))
14778     return false;
14779 
14780   LV.moveInto(Result.Val);
14781   return true;
14782 }
14783 
EvaluateDestruction(const ASTContext & Ctx,APValue::LValueBase Base,APValue DestroyedValue,QualType Type,SourceLocation Loc,Expr::EvalStatus & EStatus)14784 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14785                                 APValue DestroyedValue, QualType Type,
14786                                 SourceLocation Loc, Expr::EvalStatus &EStatus) {
14787   EvalInfo Info(Ctx, EStatus, EvalInfo::EM_ConstantExpression);
14788   Info.setEvaluatingDecl(Base, DestroyedValue,
14789                          EvalInfo::EvaluatingDeclKind::Dtor);
14790   Info.InConstantContext = true;
14791 
14792   LValue LVal;
14793   LVal.set(Base);
14794 
14795   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14796       EStatus.HasSideEffects)
14797     return false;
14798 
14799   if (!Info.discardCleanups())
14800     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14801 
14802   return true;
14803 }
14804 
EvaluateAsConstantExpr(EvalResult & Result,const ASTContext & Ctx,ConstantExprKind Kind) const14805 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14806                                   ConstantExprKind Kind) const {
14807   assert(!isValueDependent() &&
14808          "Expression evaluator can't be called on a dependent expression.");
14809 
14810   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14811   EvalInfo Info(Ctx, Result, EM);
14812   Info.InConstantContext = true;
14813 
14814   // The type of the object we're initializing is 'const T' for a class NTTP.
14815   QualType T = getType();
14816   if (Kind == ConstantExprKind::ClassTemplateArgument)
14817     T.addConst();
14818 
14819   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14820   // represent the result of the evaluation. CheckConstantExpression ensures
14821   // this doesn't escape.
14822   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14823   APValue::LValueBase Base(&BaseMTE);
14824 
14825   Info.setEvaluatingDecl(Base, Result.Val);
14826   LValue LVal;
14827   LVal.set(Base);
14828 
14829   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14830     return false;
14831 
14832   if (!Info.discardCleanups())
14833     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14834 
14835   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14836                                Result.Val, Kind))
14837     return false;
14838   if (!CheckMemoryLeaks(Info))
14839     return false;
14840 
14841   // If this is a class template argument, it's required to have constant
14842   // destruction too.
14843   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14844       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result) ||
14845        Result.HasSideEffects)) {
14846     // FIXME: Prefix a note to indicate that the problem is lack of constant
14847     // destruction.
14848     return false;
14849   }
14850 
14851   return true;
14852 }
14853 
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const14854 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14855                                  const VarDecl *VD,
14856                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14857                                  bool IsConstantInitialization) const {
14858   assert(!isValueDependent() &&
14859          "Expression evaluator can't be called on a dependent expression.");
14860 
14861   // FIXME: Evaluating initializers for large array and record types can cause
14862   // performance problems. Only do so in C++11 for now.
14863   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14864       !Ctx.getLangOpts().CPlusPlus11)
14865     return false;
14866 
14867   Expr::EvalStatus EStatus;
14868   EStatus.Diag = &Notes;
14869 
14870   EvalInfo Info(Ctx, EStatus,
14871                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14872                     ? EvalInfo::EM_ConstantExpression
14873                     : EvalInfo::EM_ConstantFold);
14874   Info.setEvaluatingDecl(VD, Value);
14875   Info.InConstantContext = IsConstantInitialization;
14876 
14877   SourceLocation DeclLoc = VD->getLocation();
14878   QualType DeclTy = VD->getType();
14879 
14880   if (Info.EnableNewConstInterp) {
14881     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14882     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14883       return false;
14884   } else {
14885     LValue LVal;
14886     LVal.set(VD);
14887 
14888     if (!EvaluateInPlace(Value, Info, LVal, this,
14889                          /*AllowNonLiteralTypes=*/true) ||
14890         EStatus.HasSideEffects)
14891       return false;
14892 
14893     // At this point, any lifetime-extended temporaries are completely
14894     // initialized.
14895     Info.performLifetimeExtension();
14896 
14897     if (!Info.discardCleanups())
14898       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14899   }
14900   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14901                                  ConstantExprKind::Normal) &&
14902          CheckMemoryLeaks(Info);
14903 }
14904 
evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> & Notes) const14905 bool VarDecl::evaluateDestruction(
14906     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14907   Expr::EvalStatus EStatus;
14908   EStatus.Diag = &Notes;
14909 
14910   // Make a copy of the value for the destructor to mutate, if we know it.
14911   // Otherwise, treat the value as default-initialized; if the destructor works
14912   // anyway, then the destruction is constant (and must be essentially empty).
14913   APValue DestroyedValue;
14914   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14915     DestroyedValue = *getEvaluatedValue();
14916   else if (!getDefaultInitValue(getType(), DestroyedValue))
14917     return false;
14918 
14919   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14920                            getType(), getLocation(), EStatus) ||
14921       EStatus.HasSideEffects)
14922     return false;
14923 
14924   ensureEvaluatedStmt()->HasConstantDestruction = true;
14925   return true;
14926 }
14927 
14928 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14929 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx,SideEffectsKind SEK) const14930 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14931   assert(!isValueDependent() &&
14932          "Expression evaluator can't be called on a dependent expression.");
14933 
14934   EvalResult Result;
14935   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14936          !hasUnacceptableSideEffect(Result, SEK);
14937 }
14938 
EvaluateKnownConstInt(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const14939 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14940                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14941   assert(!isValueDependent() &&
14942          "Expression evaluator can't be called on a dependent expression.");
14943 
14944   EvalResult EVResult;
14945   EVResult.Diag = Diag;
14946   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14947   Info.InConstantContext = true;
14948 
14949   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14950   (void)Result;
14951   assert(Result && "Could not evaluate expression");
14952   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14953 
14954   return EVResult.Val.getInt();
14955 }
14956 
EvaluateKnownConstIntCheckOverflow(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const14957 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14958     const ASTContext &Ctx, 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   Info.CheckingForUndefinedBehavior = true;
14967 
14968   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14969   (void)Result;
14970   assert(Result && "Could not evaluate expression");
14971   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14972 
14973   return EVResult.Val.getInt();
14974 }
14975 
EvaluateForOverflow(const ASTContext & Ctx) const14976 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14977   assert(!isValueDependent() &&
14978          "Expression evaluator can't be called on a dependent expression.");
14979 
14980   bool IsConst;
14981   EvalResult EVResult;
14982   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14983     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14984     Info.CheckingForUndefinedBehavior = true;
14985     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14986   }
14987 }
14988 
isGlobalLValue() const14989 bool Expr::EvalResult::isGlobalLValue() const {
14990   assert(Val.isLValue());
14991   return IsGlobalLValue(Val.getLValueBase());
14992 }
14993 
14994 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14995 /// an integer constant expression.
14996 
14997 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14998 /// comma, etc
14999 
15000 // CheckICE - This function does the fundamental ICE checking: the returned
15001 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15002 // and a (possibly null) SourceLocation indicating the location of the problem.
15003 //
15004 // Note that to reduce code duplication, this helper does no evaluation
15005 // itself; the caller checks whether the expression is evaluatable, and
15006 // in the rare cases where CheckICE actually cares about the evaluated
15007 // value, it calls into Evaluate.
15008 
15009 namespace {
15010 
15011 enum ICEKind {
15012   /// This expression is an ICE.
15013   IK_ICE,
15014   /// This expression is not an ICE, but if it isn't evaluated, it's
15015   /// a legal subexpression for an ICE. This return value is used to handle
15016   /// the comma operator in C99 mode, and non-constant subexpressions.
15017   IK_ICEIfUnevaluated,
15018   /// This expression is not an ICE, and is not a legal subexpression for one.
15019   IK_NotICE
15020 };
15021 
15022 struct ICEDiag {
15023   ICEKind Kind;
15024   SourceLocation Loc;
15025 
ICEDiag__anona656c3113511::ICEDiag15026   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15027 };
15028 
15029 }
15030 
NoDiag()15031 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15032 
Worst(ICEDiag A,ICEDiag B)15033 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15034 
CheckEvalInICE(const Expr * E,const ASTContext & Ctx)15035 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15036   Expr::EvalResult EVResult;
15037   Expr::EvalStatus Status;
15038   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15039 
15040   Info.InConstantContext = true;
15041   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15042       !EVResult.Val.isInt())
15043     return ICEDiag(IK_NotICE, E->getBeginLoc());
15044 
15045   return NoDiag();
15046 }
15047 
CheckICE(const Expr * E,const ASTContext & Ctx)15048 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15049   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15050   if (!E->getType()->isIntegralOrEnumerationType())
15051     return ICEDiag(IK_NotICE, E->getBeginLoc());
15052 
15053   switch (E->getStmtClass()) {
15054 #define ABSTRACT_STMT(Node)
15055 #define STMT(Node, Base) case Expr::Node##Class:
15056 #define EXPR(Node, Base)
15057 #include "clang/AST/StmtNodes.inc"
15058   case Expr::PredefinedExprClass:
15059   case Expr::FloatingLiteralClass:
15060   case Expr::ImaginaryLiteralClass:
15061   case Expr::StringLiteralClass:
15062   case Expr::ArraySubscriptExprClass:
15063   case Expr::MatrixSubscriptExprClass:
15064   case Expr::OMPArraySectionExprClass:
15065   case Expr::OMPArrayShapingExprClass:
15066   case Expr::OMPIteratorExprClass:
15067   case Expr::MemberExprClass:
15068   case Expr::CompoundAssignOperatorClass:
15069   case Expr::CompoundLiteralExprClass:
15070   case Expr::ExtVectorElementExprClass:
15071   case Expr::DesignatedInitExprClass:
15072   case Expr::ArrayInitLoopExprClass:
15073   case Expr::ArrayInitIndexExprClass:
15074   case Expr::NoInitExprClass:
15075   case Expr::DesignatedInitUpdateExprClass:
15076   case Expr::ImplicitValueInitExprClass:
15077   case Expr::ParenListExprClass:
15078   case Expr::VAArgExprClass:
15079   case Expr::AddrLabelExprClass:
15080   case Expr::StmtExprClass:
15081   case Expr::CXXMemberCallExprClass:
15082   case Expr::CUDAKernelCallExprClass:
15083   case Expr::CXXAddrspaceCastExprClass:
15084   case Expr::CXXDynamicCastExprClass:
15085   case Expr::CXXTypeidExprClass:
15086   case Expr::CXXUuidofExprClass:
15087   case Expr::MSPropertyRefExprClass:
15088   case Expr::MSPropertySubscriptExprClass:
15089   case Expr::CXXNullPtrLiteralExprClass:
15090   case Expr::UserDefinedLiteralClass:
15091   case Expr::CXXThisExprClass:
15092   case Expr::CXXThrowExprClass:
15093   case Expr::CXXNewExprClass:
15094   case Expr::CXXDeleteExprClass:
15095   case Expr::CXXPseudoDestructorExprClass:
15096   case Expr::UnresolvedLookupExprClass:
15097   case Expr::TypoExprClass:
15098   case Expr::RecoveryExprClass:
15099   case Expr::DependentScopeDeclRefExprClass:
15100   case Expr::CXXConstructExprClass:
15101   case Expr::CXXInheritedCtorInitExprClass:
15102   case Expr::CXXStdInitializerListExprClass:
15103   case Expr::CXXBindTemporaryExprClass:
15104   case Expr::ExprWithCleanupsClass:
15105   case Expr::CXXTemporaryObjectExprClass:
15106   case Expr::CXXUnresolvedConstructExprClass:
15107   case Expr::CXXDependentScopeMemberExprClass:
15108   case Expr::UnresolvedMemberExprClass:
15109   case Expr::ObjCStringLiteralClass:
15110   case Expr::ObjCBoxedExprClass:
15111   case Expr::ObjCArrayLiteralClass:
15112   case Expr::ObjCDictionaryLiteralClass:
15113   case Expr::ObjCEncodeExprClass:
15114   case Expr::ObjCMessageExprClass:
15115   case Expr::ObjCSelectorExprClass:
15116   case Expr::ObjCProtocolExprClass:
15117   case Expr::ObjCIvarRefExprClass:
15118   case Expr::ObjCPropertyRefExprClass:
15119   case Expr::ObjCSubscriptRefExprClass:
15120   case Expr::ObjCIsaExprClass:
15121   case Expr::ObjCAvailabilityCheckExprClass:
15122   case Expr::ShuffleVectorExprClass:
15123   case Expr::ConvertVectorExprClass:
15124   case Expr::BlockExprClass:
15125   case Expr::NoStmtClass:
15126   case Expr::OpaqueValueExprClass:
15127   case Expr::PackExpansionExprClass:
15128   case Expr::SubstNonTypeTemplateParmPackExprClass:
15129   case Expr::FunctionParmPackExprClass:
15130   case Expr::AsTypeExprClass:
15131   case Expr::ObjCIndirectCopyRestoreExprClass:
15132   case Expr::MaterializeTemporaryExprClass:
15133   case Expr::PseudoObjectExprClass:
15134   case Expr::AtomicExprClass:
15135   case Expr::LambdaExprClass:
15136   case Expr::CXXFoldExprClass:
15137   case Expr::CoawaitExprClass:
15138   case Expr::DependentCoawaitExprClass:
15139   case Expr::CoyieldExprClass:
15140     return ICEDiag(IK_NotICE, E->getBeginLoc());
15141 
15142   case Expr::InitListExprClass: {
15143     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15144     // form "T x = { a };" is equivalent to "T x = a;".
15145     // Unless we're initializing a reference, T is a scalar as it is known to be
15146     // of integral or enumeration type.
15147     if (E->isRValue())
15148       if (cast<InitListExpr>(E)->getNumInits() == 1)
15149         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15150     return ICEDiag(IK_NotICE, E->getBeginLoc());
15151   }
15152 
15153   case Expr::SizeOfPackExprClass:
15154   case Expr::GNUNullExprClass:
15155   case Expr::SourceLocExprClass:
15156     return NoDiag();
15157 
15158   case Expr::SubstNonTypeTemplateParmExprClass:
15159     return
15160       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15161 
15162   case Expr::ConstantExprClass:
15163     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15164 
15165   case Expr::ParenExprClass:
15166     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15167   case Expr::GenericSelectionExprClass:
15168     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15169   case Expr::IntegerLiteralClass:
15170   case Expr::FixedPointLiteralClass:
15171   case Expr::CharacterLiteralClass:
15172   case Expr::ObjCBoolLiteralExprClass:
15173   case Expr::CXXBoolLiteralExprClass:
15174   case Expr::CXXScalarValueInitExprClass:
15175   case Expr::TypeTraitExprClass:
15176   case Expr::ConceptSpecializationExprClass:
15177   case Expr::RequiresExprClass:
15178   case Expr::ArrayTypeTraitExprClass:
15179   case Expr::ExpressionTraitExprClass:
15180   case Expr::CXXNoexceptExprClass:
15181     return NoDiag();
15182   case Expr::CallExprClass:
15183   case Expr::CXXOperatorCallExprClass: {
15184     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15185     // constant expressions, but they can never be ICEs because an ICE cannot
15186     // contain an operand of (pointer to) function type.
15187     const CallExpr *CE = cast<CallExpr>(E);
15188     if (CE->getBuiltinCallee())
15189       return CheckEvalInICE(E, Ctx);
15190     return ICEDiag(IK_NotICE, E->getBeginLoc());
15191   }
15192   case Expr::CXXRewrittenBinaryOperatorClass:
15193     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15194                     Ctx);
15195   case Expr::DeclRefExprClass: {
15196     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15197     if (isa<EnumConstantDecl>(D))
15198       return NoDiag();
15199 
15200     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15201     // integer variables in constant expressions:
15202     //
15203     // C++ 7.1.5.1p2
15204     //   A variable of non-volatile const-qualified integral or enumeration
15205     //   type initialized by an ICE can be used in ICEs.
15206     //
15207     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15208     // that mode, use of reference variables should not be allowed.
15209     const VarDecl *VD = dyn_cast<VarDecl>(D);
15210     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15211         !VD->getType()->isReferenceType())
15212       return NoDiag();
15213 
15214     return ICEDiag(IK_NotICE, E->getBeginLoc());
15215   }
15216   case Expr::UnaryOperatorClass: {
15217     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15218     switch (Exp->getOpcode()) {
15219     case UO_PostInc:
15220     case UO_PostDec:
15221     case UO_PreInc:
15222     case UO_PreDec:
15223     case UO_AddrOf:
15224     case UO_Deref:
15225     case UO_Coawait:
15226       // C99 6.6/3 allows increment and decrement within unevaluated
15227       // subexpressions of constant expressions, but they can never be ICEs
15228       // because an ICE cannot contain an lvalue operand.
15229       return ICEDiag(IK_NotICE, E->getBeginLoc());
15230     case UO_Extension:
15231     case UO_LNot:
15232     case UO_Plus:
15233     case UO_Minus:
15234     case UO_Not:
15235     case UO_Real:
15236     case UO_Imag:
15237       return CheckICE(Exp->getSubExpr(), Ctx);
15238     }
15239     llvm_unreachable("invalid unary operator class");
15240   }
15241   case Expr::OffsetOfExprClass: {
15242     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15243     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15244     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15245     // compliance: we should warn earlier for offsetof expressions with
15246     // array subscripts that aren't ICEs, and if the array subscripts
15247     // are ICEs, the value of the offsetof must be an integer constant.
15248     return CheckEvalInICE(E, Ctx);
15249   }
15250   case Expr::UnaryExprOrTypeTraitExprClass: {
15251     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15252     if ((Exp->getKind() ==  UETT_SizeOf) &&
15253         Exp->getTypeOfArgument()->isVariableArrayType())
15254       return ICEDiag(IK_NotICE, E->getBeginLoc());
15255     return NoDiag();
15256   }
15257   case Expr::BinaryOperatorClass: {
15258     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15259     switch (Exp->getOpcode()) {
15260     case BO_PtrMemD:
15261     case BO_PtrMemI:
15262     case BO_Assign:
15263     case BO_MulAssign:
15264     case BO_DivAssign:
15265     case BO_RemAssign:
15266     case BO_AddAssign:
15267     case BO_SubAssign:
15268     case BO_ShlAssign:
15269     case BO_ShrAssign:
15270     case BO_AndAssign:
15271     case BO_XorAssign:
15272     case BO_OrAssign:
15273       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15274       // constant expressions, but they can never be ICEs because an ICE cannot
15275       // contain an lvalue operand.
15276       return ICEDiag(IK_NotICE, E->getBeginLoc());
15277 
15278     case BO_Mul:
15279     case BO_Div:
15280     case BO_Rem:
15281     case BO_Add:
15282     case BO_Sub:
15283     case BO_Shl:
15284     case BO_Shr:
15285     case BO_LT:
15286     case BO_GT:
15287     case BO_LE:
15288     case BO_GE:
15289     case BO_EQ:
15290     case BO_NE:
15291     case BO_And:
15292     case BO_Xor:
15293     case BO_Or:
15294     case BO_Comma:
15295     case BO_Cmp: {
15296       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15297       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15298       if (Exp->getOpcode() == BO_Div ||
15299           Exp->getOpcode() == BO_Rem) {
15300         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15301         // we don't evaluate one.
15302         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15303           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15304           if (REval == 0)
15305             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15306           if (REval.isSigned() && REval.isAllOnesValue()) {
15307             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15308             if (LEval.isMinSignedValue())
15309               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15310           }
15311         }
15312       }
15313       if (Exp->getOpcode() == BO_Comma) {
15314         if (Ctx.getLangOpts().C99) {
15315           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15316           // if it isn't evaluated.
15317           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15318             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15319         } else {
15320           // In both C89 and C++, commas in ICEs are illegal.
15321           return ICEDiag(IK_NotICE, E->getBeginLoc());
15322         }
15323       }
15324       return Worst(LHSResult, RHSResult);
15325     }
15326     case BO_LAnd:
15327     case BO_LOr: {
15328       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15329       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15330       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15331         // Rare case where the RHS has a comma "side-effect"; we need
15332         // to actually check the condition to see whether the side
15333         // with the comma is evaluated.
15334         if ((Exp->getOpcode() == BO_LAnd) !=
15335             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15336           return RHSResult;
15337         return NoDiag();
15338       }
15339 
15340       return Worst(LHSResult, RHSResult);
15341     }
15342     }
15343     llvm_unreachable("invalid binary operator kind");
15344   }
15345   case Expr::ImplicitCastExprClass:
15346   case Expr::CStyleCastExprClass:
15347   case Expr::CXXFunctionalCastExprClass:
15348   case Expr::CXXStaticCastExprClass:
15349   case Expr::CXXReinterpretCastExprClass:
15350   case Expr::CXXConstCastExprClass:
15351   case Expr::ObjCBridgedCastExprClass: {
15352     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15353     if (isa<ExplicitCastExpr>(E)) {
15354       if (const FloatingLiteral *FL
15355             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15356         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15357         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15358         APSInt IgnoredVal(DestWidth, !DestSigned);
15359         bool Ignored;
15360         // If the value does not fit in the destination type, the behavior is
15361         // undefined, so we are not required to treat it as a constant
15362         // expression.
15363         if (FL->getValue().convertToInteger(IgnoredVal,
15364                                             llvm::APFloat::rmTowardZero,
15365                                             &Ignored) & APFloat::opInvalidOp)
15366           return ICEDiag(IK_NotICE, E->getBeginLoc());
15367         return NoDiag();
15368       }
15369     }
15370     switch (cast<CastExpr>(E)->getCastKind()) {
15371     case CK_LValueToRValue:
15372     case CK_AtomicToNonAtomic:
15373     case CK_NonAtomicToAtomic:
15374     case CK_NoOp:
15375     case CK_IntegralToBoolean:
15376     case CK_IntegralCast:
15377       return CheckICE(SubExpr, Ctx);
15378     default:
15379       return ICEDiag(IK_NotICE, E->getBeginLoc());
15380     }
15381   }
15382   case Expr::BinaryConditionalOperatorClass: {
15383     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15384     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15385     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15386     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15387     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15388     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15389     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15390         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15391     return FalseResult;
15392   }
15393   case Expr::ConditionalOperatorClass: {
15394     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15395     // If the condition (ignoring parens) is a __builtin_constant_p call,
15396     // then only the true side is actually considered in an integer constant
15397     // expression, and it is fully evaluated.  This is an important GNU
15398     // extension.  See GCC PR38377 for discussion.
15399     if (const CallExpr *CallCE
15400         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15401       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15402         return CheckEvalInICE(E, Ctx);
15403     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15404     if (CondResult.Kind == IK_NotICE)
15405       return CondResult;
15406 
15407     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15408     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15409 
15410     if (TrueResult.Kind == IK_NotICE)
15411       return TrueResult;
15412     if (FalseResult.Kind == IK_NotICE)
15413       return FalseResult;
15414     if (CondResult.Kind == IK_ICEIfUnevaluated)
15415       return CondResult;
15416     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15417       return NoDiag();
15418     // Rare case where the diagnostics depend on which side is evaluated
15419     // Note that if we get here, CondResult is 0, and at least one of
15420     // TrueResult and FalseResult is non-zero.
15421     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15422       return FalseResult;
15423     return TrueResult;
15424   }
15425   case Expr::CXXDefaultArgExprClass:
15426     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15427   case Expr::CXXDefaultInitExprClass:
15428     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15429   case Expr::ChooseExprClass: {
15430     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15431   }
15432   case Expr::BuiltinBitCastExprClass: {
15433     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15434       return ICEDiag(IK_NotICE, E->getBeginLoc());
15435     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15436   }
15437   }
15438 
15439   llvm_unreachable("Invalid StmtClass!");
15440 }
15441 
15442 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)15443 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15444                                                     const Expr *E,
15445                                                     llvm::APSInt *Value,
15446                                                     SourceLocation *Loc) {
15447   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15448     if (Loc) *Loc = E->getExprLoc();
15449     return false;
15450   }
15451 
15452   APValue Result;
15453   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15454     return false;
15455 
15456   if (!Result.isInt()) {
15457     if (Loc) *Loc = E->getExprLoc();
15458     return false;
15459   }
15460 
15461   if (Value) *Value = Result.getInt();
15462   return true;
15463 }
15464 
isIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const15465 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15466                                  SourceLocation *Loc) const {
15467   assert(!isValueDependent() &&
15468          "Expression evaluator can't be called on a dependent expression.");
15469 
15470   if (Ctx.getLangOpts().CPlusPlus11)
15471     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15472 
15473   ICEDiag D = CheckICE(this, Ctx);
15474   if (D.Kind != IK_ICE) {
15475     if (Loc) *Loc = D.Loc;
15476     return false;
15477   }
15478   return true;
15479 }
15480 
getIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc,bool isEvaluated) const15481 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15482                                                     SourceLocation *Loc,
15483                                                     bool isEvaluated) const {
15484   assert(!isValueDependent() &&
15485          "Expression evaluator can't be called on a dependent expression.");
15486 
15487   APSInt Value;
15488 
15489   if (Ctx.getLangOpts().CPlusPlus11) {
15490     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15491       return Value;
15492     return None;
15493   }
15494 
15495   if (!isIntegerConstantExpr(Ctx, Loc))
15496     return None;
15497 
15498   // The only possible side-effects here are due to UB discovered in the
15499   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15500   // required to treat the expression as an ICE, so we produce the folded
15501   // value.
15502   EvalResult ExprResult;
15503   Expr::EvalStatus Status;
15504   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15505   Info.InConstantContext = true;
15506 
15507   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15508     llvm_unreachable("ICE cannot be evaluated!");
15509 
15510   return ExprResult.Val.getInt();
15511 }
15512 
isCXX98IntegralConstantExpr(const ASTContext & Ctx) const15513 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15514   assert(!isValueDependent() &&
15515          "Expression evaluator can't be called on a dependent expression.");
15516 
15517   return CheckICE(this, Ctx).Kind == IK_ICE;
15518 }
15519 
isCXX11ConstantExpr(const ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const15520 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15521                                SourceLocation *Loc) const {
15522   assert(!isValueDependent() &&
15523          "Expression evaluator can't be called on a dependent expression.");
15524 
15525   // We support this checking in C++98 mode in order to diagnose compatibility
15526   // issues.
15527   assert(Ctx.getLangOpts().CPlusPlus);
15528 
15529   // Build evaluation settings.
15530   Expr::EvalStatus Status;
15531   SmallVector<PartialDiagnosticAt, 8> Diags;
15532   Status.Diag = &Diags;
15533   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15534 
15535   APValue Scratch;
15536   bool IsConstExpr =
15537       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15538       // FIXME: We don't produce a diagnostic for this, but the callers that
15539       // call us on arbitrary full-expressions should generally not care.
15540       Info.discardCleanups() && !Status.HasSideEffects;
15541 
15542   if (!Diags.empty()) {
15543     IsConstExpr = false;
15544     if (Loc) *Loc = Diags[0].first;
15545   } else if (!IsConstExpr) {
15546     // FIXME: This shouldn't happen.
15547     if (Loc) *Loc = getExprLoc();
15548   }
15549 
15550   return IsConstExpr;
15551 }
15552 
EvaluateWithSubstitution(APValue & Value,ASTContext & Ctx,const FunctionDecl * Callee,ArrayRef<const Expr * > Args,const Expr * This) const15553 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15554                                     const FunctionDecl *Callee,
15555                                     ArrayRef<const Expr*> Args,
15556                                     const Expr *This) const {
15557   assert(!isValueDependent() &&
15558          "Expression evaluator can't be called on a dependent expression.");
15559 
15560   Expr::EvalStatus Status;
15561   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15562   Info.InConstantContext = true;
15563 
15564   LValue ThisVal;
15565   const LValue *ThisPtr = nullptr;
15566   if (This) {
15567 #ifndef NDEBUG
15568     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15569     assert(MD && "Don't provide `this` for non-methods.");
15570     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15571 #endif
15572     if (!This->isValueDependent() &&
15573         EvaluateObjectArgument(Info, This, ThisVal) &&
15574         !Info.EvalStatus.HasSideEffects)
15575       ThisPtr = &ThisVal;
15576 
15577     // Ignore any side-effects from a failed evaluation. This is safe because
15578     // they can't interfere with any other argument evaluation.
15579     Info.EvalStatus.HasSideEffects = false;
15580   }
15581 
15582   CallRef Call = Info.CurrentCall->createCall(Callee);
15583   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15584        I != E; ++I) {
15585     unsigned Idx = I - Args.begin();
15586     if (Idx >= Callee->getNumParams())
15587       break;
15588     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15589     if ((*I)->isValueDependent() ||
15590         !EvaluateCallArg(PVD, *I, Call, Info) ||
15591         Info.EvalStatus.HasSideEffects) {
15592       // If evaluation fails, throw away the argument entirely.
15593       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15594         *Slot = APValue();
15595     }
15596 
15597     // Ignore any side-effects from a failed evaluation. This is safe because
15598     // they can't interfere with any other argument evaluation.
15599     Info.EvalStatus.HasSideEffects = false;
15600   }
15601 
15602   // Parameter cleanups happen in the caller and are not part of this
15603   // evaluation.
15604   Info.discardCleanups();
15605   Info.EvalStatus.HasSideEffects = false;
15606 
15607   // Build fake call to Callee.
15608   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15609   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15610   FullExpressionRAII Scope(Info);
15611   return Evaluate(Value, Info, this) && Scope.destroy() &&
15612          !Info.EvalStatus.HasSideEffects;
15613 }
15614 
isPotentialConstantExpr(const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15615 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15616                                    SmallVectorImpl<
15617                                      PartialDiagnosticAt> &Diags) {
15618   // FIXME: It would be useful to check constexpr function templates, but at the
15619   // moment the constant expression evaluator cannot cope with the non-rigorous
15620   // ASTs which we build for dependent expressions.
15621   if (FD->isDependentContext())
15622     return true;
15623 
15624   Expr::EvalStatus Status;
15625   Status.Diag = &Diags;
15626 
15627   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15628   Info.InConstantContext = true;
15629   Info.CheckingPotentialConstantExpression = true;
15630 
15631   // The constexpr VM attempts to compile all methods to bytecode here.
15632   if (Info.EnableNewConstInterp) {
15633     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15634     return Diags.empty();
15635   }
15636 
15637   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15638   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15639 
15640   // Fabricate an arbitrary expression on the stack and pretend that it
15641   // is a temporary being used as the 'this' pointer.
15642   LValue This;
15643   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15644   This.set({&VIE, Info.CurrentCall->Index});
15645 
15646   ArrayRef<const Expr*> Args;
15647 
15648   APValue Scratch;
15649   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15650     // Evaluate the call as a constant initializer, to allow the construction
15651     // of objects of non-literal types.
15652     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15653     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15654   } else {
15655     SourceLocation Loc = FD->getLocation();
15656     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15657                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15658   }
15659 
15660   return Diags.empty();
15661 }
15662 
isPotentialConstantExprUnevaluated(Expr * E,const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15663 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15664                                               const FunctionDecl *FD,
15665                                               SmallVectorImpl<
15666                                                 PartialDiagnosticAt> &Diags) {
15667   assert(!E->isValueDependent() &&
15668          "Expression evaluator can't be called on a dependent expression.");
15669 
15670   Expr::EvalStatus Status;
15671   Status.Diag = &Diags;
15672 
15673   EvalInfo Info(FD->getASTContext(), Status,
15674                 EvalInfo::EM_ConstantExpressionUnevaluated);
15675   Info.InConstantContext = true;
15676   Info.CheckingPotentialConstantExpression = true;
15677 
15678   // Fabricate a call stack frame to give the arguments a plausible cover story.
15679   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15680 
15681   APValue ResultScratch;
15682   Evaluate(ResultScratch, Info, E);
15683   return Diags.empty();
15684 }
15685 
tryEvaluateObjectSize(uint64_t & Result,ASTContext & Ctx,unsigned Type) const15686 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15687                                  unsigned Type) const {
15688   if (!getType()->isPointerType())
15689     return false;
15690 
15691   Expr::EvalStatus Status;
15692   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15693   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15694 }
15695