clang  6.0.0svn
ExprConstant.cpp
Go to the documentation of this file.
1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Expr constant evaluator.
11 //
12 // Constant expression evaluation produces four main results:
13 //
14 // * A success/failure flag indicating whether constant folding was successful.
15 // This is the 'bool' return value used by most of the code in this file. A
16 // 'false' return value indicates that constant folding has failed, and any
17 // appropriate diagnostic has already been produced.
18 //
19 // * An evaluated result, valid only if constant folding has not failed.
20 //
21 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 // where it is possible to determine the evaluated result regardless.
24 //
25 // * A set of notes indicating why the evaluation was not a constant expression
26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 // too, why the expression could not be folded.
28 //
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
39 #include "clang/AST/ASTLambda.h"
40 #include "clang/AST/CharUnits.h"
41 #include "clang/AST/Expr.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/StmtVisitor.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/Basic/Builtins.h"
46 #include "clang/Basic/TargetInfo.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using llvm::APSInt;
53 using llvm::APFloat;
54 
55 static bool IsGlobalLValue(APValue::LValueBase B);
56 
57 namespace {
58  struct LValue;
59  struct CallStackFrame;
60  struct EvalInfo;
61 
62  static QualType getType(APValue::LValueBase B) {
63  if (!B) return QualType();
64  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65  return D->getType();
66 
67  const Expr *Base = B.get<const Expr*>();
68 
69  // For a materialized temporary, the type of the temporary we materialized
70  // may not be the type of the expression.
71  if (const MaterializeTemporaryExpr *MTE =
72  dyn_cast<MaterializeTemporaryExpr>(Base)) {
75  const Expr *Temp = MTE->GetTemporaryExpr();
76  const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77  Adjustments);
78  // Keep any cv-qualifiers from the reference if we generated a temporary
79  // for it directly. Otherwise use the type after adjustment.
80  if (!Adjustments.empty())
81  return Inner->getType();
82  }
83 
84  return Base->getType();
85  }
86 
87  /// Get an LValue path entry, which is known to not be an array index, as a
88  /// field or base class.
89  static
92  Value.setFromOpaqueValue(E.BaseOrMember);
93  return Value;
94  }
95 
96  /// Get an LValue path entry, which is known to not be an array index, as a
97  /// field declaration.
98  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99  return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
100  }
101  /// Get an LValue path entry, which is known to not be an array index, as a
102  /// base class declaration.
103  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104  return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
105  }
106  /// Determine whether this LValue path entry for a base class names a virtual
107  /// base class.
108  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109  return getAsBaseOrMember(E).getInt();
110  }
111 
112  /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113  static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114  const FunctionDecl *Callee = CE->getDirectCallee();
115  return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
116  }
117 
118  /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119  /// This will look through a single cast.
120  ///
121  /// Returns null if we couldn't unwrap a function with alloc_size.
122  static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123  if (!E->getType()->isPointerType())
124  return nullptr;
125 
126  E = E->IgnoreParens();
127  // If we're doing a variable assignment from e.g. malloc(N), there will
128  // probably be a cast of some kind. Ignore it.
129  if (const auto *Cast = dyn_cast<CastExpr>(E))
130  E = Cast->getSubExpr()->IgnoreParens();
131 
132  if (const auto *CE = dyn_cast<CallExpr>(E))
133  return getAllocSizeAttr(CE) ? CE : nullptr;
134  return nullptr;
135  }
136 
137  /// Determines whether or not the given Base contains a call to a function
138  /// with the alloc_size attribute.
139  static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140  const auto *E = Base.dyn_cast<const Expr *>();
141  return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
142  }
143 
144  /// Determines if an LValue with the given LValueBase will have an unsized
145  /// array in its designator.
146  /// Find the path length and type of the most-derived subobject in the given
147  /// path, and find the size of the containing array, if any.
148  static unsigned
149  findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
151  uint64_t &ArraySize, QualType &Type, bool &IsArray) {
152  // This only accepts LValueBases from APValues, and APValues don't support
153  // arrays that lack size info.
154  assert(!isBaseAnAllocSizeCall(Base) &&
155  "Unsized arrays shouldn't appear here");
156  unsigned MostDerivedLength = 0;
157  Type = getType(Base);
158 
159  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
160  if (Type->isArrayType()) {
161  const ConstantArrayType *CAT =
162  cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
163  Type = CAT->getElementType();
164  ArraySize = CAT->getSize().getZExtValue();
165  MostDerivedLength = I + 1;
166  IsArray = true;
167  } else if (Type->isAnyComplexType()) {
168  const ComplexType *CT = Type->castAs<ComplexType>();
169  Type = CT->getElementType();
170  ArraySize = 2;
171  MostDerivedLength = I + 1;
172  IsArray = true;
173  } else if (const FieldDecl *FD = getAsField(Path[I])) {
174  Type = FD->getType();
175  ArraySize = 0;
176  MostDerivedLength = I + 1;
177  IsArray = false;
178  } else {
179  // Path[I] describes a base class.
180  ArraySize = 0;
181  IsArray = false;
182  }
183  }
184  return MostDerivedLength;
185  }
186 
187  // The order of this enum is important for diagnostics.
189  CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
190  CSK_This, CSK_Real, CSK_Imag
191  };
192 
193  /// A path from a glvalue to a subobject of that glvalue.
194  struct SubobjectDesignator {
195  /// True if the subobject was named in a manner not supported by C++11. Such
196  /// lvalues can still be folded, but they are not core constant expressions
197  /// and we cannot perform lvalue-to-rvalue conversions on them.
198  unsigned Invalid : 1;
199 
200  /// Is this a pointer one past the end of an object?
201  unsigned IsOnePastTheEnd : 1;
202 
203  /// Indicator of whether the first entry is an unsized array.
204  unsigned FirstEntryIsAnUnsizedArray : 1;
205 
206  /// Indicator of whether the most-derived object is an array element.
207  unsigned MostDerivedIsArrayElement : 1;
208 
209  /// The length of the path to the most-derived object of which this is a
210  /// subobject.
211  unsigned MostDerivedPathLength : 28;
212 
213  /// The size of the array of which the most-derived object is an element.
214  /// This will always be 0 if the most-derived object is not an array
215  /// element. 0 is not an indicator of whether or not the most-derived object
216  /// is an array, however, because 0-length arrays are allowed.
217  ///
218  /// If the current array is an unsized array, the value of this is
219  /// undefined.
220  uint64_t MostDerivedArraySize;
221 
222  /// The type of the most derived object referred to by this address.
223  QualType MostDerivedType;
224 
225  typedef APValue::LValuePathEntry PathEntry;
226 
227  /// The entries on the path from the glvalue to the designated subobject.
229 
230  SubobjectDesignator() : Invalid(true) {}
231 
232  explicit SubobjectDesignator(QualType T)
233  : Invalid(false), IsOnePastTheEnd(false),
234  FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
235  MostDerivedPathLength(0), MostDerivedArraySize(0),
236  MostDerivedType(T) {}
237 
238  SubobjectDesignator(ASTContext &Ctx, const APValue &V)
239  : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
240  FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
241  MostDerivedPathLength(0), MostDerivedArraySize(0) {
242  assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
243  if (!Invalid) {
244  IsOnePastTheEnd = V.isLValueOnePastTheEnd();
245  ArrayRef<PathEntry> VEntries = V.getLValuePath();
246  Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
247  if (V.getLValueBase()) {
248  bool IsArray = false;
249  MostDerivedPathLength = findMostDerivedSubobject(
250  Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251  MostDerivedType, IsArray);
252  MostDerivedIsArrayElement = IsArray;
253  }
254  }
255  }
256 
257  void setInvalid() {
258  Invalid = true;
259  Entries.clear();
260  }
261 
262  /// Determine whether the most derived subobject is an array without a
263  /// known bound.
264  bool isMostDerivedAnUnsizedArray() const {
265  assert(!Invalid && "Calling this makes no sense on invalid designators");
266  return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
267  }
268 
269  /// Determine what the most derived array's size is. Results in an assertion
270  /// failure if the most derived array lacks a size.
271  uint64_t getMostDerivedArraySize() const {
272  assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
273  return MostDerivedArraySize;
274  }
275 
276  /// Determine whether this is a one-past-the-end pointer.
277  bool isOnePastTheEnd() const {
278  assert(!Invalid);
279  if (IsOnePastTheEnd)
280  return true;
281  if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
282  Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
283  return true;
284  return false;
285  }
286 
287  /// Check that this refers to a valid subobject.
288  bool isValidSubobject() const {
289  if (Invalid)
290  return false;
291  return !isOnePastTheEnd();
292  }
293  /// Check that this refers to a valid subobject, and if not, produce a
294  /// relevant diagnostic and set the designator as invalid.
295  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
296 
297  /// Update this designator to refer to the first element within this array.
298  void addArrayUnchecked(const ConstantArrayType *CAT) {
299  PathEntry Entry;
300  Entry.ArrayIndex = 0;
301  Entries.push_back(Entry);
302 
303  // This is a most-derived object.
304  MostDerivedType = CAT->getElementType();
305  MostDerivedIsArrayElement = true;
306  MostDerivedArraySize = CAT->getSize().getZExtValue();
307  MostDerivedPathLength = Entries.size();
308  }
309  /// Update this designator to refer to the first element within the array of
310  /// elements of type T. This is an array of unknown size.
311  void addUnsizedArrayUnchecked(QualType ElemTy) {
312  PathEntry Entry;
313  Entry.ArrayIndex = 0;
314  Entries.push_back(Entry);
315 
316  MostDerivedType = ElemTy;
317  MostDerivedIsArrayElement = true;
318  // The value in MostDerivedArraySize is undefined in this case. So, set it
319  // to an arbitrary value that's likely to loudly break things if it's
320  // used.
321  MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
322  MostDerivedPathLength = Entries.size();
323  }
324  /// Update this designator to refer to the given base or member of this
325  /// object.
326  void addDeclUnchecked(const Decl *D, bool Virtual = false) {
327  PathEntry Entry;
328  APValue::BaseOrMemberType Value(D, Virtual);
329  Entry.BaseOrMember = Value.getOpaqueValue();
330  Entries.push_back(Entry);
331 
332  // If this isn't a base class, it's a new most-derived object.
333  if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
334  MostDerivedType = FD->getType();
335  MostDerivedIsArrayElement = false;
336  MostDerivedArraySize = 0;
337  MostDerivedPathLength = Entries.size();
338  }
339  }
340  /// Update this designator to refer to the given complex component.
341  void addComplexUnchecked(QualType EltTy, bool Imag) {
342  PathEntry Entry;
343  Entry.ArrayIndex = Imag;
344  Entries.push_back(Entry);
345 
346  // This is technically a most-derived object, though in practice this
347  // is unlikely to matter.
348  MostDerivedType = EltTy;
349  MostDerivedIsArrayElement = true;
350  MostDerivedArraySize = 2;
351  MostDerivedPathLength = Entries.size();
352  }
353  void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
354  const APSInt &N);
355  /// Add N to the address of this subobject.
356  void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
357  if (Invalid || !N) return;
358  uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
359  if (isMostDerivedAnUnsizedArray()) {
360  // Can't verify -- trust that the user is doing the right thing (or if
361  // not, trust that the caller will catch the bad behavior).
362  // FIXME: Should we reject if this overflows, at least?
363  Entries.back().ArrayIndex += TruncatedN;
364  return;
365  }
366 
367  // [expr.add]p4: For the purposes of these operators, a pointer to a
368  // nonarray object behaves the same as a pointer to the first element of
369  // an array of length one with the type of the object as its element type.
370  bool IsArray = MostDerivedPathLength == Entries.size() &&
371  MostDerivedIsArrayElement;
372  uint64_t ArrayIndex =
373  IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
374  uint64_t ArraySize =
375  IsArray ? getMostDerivedArraySize() : (uint64_t)1;
376 
377  if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
378  // Calculate the actual index in a wide enough type, so we can include
379  // it in the note.
380  N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
381  (llvm::APInt&)N += ArrayIndex;
382  assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
383  diagnosePointerArithmetic(Info, E, N);
384  setInvalid();
385  return;
386  }
387 
388  ArrayIndex += TruncatedN;
389  assert(ArrayIndex <= ArraySize &&
390  "bounds check succeeded for out-of-bounds index");
391 
392  if (IsArray)
393  Entries.back().ArrayIndex = ArrayIndex;
394  else
395  IsOnePastTheEnd = (ArrayIndex != 0);
396  }
397  };
398 
399  /// A stack frame in the constexpr call stack.
400  struct CallStackFrame {
401  EvalInfo &Info;
402 
403  /// Parent - The caller of this stack frame.
404  CallStackFrame *Caller;
405 
406  /// Callee - The function which was called.
407  const FunctionDecl *Callee;
408 
409  /// This - The binding for the this pointer in this call, if any.
410  const LValue *This;
411 
412  /// Arguments - Parameter bindings for this function call, indexed by
413  /// parameters' function scope indices.
414  APValue *Arguments;
415 
416  // Note that we intentionally use std::map here so that references to
417  // values are stable.
418  typedef std::map<const void*, APValue> MapTy;
419  typedef MapTy::const_iterator temp_iterator;
420  /// Temporaries - Temporary lvalues materialized within this stack frame.
421  MapTy Temporaries;
422 
423  /// CallLoc - The location of the call expression for this call.
424  SourceLocation CallLoc;
425 
426  /// Index - The call index of this call.
427  unsigned Index;
428 
429  // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
430  // on the overall stack usage of deeply-recursing constexpr evaluataions.
431  // (We should cache this map rather than recomputing it repeatedly.)
432  // But let's try this and see how it goes; we can look into caching the map
433  // as a later change.
434 
435  /// LambdaCaptureFields - Mapping from captured variables/this to
436  /// corresponding data members in the closure class.
437  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
438  FieldDecl *LambdaThisCaptureField;
439 
440  CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
441  const FunctionDecl *Callee, const LValue *This,
442  APValue *Arguments);
443  ~CallStackFrame();
444 
445  APValue *getTemporary(const void *Key) {
446  MapTy::iterator I = Temporaries.find(Key);
447  return I == Temporaries.end() ? nullptr : &I->second;
448  }
449  APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
450  };
451 
452  /// Temporarily override 'this'.
453  class ThisOverrideRAII {
454  public:
455  ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
456  : Frame(Frame), OldThis(Frame.This) {
457  if (Enable)
458  Frame.This = NewThis;
459  }
460  ~ThisOverrideRAII() {
461  Frame.This = OldThis;
462  }
463  private:
464  CallStackFrame &Frame;
465  const LValue *OldThis;
466  };
467 
468  /// A partial diagnostic which we might know in advance that we are not going
469  /// to emit.
470  class OptionalDiagnostic {
472 
473  public:
474  explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
475  : Diag(Diag) {}
476 
477  template<typename T>
478  OptionalDiagnostic &operator<<(const T &v) {
479  if (Diag)
480  *Diag << v;
481  return *this;
482  }
483 
484  OptionalDiagnostic &operator<<(const APSInt &I) {
485  if (Diag) {
486  SmallVector<char, 32> Buffer;
487  I.toString(Buffer);
488  *Diag << StringRef(Buffer.data(), Buffer.size());
489  }
490  return *this;
491  }
492 
493  OptionalDiagnostic &operator<<(const APFloat &F) {
494  if (Diag) {
495  // FIXME: Force the precision of the source value down so we don't
496  // print digits which are usually useless (we don't really care here if
497  // we truncate a digit by accident in edge cases). Ideally,
498  // APFloat::toString would automatically print the shortest
499  // representation which rounds to the correct value, but it's a bit
500  // tricky to implement.
501  unsigned precision =
502  llvm::APFloat::semanticsPrecision(F.getSemantics());
503  precision = (precision * 59 + 195) / 196;
504  SmallVector<char, 32> Buffer;
505  F.toString(Buffer, precision);
506  *Diag << StringRef(Buffer.data(), Buffer.size());
507  }
508  return *this;
509  }
510  };
511 
512  /// A cleanup, and a flag indicating whether it is lifetime-extended.
513  class Cleanup {
514  llvm::PointerIntPair<APValue*, 1, bool> Value;
515 
516  public:
517  Cleanup(APValue *Val, bool IsLifetimeExtended)
518  : Value(Val, IsLifetimeExtended) {}
519 
520  bool isLifetimeExtended() const { return Value.getInt(); }
521  void endLifetime() {
522  *Value.getPointer() = APValue();
523  }
524  };
525 
526  /// EvalInfo - This is a private struct used by the evaluator to capture
527  /// information about a subexpression as it is folded. It retains information
528  /// about the AST context, but also maintains information about the folded
529  /// expression.
530  ///
531  /// If an expression could be evaluated, it is still possible it is not a C
532  /// "integer constant expression" or constant expression. If not, this struct
533  /// captures information about how and why not.
534  ///
535  /// One bit of information passed *into* the request for constant folding
536  /// indicates whether the subexpression is "evaluated" or not according to C
537  /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
538  /// evaluate the expression regardless of what the RHS is, but C only allows
539  /// certain things in certain situations.
540  struct EvalInfo {
541  ASTContext &Ctx;
542 
543  /// EvalStatus - Contains information about the evaluation.
544  Expr::EvalStatus &EvalStatus;
545 
546  /// CurrentCall - The top of the constexpr call stack.
547  CallStackFrame *CurrentCall;
548 
549  /// CallStackDepth - The number of calls in the call stack right now.
550  unsigned CallStackDepth;
551 
552  /// NextCallIndex - The next call index to assign.
553  unsigned NextCallIndex;
554 
555  /// StepsLeft - The remaining number of evaluation steps we're permitted
556  /// to perform. This is essentially a limit for the number of statements
557  /// we will evaluate.
558  unsigned StepsLeft;
559 
560  /// BottomFrame - The frame in which evaluation started. This must be
561  /// initialized after CurrentCall and CallStackDepth.
562  CallStackFrame BottomFrame;
563 
564  /// A stack of values whose lifetimes end at the end of some surrounding
565  /// evaluation frame.
566  llvm::SmallVector<Cleanup, 16> CleanupStack;
567 
568  /// EvaluatingDecl - This is the declaration whose initializer is being
569  /// evaluated, if any.
570  APValue::LValueBase EvaluatingDecl;
571 
572  /// EvaluatingDeclValue - This is the value being constructed for the
573  /// declaration whose initializer is being evaluated, if any.
574  APValue *EvaluatingDeclValue;
575 
576  /// EvaluatingObject - Pair of the AST node that an lvalue represents and
577  /// the call index that that lvalue was allocated in.
578  typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
579 
580  /// EvaluatingConstructors - Set of objects that are currently being
581  /// constructed.
582  llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
583 
584  struct EvaluatingConstructorRAII {
585  EvalInfo &EI;
586  EvaluatingObject Object;
587  bool DidInsert;
588  EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
589  : EI(EI), Object(Object) {
590  DidInsert = EI.EvaluatingConstructors.insert(Object).second;
591  }
592  ~EvaluatingConstructorRAII() {
593  if (DidInsert) EI.EvaluatingConstructors.erase(Object);
594  }
595  };
596 
597  bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
598  return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
599  }
600 
601  /// The current array initialization index, if we're performing array
602  /// initialization.
603  uint64_t ArrayInitIndex = -1;
604 
605  /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
606  /// notes attached to it will also be stored, otherwise they will not be.
607  bool HasActiveDiagnostic;
608 
609  /// \brief Have we emitted a diagnostic explaining why we couldn't constant
610  /// fold (not just why it's not strictly a constant expression)?
611  bool HasFoldFailureDiagnostic;
612 
613  /// \brief Whether or not we're currently speculatively evaluating.
614  bool IsSpeculativelyEvaluating;
615 
616  enum EvaluationMode {
617  /// Evaluate as a constant expression. Stop if we find that the expression
618  /// is not a constant expression.
619  EM_ConstantExpression,
620 
621  /// Evaluate as a potential constant expression. Keep going if we hit a
622  /// construct that we can't evaluate yet (because we don't yet know the
623  /// value of something) but stop if we hit something that could never be
624  /// a constant expression.
625  EM_PotentialConstantExpression,
626 
627  /// Fold the expression to a constant. Stop if we hit a side-effect that
628  /// we can't model.
629  EM_ConstantFold,
630 
631  /// Evaluate the expression looking for integer overflow and similar
632  /// issues. Don't worry about side-effects, and try to visit all
633  /// subexpressions.
634  EM_EvaluateForOverflow,
635 
636  /// Evaluate in any way we know how. Don't worry about side-effects that
637  /// can't be modeled.
638  EM_IgnoreSideEffects,
639 
640  /// Evaluate as a constant expression. Stop if we find that the expression
641  /// is not a constant expression. Some expressions can be retried in the
642  /// optimizer if we don't constant fold them here, but in an unevaluated
643  /// context we try to fold them immediately since the optimizer never
644  /// gets a chance to look at it.
645  EM_ConstantExpressionUnevaluated,
646 
647  /// Evaluate as a potential constant expression. Keep going if we hit a
648  /// construct that we can't evaluate yet (because we don't yet know the
649  /// value of something) but stop if we hit something that could never be
650  /// a constant expression. Some expressions can be retried in the
651  /// optimizer if we don't constant fold them here, but in an unevaluated
652  /// context we try to fold them immediately since the optimizer never
653  /// gets a chance to look at it.
654  EM_PotentialConstantExpressionUnevaluated,
655 
656  /// Evaluate as a constant expression. In certain scenarios, if:
657  /// - we find a MemberExpr with a base that can't be evaluated, or
658  /// - we find a variable initialized with a call to a function that has
659  /// the alloc_size attribute on it
660  /// then we may consider evaluation to have succeeded.
661  ///
662  /// In either case, the LValue returned shall have an invalid base; in the
663  /// former, the base will be the invalid MemberExpr, in the latter, the
664  /// base will be either the alloc_size CallExpr or a CastExpr wrapping
665  /// said CallExpr.
666  EM_OffsetFold,
667  } EvalMode;
668 
669  /// Are we checking whether the expression is a potential constant
670  /// expression?
671  bool checkingPotentialConstantExpression() const {
672  return EvalMode == EM_PotentialConstantExpression ||
673  EvalMode == EM_PotentialConstantExpressionUnevaluated;
674  }
675 
676  /// Are we checking an expression for overflow?
677  // FIXME: We should check for any kind of undefined or suspicious behavior
678  // in such constructs, not just overflow.
679  bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
680 
681  EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
682  : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
683  CallStackDepth(0), NextCallIndex(1),
684  StepsLeft(getLangOpts().ConstexprStepLimit),
685  BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
686  EvaluatingDecl((const ValueDecl *)nullptr),
687  EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
688  HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
689  EvalMode(Mode) {}
690 
691  void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
692  EvaluatingDecl = Base;
693  EvaluatingDeclValue = &Value;
694  EvaluatingConstructors.insert({Base, 0});
695  }
696 
697  const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
698 
699  bool CheckCallLimit(SourceLocation Loc) {
700  // Don't perform any constexpr calls (other than the call we're checking)
701  // when checking a potential constant expression.
702  if (checkingPotentialConstantExpression() && CallStackDepth > 1)
703  return false;
704  if (NextCallIndex == 0) {
705  // NextCallIndex has wrapped around.
706  FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
707  return false;
708  }
709  if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
710  return true;
711  FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
712  << getLangOpts().ConstexprCallDepth;
713  return false;
714  }
715 
716  CallStackFrame *getCallFrame(unsigned CallIndex) {
717  assert(CallIndex && "no call index in getCallFrame");
718  // We will eventually hit BottomFrame, which has Index 1, so Frame can't
719  // be null in this loop.
720  CallStackFrame *Frame = CurrentCall;
721  while (Frame->Index > CallIndex)
722  Frame = Frame->Caller;
723  return (Frame->Index == CallIndex) ? Frame : nullptr;
724  }
725 
726  bool nextStep(const Stmt *S) {
727  if (!StepsLeft) {
728  FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
729  return false;
730  }
731  --StepsLeft;
732  return true;
733  }
734 
735  private:
736  /// Add a diagnostic to the diagnostics list.
737  PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
738  PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
739  EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
740  return EvalStatus.Diag->back().second;
741  }
742 
743  /// Add notes containing a call stack to the current point of evaluation.
744  void addCallStack(unsigned Limit);
745 
746  private:
747  OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
748  unsigned ExtraNotes, bool IsCCEDiag) {
749 
750  if (EvalStatus.Diag) {
751  // If we have a prior diagnostic, it will be noting that the expression
752  // isn't a constant expression. This diagnostic is more important,
753  // unless we require this evaluation to produce a constant expression.
754  //
755  // FIXME: We might want to show both diagnostics to the user in
756  // EM_ConstantFold mode.
757  if (!EvalStatus.Diag->empty()) {
758  switch (EvalMode) {
759  case EM_ConstantFold:
760  case EM_IgnoreSideEffects:
761  case EM_EvaluateForOverflow:
762  if (!HasFoldFailureDiagnostic)
763  break;
764  // We've already failed to fold something. Keep that diagnostic.
765  LLVM_FALLTHROUGH;
766  case EM_ConstantExpression:
767  case EM_PotentialConstantExpression:
768  case EM_ConstantExpressionUnevaluated:
769  case EM_PotentialConstantExpressionUnevaluated:
770  case EM_OffsetFold:
771  HasActiveDiagnostic = false;
772  return OptionalDiagnostic();
773  }
774  }
775 
776  unsigned CallStackNotes = CallStackDepth - 1;
777  unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
778  if (Limit)
779  CallStackNotes = std::min(CallStackNotes, Limit + 1);
780  if (checkingPotentialConstantExpression())
781  CallStackNotes = 0;
782 
783  HasActiveDiagnostic = true;
784  HasFoldFailureDiagnostic = !IsCCEDiag;
785  EvalStatus.Diag->clear();
786  EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
787  addDiag(Loc, DiagId);
788  if (!checkingPotentialConstantExpression())
789  addCallStack(Limit);
790  return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
791  }
792  HasActiveDiagnostic = false;
793  return OptionalDiagnostic();
794  }
795  public:
796  // Diagnose that the evaluation could not be folded (FF => FoldFailure)
797  OptionalDiagnostic
798  FFDiag(SourceLocation Loc,
799  diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
800  unsigned ExtraNotes = 0) {
801  return Diag(Loc, DiagId, ExtraNotes, false);
802  }
803 
804  OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
805  = diag::note_invalid_subexpr_in_const_expr,
806  unsigned ExtraNotes = 0) {
807  if (EvalStatus.Diag)
808  return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
809  HasActiveDiagnostic = false;
810  return OptionalDiagnostic();
811  }
812 
813  /// Diagnose that the evaluation does not produce a C++11 core constant
814  /// expression.
815  ///
816  /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
817  /// EM_PotentialConstantExpression mode and we produce one of these.
818  OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
819  = diag::note_invalid_subexpr_in_const_expr,
820  unsigned ExtraNotes = 0) {
821  // Don't override a previous diagnostic. Don't bother collecting
822  // diagnostics if we're evaluating for overflow.
823  if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
824  HasActiveDiagnostic = false;
825  return OptionalDiagnostic();
826  }
827  return Diag(Loc, DiagId, ExtraNotes, true);
828  }
829  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
830  = diag::note_invalid_subexpr_in_const_expr,
831  unsigned ExtraNotes = 0) {
832  return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
833  }
834  /// Add a note to a prior diagnostic.
835  OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
836  if (!HasActiveDiagnostic)
837  return OptionalDiagnostic();
838  return OptionalDiagnostic(&addDiag(Loc, DiagId));
839  }
840 
841  /// Add a stack of notes to a prior diagnostic.
842  void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
843  if (HasActiveDiagnostic) {
844  EvalStatus.Diag->insert(EvalStatus.Diag->end(),
845  Diags.begin(), Diags.end());
846  }
847  }
848 
849  /// Should we continue evaluation after encountering a side-effect that we
850  /// couldn't model?
851  bool keepEvaluatingAfterSideEffect() {
852  switch (EvalMode) {
853  case EM_PotentialConstantExpression:
854  case EM_PotentialConstantExpressionUnevaluated:
855  case EM_EvaluateForOverflow:
856  case EM_IgnoreSideEffects:
857  return true;
858 
859  case EM_ConstantExpression:
860  case EM_ConstantExpressionUnevaluated:
861  case EM_ConstantFold:
862  case EM_OffsetFold:
863  return false;
864  }
865  llvm_unreachable("Missed EvalMode case");
866  }
867 
868  /// Note that we have had a side-effect, and determine whether we should
869  /// keep evaluating.
870  bool noteSideEffect() {
871  EvalStatus.HasSideEffects = true;
872  return keepEvaluatingAfterSideEffect();
873  }
874 
875  /// Should we continue evaluation after encountering undefined behavior?
876  bool keepEvaluatingAfterUndefinedBehavior() {
877  switch (EvalMode) {
878  case EM_EvaluateForOverflow:
879  case EM_IgnoreSideEffects:
880  case EM_ConstantFold:
881  case EM_OffsetFold:
882  return true;
883 
884  case EM_PotentialConstantExpression:
885  case EM_PotentialConstantExpressionUnevaluated:
886  case EM_ConstantExpression:
887  case EM_ConstantExpressionUnevaluated:
888  return false;
889  }
890  llvm_unreachable("Missed EvalMode case");
891  }
892 
893  /// Note that we hit something that was technically undefined behavior, but
894  /// that we can evaluate past it (such as signed overflow or floating-point
895  /// division by zero.)
896  bool noteUndefinedBehavior() {
897  EvalStatus.HasUndefinedBehavior = true;
898  return keepEvaluatingAfterUndefinedBehavior();
899  }
900 
901  /// Should we continue evaluation as much as possible after encountering a
902  /// construct which can't be reduced to a value?
903  bool keepEvaluatingAfterFailure() {
904  if (!StepsLeft)
905  return false;
906 
907  switch (EvalMode) {
908  case EM_PotentialConstantExpression:
909  case EM_PotentialConstantExpressionUnevaluated:
910  case EM_EvaluateForOverflow:
911  return true;
912 
913  case EM_ConstantExpression:
914  case EM_ConstantExpressionUnevaluated:
915  case EM_ConstantFold:
916  case EM_IgnoreSideEffects:
917  case EM_OffsetFold:
918  return false;
919  }
920  llvm_unreachable("Missed EvalMode case");
921  }
922 
923  /// Notes that we failed to evaluate an expression that other expressions
924  /// directly depend on, and determine if we should keep evaluating. This
925  /// should only be called if we actually intend to keep evaluating.
926  ///
927  /// Call noteSideEffect() instead if we may be able to ignore the value that
928  /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
929  ///
930  /// (Foo(), 1) // use noteSideEffect
931  /// (Foo() || true) // use noteSideEffect
932  /// Foo() + 1 // use noteFailure
933  LLVM_NODISCARD bool noteFailure() {
934  // Failure when evaluating some expression often means there is some
935  // subexpression whose evaluation was skipped. Therefore, (because we
936  // don't track whether we skipped an expression when unwinding after an
937  // evaluation failure) every evaluation failure that bubbles up from a
938  // subexpression implies that a side-effect has potentially happened. We
939  // skip setting the HasSideEffects flag to true until we decide to
940  // continue evaluating after that point, which happens here.
941  bool KeepGoing = keepEvaluatingAfterFailure();
942  EvalStatus.HasSideEffects |= KeepGoing;
943  return KeepGoing;
944  }
945 
946  class ArrayInitLoopIndex {
947  EvalInfo &Info;
948  uint64_t OuterIndex;
949 
950  public:
951  ArrayInitLoopIndex(EvalInfo &Info)
952  : Info(Info), OuterIndex(Info.ArrayInitIndex) {
953  Info.ArrayInitIndex = 0;
954  }
955  ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
956 
957  operator uint64_t&() { return Info.ArrayInitIndex; }
958  };
959  };
960 
961  /// Object used to treat all foldable expressions as constant expressions.
962  struct FoldConstant {
963  EvalInfo &Info;
964  bool Enabled;
965  bool HadNoPriorDiags;
966  EvalInfo::EvaluationMode OldMode;
967 
968  explicit FoldConstant(EvalInfo &Info, bool Enabled)
969  : Info(Info),
970  Enabled(Enabled),
971  HadNoPriorDiags(Info.EvalStatus.Diag &&
972  Info.EvalStatus.Diag->empty() &&
973  !Info.EvalStatus.HasSideEffects),
974  OldMode(Info.EvalMode) {
975  if (Enabled &&
976  (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
977  Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
978  Info.EvalMode = EvalInfo::EM_ConstantFold;
979  }
980  void keepDiagnostics() { Enabled = false; }
981  ~FoldConstant() {
982  if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
983  !Info.EvalStatus.HasSideEffects)
984  Info.EvalStatus.Diag->clear();
985  Info.EvalMode = OldMode;
986  }
987  };
988 
989  /// RAII object used to treat the current evaluation as the correct pointer
990  /// offset fold for the current EvalMode
991  struct FoldOffsetRAII {
992  EvalInfo &Info;
993  EvalInfo::EvaluationMode OldMode;
994  explicit FoldOffsetRAII(EvalInfo &Info)
995  : Info(Info), OldMode(Info.EvalMode) {
996  if (!Info.checkingPotentialConstantExpression())
997  Info.EvalMode = EvalInfo::EM_OffsetFold;
998  }
999 
1000  ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1001  };
1002 
1003  /// RAII object used to optionally suppress diagnostics and side-effects from
1004  /// a speculative evaluation.
1005  class SpeculativeEvaluationRAII {
1006  EvalInfo *Info = nullptr;
1007  Expr::EvalStatus OldStatus;
1008  bool OldIsSpeculativelyEvaluating;
1009 
1010  void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1011  Info = Other.Info;
1012  OldStatus = Other.OldStatus;
1013  OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1014  Other.Info = nullptr;
1015  }
1016 
1017  void maybeRestoreState() {
1018  if (!Info)
1019  return;
1020 
1021  Info->EvalStatus = OldStatus;
1022  Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1023  }
1024 
1025  public:
1026  SpeculativeEvaluationRAII() = default;
1027 
1028  SpeculativeEvaluationRAII(
1029  EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1030  : Info(&Info), OldStatus(Info.EvalStatus),
1031  OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1032  Info.EvalStatus.Diag = NewDiag;
1033  Info.IsSpeculativelyEvaluating = true;
1034  }
1035 
1036  SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1037  SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1038  moveFromAndCancel(std::move(Other));
1039  }
1040 
1041  SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1042  maybeRestoreState();
1043  moveFromAndCancel(std::move(Other));
1044  return *this;
1045  }
1046 
1047  ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1048  };
1049 
1050  /// RAII object wrapping a full-expression or block scope, and handling
1051  /// the ending of the lifetime of temporaries created within it.
1052  template<bool IsFullExpression>
1053  class ScopeRAII {
1054  EvalInfo &Info;
1055  unsigned OldStackSize;
1056  public:
1057  ScopeRAII(EvalInfo &Info)
1058  : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1059  ~ScopeRAII() {
1060  // Body moved to a static method to encourage the compiler to inline away
1061  // instances of this class.
1062  cleanup(Info, OldStackSize);
1063  }
1064  private:
1065  static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1066  unsigned NewEnd = OldStackSize;
1067  for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1068  I != N; ++I) {
1069  if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1070  // Full-expression cleanup of a lifetime-extended temporary: nothing
1071  // to do, just move this cleanup to the right place in the stack.
1072  std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1073  ++NewEnd;
1074  } else {
1075  // End the lifetime of the object.
1076  Info.CleanupStack[I].endLifetime();
1077  }
1078  }
1079  Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1080  Info.CleanupStack.end());
1081  }
1082  };
1083  typedef ScopeRAII<false> BlockScopeRAII;
1084  typedef ScopeRAII<true> FullExpressionRAII;
1085 }
1086 
1087 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1088  CheckSubobjectKind CSK) {
1089  if (Invalid)
1090  return false;
1091  if (isOnePastTheEnd()) {
1092  Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1093  << CSK;
1094  setInvalid();
1095  return false;
1096  }
1097  return true;
1098 }
1099 
1100 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1101  const Expr *E,
1102  const APSInt &N) {
1103  // If we're complaining, we must be able to statically determine the size of
1104  // the most derived array.
1105  if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1106  Info.CCEDiag(E, diag::note_constexpr_array_index)
1107  << N << /*array*/ 0
1108  << static_cast<unsigned>(getMostDerivedArraySize());
1109  else
1110  Info.CCEDiag(E, diag::note_constexpr_array_index)
1111  << N << /*non-array*/ 1;
1112  setInvalid();
1113 }
1114 
1115 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1116  const FunctionDecl *Callee, const LValue *This,
1117  APValue *Arguments)
1118  : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1119  Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1120  Info.CurrentCall = this;
1121  ++Info.CallStackDepth;
1122 }
1123 
1124 CallStackFrame::~CallStackFrame() {
1125  assert(Info.CurrentCall == this && "calls retired out of order");
1126  --Info.CallStackDepth;
1127  Info.CurrentCall = Caller;
1128 }
1129 
1130 APValue &CallStackFrame::createTemporary(const void *Key,
1131  bool IsLifetimeExtended) {
1132  APValue &Result = Temporaries[Key];
1133  assert(Result.isUninit() && "temporary created multiple times");
1134  Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1135  return Result;
1136 }
1137 
1138 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1139 
1140 void EvalInfo::addCallStack(unsigned Limit) {
1141  // Determine which calls to skip, if any.
1142  unsigned ActiveCalls = CallStackDepth - 1;
1143  unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1144  if (Limit && Limit < ActiveCalls) {
1145  SkipStart = Limit / 2 + Limit % 2;
1146  SkipEnd = ActiveCalls - Limit / 2;
1147  }
1148 
1149  // Walk the call stack and add the diagnostics.
1150  unsigned CallIdx = 0;
1151  for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1152  Frame = Frame->Caller, ++CallIdx) {
1153  // Skip this call?
1154  if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1155  if (CallIdx == SkipStart) {
1156  // Note that we're skipping calls.
1157  addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1158  << unsigned(ActiveCalls - Limit);
1159  }
1160  continue;
1161  }
1162 
1163  // Use a different note for an inheriting constructor, because from the
1164  // user's perspective it's not really a function at all.
1165  if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1166  if (CD->isInheritingConstructor()) {
1167  addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1168  << CD->getParent();
1169  continue;
1170  }
1171  }
1172 
1173  SmallVector<char, 128> Buffer;
1174  llvm::raw_svector_ostream Out(Buffer);
1175  describeCall(Frame, Out);
1176  addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1177  }
1178 }
1179 
1180 namespace {
1181  struct ComplexValue {
1182  private:
1183  bool IsInt;
1184 
1185  public:
1186  APSInt IntReal, IntImag;
1187  APFloat FloatReal, FloatImag;
1188 
1189  ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1190 
1191  void makeComplexFloat() { IsInt = false; }
1192  bool isComplexFloat() const { return !IsInt; }
1193  APFloat &getComplexFloatReal() { return FloatReal; }
1194  APFloat &getComplexFloatImag() { return FloatImag; }
1195 
1196  void makeComplexInt() { IsInt = true; }
1197  bool isComplexInt() const { return IsInt; }
1198  APSInt &getComplexIntReal() { return IntReal; }
1199  APSInt &getComplexIntImag() { return IntImag; }
1200 
1201  void moveInto(APValue &v) const {
1202  if (isComplexFloat())
1203  v = APValue(FloatReal, FloatImag);
1204  else
1205  v = APValue(IntReal, IntImag);
1206  }
1207  void setFrom(const APValue &v) {
1208  assert(v.isComplexFloat() || v.isComplexInt());
1209  if (v.isComplexFloat()) {
1210  makeComplexFloat();
1211  FloatReal = v.getComplexFloatReal();
1212  FloatImag = v.getComplexFloatImag();
1213  } else {
1214  makeComplexInt();
1215  IntReal = v.getComplexIntReal();
1216  IntImag = v.getComplexIntImag();
1217  }
1218  }
1219  };
1220 
1221  struct LValue {
1222  APValue::LValueBase Base;
1223  CharUnits Offset;
1224  unsigned InvalidBase : 1;
1225  unsigned CallIndex : 31;
1226  SubobjectDesignator Designator;
1227  bool IsNullPtr;
1228 
1229  const APValue::LValueBase getLValueBase() const { return Base; }
1230  CharUnits &getLValueOffset() { return Offset; }
1231  const CharUnits &getLValueOffset() const { return Offset; }
1232  unsigned getLValueCallIndex() const { return CallIndex; }
1233  SubobjectDesignator &getLValueDesignator() { return Designator; }
1234  const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1235  bool isNullPointer() const { return IsNullPtr;}
1236 
1237  void moveInto(APValue &V) const {
1238  if (Designator.Invalid)
1239  V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1240  IsNullPtr);
1241  else {
1242  assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1243  assert(!Designator.FirstEntryIsAnUnsizedArray &&
1244  "Unsized array with a valid base?");
1245  V = APValue(Base, Offset, Designator.Entries,
1246  Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1247  }
1248  }
1249  void setFrom(ASTContext &Ctx, const APValue &V) {
1250  assert(V.isLValue() && "Setting LValue from a non-LValue?");
1251  Base = V.getLValueBase();
1252  Offset = V.getLValueOffset();
1253  InvalidBase = false;
1254  CallIndex = V.getLValueCallIndex();
1255  Designator = SubobjectDesignator(Ctx, V);
1256  IsNullPtr = V.isNullPointer();
1257  }
1258 
1259  void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1260 #ifndef NDEBUG
1261  // We only allow a few types of invalid bases. Enforce that here.
1262  if (BInvalid) {
1263  const auto *E = B.get<const Expr *>();
1264  assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1265  "Unexpected type of invalid base");
1266  }
1267 #endif
1268 
1269  Base = B;
1270  Offset = CharUnits::fromQuantity(0);
1271  InvalidBase = BInvalid;
1272  CallIndex = I;
1273  Designator = SubobjectDesignator(getType(B));
1274  IsNullPtr = false;
1275  }
1276 
1277  void setNull(QualType PointerTy, uint64_t TargetVal) {
1278  Base = (Expr *)nullptr;
1279  Offset = CharUnits::fromQuantity(TargetVal);
1280  InvalidBase = false;
1281  CallIndex = 0;
1282  Designator = SubobjectDesignator(PointerTy->getPointeeType());
1283  IsNullPtr = true;
1284  }
1285 
1286  void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1287  set(B, I, true);
1288  }
1289 
1290  // Check that this LValue is not based on a null pointer. If it is, produce
1291  // a diagnostic and mark the designator as invalid.
1292  bool checkNullPointer(EvalInfo &Info, const Expr *E,
1293  CheckSubobjectKind CSK) {
1294  if (Designator.Invalid)
1295  return false;
1296  if (IsNullPtr) {
1297  Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1298  << CSK;
1299  Designator.setInvalid();
1300  return false;
1301  }
1302  return true;
1303  }
1304 
1305  // Check this LValue refers to an object. If not, set the designator to be
1306  // invalid and emit a diagnostic.
1307  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1308  return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1309  Designator.checkSubobject(Info, E, CSK);
1310  }
1311 
1312  void addDecl(EvalInfo &Info, const Expr *E,
1313  const Decl *D, bool Virtual = false) {
1314  if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1315  Designator.addDeclUnchecked(D, Virtual);
1316  }
1317  void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1318  assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1319  assert(isBaseAnAllocSizeCall(Base) &&
1320  "Only alloc_size bases can have unsized arrays");
1321  Designator.FirstEntryIsAnUnsizedArray = true;
1322  Designator.addUnsizedArrayUnchecked(ElemTy);
1323  }
1324  void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1325  if (checkSubobject(Info, E, CSK_ArrayToPointer))
1326  Designator.addArrayUnchecked(CAT);
1327  }
1328  void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1329  if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1330  Designator.addComplexUnchecked(EltTy, Imag);
1331  }
1332  void clearIsNullPointer() {
1333  IsNullPtr = false;
1334  }
1335  void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1336  const APSInt &Index, CharUnits ElementSize) {
1337  // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1338  // but we're not required to diagnose it and it's valid in C++.)
1339  if (!Index)
1340  return;
1341 
1342  // Compute the new offset in the appropriate width, wrapping at 64 bits.
1343  // FIXME: When compiling for a 32-bit target, we should use 32-bit
1344  // offsets.
1345  uint64_t Offset64 = Offset.getQuantity();
1346  uint64_t ElemSize64 = ElementSize.getQuantity();
1347  uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1348  Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1349 
1350  if (checkNullPointer(Info, E, CSK_ArrayIndex))
1351  Designator.adjustIndex(Info, E, Index);
1352  clearIsNullPointer();
1353  }
1354  void adjustOffset(CharUnits N) {
1355  Offset += N;
1356  if (N.getQuantity())
1357  clearIsNullPointer();
1358  }
1359  };
1360 
1361  struct MemberPtr {
1362  MemberPtr() {}
1363  explicit MemberPtr(const ValueDecl *Decl) :
1364  DeclAndIsDerivedMember(Decl, false), Path() {}
1365 
1366  /// The member or (direct or indirect) field referred to by this member
1367  /// pointer, or 0 if this is a null member pointer.
1368  const ValueDecl *getDecl() const {
1369  return DeclAndIsDerivedMember.getPointer();
1370  }
1371  /// Is this actually a member of some type derived from the relevant class?
1372  bool isDerivedMember() const {
1373  return DeclAndIsDerivedMember.getInt();
1374  }
1375  /// Get the class which the declaration actually lives in.
1376  const CXXRecordDecl *getContainingRecord() const {
1377  return cast<CXXRecordDecl>(
1378  DeclAndIsDerivedMember.getPointer()->getDeclContext());
1379  }
1380 
1381  void moveInto(APValue &V) const {
1382  V = APValue(getDecl(), isDerivedMember(), Path);
1383  }
1384  void setFrom(const APValue &V) {
1385  assert(V.isMemberPointer());
1386  DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1387  DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1388  Path.clear();
1390  Path.insert(Path.end(), P.begin(), P.end());
1391  }
1392 
1393  /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1394  /// whether the member is a member of some class derived from the class type
1395  /// of the member pointer.
1396  llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1397  /// Path - The path of base/derived classes from the member declaration's
1398  /// class (exclusive) to the class type of the member pointer (inclusive).
1400 
1401  /// Perform a cast towards the class of the Decl (either up or down the
1402  /// hierarchy).
1403  bool castBack(const CXXRecordDecl *Class) {
1404  assert(!Path.empty());
1405  const CXXRecordDecl *Expected;
1406  if (Path.size() >= 2)
1407  Expected = Path[Path.size() - 2];
1408  else
1409  Expected = getContainingRecord();
1410  if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1411  // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1412  // if B does not contain the original member and is not a base or
1413  // derived class of the class containing the original member, the result
1414  // of the cast is undefined.
1415  // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1416  // (D::*). We consider that to be a language defect.
1417  return false;
1418  }
1419  Path.pop_back();
1420  return true;
1421  }
1422  /// Perform a base-to-derived member pointer cast.
1423  bool castToDerived(const CXXRecordDecl *Derived) {
1424  if (!getDecl())
1425  return true;
1426  if (!isDerivedMember()) {
1427  Path.push_back(Derived);
1428  return true;
1429  }
1430  if (!castBack(Derived))
1431  return false;
1432  if (Path.empty())
1433  DeclAndIsDerivedMember.setInt(false);
1434  return true;
1435  }
1436  /// Perform a derived-to-base member pointer cast.
1437  bool castToBase(const CXXRecordDecl *Base) {
1438  if (!getDecl())
1439  return true;
1440  if (Path.empty())
1441  DeclAndIsDerivedMember.setInt(true);
1442  if (isDerivedMember()) {
1443  Path.push_back(Base);
1444  return true;
1445  }
1446  return castBack(Base);
1447  }
1448  };
1449 
1450  /// Compare two member pointers, which are assumed to be of the same type.
1451  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1452  if (!LHS.getDecl() || !RHS.getDecl())
1453  return !LHS.getDecl() && !RHS.getDecl();
1454  if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1455  return false;
1456  return LHS.Path == RHS.Path;
1457  }
1458 }
1459 
1460 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1461 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1462  const LValue &This, const Expr *E,
1463  bool AllowNonLiteralTypes = false);
1464 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1465  bool InvalidBaseOK = false);
1466 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1467  bool InvalidBaseOK = false);
1468 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1469  EvalInfo &Info);
1470 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1471 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1472 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1473  EvalInfo &Info);
1474 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1475 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1476 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1477  EvalInfo &Info);
1478 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1479 
1480 //===----------------------------------------------------------------------===//
1481 // Misc utilities
1482 //===----------------------------------------------------------------------===//
1483 
1484 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1485 /// preserving its value (by extending by up to one bit as needed).
1486 static void negateAsSigned(APSInt &Int) {
1487  if (Int.isUnsigned() || Int.isMinSignedValue()) {
1488  Int = Int.extend(Int.getBitWidth() + 1);
1489  Int.setIsSigned(true);
1490  }
1491  Int = -Int;
1492 }
1493 
1494 /// Produce a string describing the given constexpr call.
1495 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1496  unsigned ArgIndex = 0;
1497  bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1498  !isa<CXXConstructorDecl>(Frame->Callee) &&
1499  cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1500 
1501  if (!IsMemberCall)
1502  Out << *Frame->Callee << '(';
1503 
1504  if (Frame->This && IsMemberCall) {
1505  APValue Val;
1506  Frame->This->moveInto(Val);
1507  Val.printPretty(Out, Frame->Info.Ctx,
1508  Frame->This->Designator.MostDerivedType);
1509  // FIXME: Add parens around Val if needed.
1510  Out << "->" << *Frame->Callee << '(';
1511  IsMemberCall = false;
1512  }
1513 
1514  for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1515  E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1516  if (ArgIndex > (unsigned)IsMemberCall)
1517  Out << ", ";
1518 
1519  const ParmVarDecl *Param = *I;
1520  const APValue &Arg = Frame->Arguments[ArgIndex];
1521  Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1522 
1523  if (ArgIndex == 0 && IsMemberCall)
1524  Out << "->" << *Frame->Callee << '(';
1525  }
1526 
1527  Out << ')';
1528 }
1529 
1530 /// Evaluate an expression to see if it had side-effects, and discard its
1531 /// result.
1532 /// \return \c true if the caller should keep evaluating.
1533 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1534  APValue Scratch;
1535  if (!Evaluate(Scratch, Info, E))
1536  // We don't need the value, but we might have skipped a side effect here.
1537  return Info.noteSideEffect();
1538  return true;
1539 }
1540 
1541 /// Should this call expression be treated as a string literal?
1542 static bool IsStringLiteralCall(const CallExpr *E) {
1543  unsigned Builtin = E->getBuiltinCallee();
1544  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1545  Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1546 }
1547 
1549  // C++11 [expr.const]p3 An address constant expression is a prvalue core
1550  // constant expression of pointer type that evaluates to...
1551 
1552  // ... a null pointer value, or a prvalue core constant expression of type
1553  // std::nullptr_t.
1554  if (!B) return true;
1555 
1556  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1557  // ... the address of an object with static storage duration,
1558  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1559  return VD->hasGlobalStorage();
1560  // ... the address of a function,
1561  return isa<FunctionDecl>(D);
1562  }
1563 
1564  const Expr *E = B.get<const Expr*>();
1565  switch (E->getStmtClass()) {
1566  default:
1567  return false;
1568  case Expr::CompoundLiteralExprClass: {
1569  const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1570  return CLE->isFileScope() && CLE->isLValue();
1571  }
1572  case Expr::MaterializeTemporaryExprClass:
1573  // A materialized temporary might have been lifetime-extended to static
1574  // storage duration.
1575  return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1576  // A string literal has static storage duration.
1577  case Expr::StringLiteralClass:
1578  case Expr::PredefinedExprClass:
1579  case Expr::ObjCStringLiteralClass:
1580  case Expr::ObjCEncodeExprClass:
1581  case Expr::CXXTypeidExprClass:
1582  case Expr::CXXUuidofExprClass:
1583  return true;
1584  case Expr::CallExprClass:
1585  return IsStringLiteralCall(cast<CallExpr>(E));
1586  // For GCC compatibility, &&label has static storage duration.
1587  case Expr::AddrLabelExprClass:
1588  return true;
1589  // A Block literal expression may be used as the initialization value for
1590  // Block variables at global or local static scope.
1591  case Expr::BlockExprClass:
1592  return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1593  case Expr::ImplicitValueInitExprClass:
1594  // FIXME:
1595  // We can never form an lvalue with an implicit value initialization as its
1596  // base through expression evaluation, so these only appear in one case: the
1597  // implicit variable declaration we invent when checking whether a constexpr
1598  // constructor can produce a constant expression. We must assume that such
1599  // an expression might be a global lvalue.
1600  return true;
1601  }
1602 }
1603 
1604 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1605  assert(Base && "no location for a null lvalue");
1606  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1607  if (VD)
1608  Info.Note(VD->getLocation(), diag::note_declared_at);
1609  else
1610  Info.Note(Base.get<const Expr*>()->getExprLoc(),
1611  diag::note_constexpr_temporary_here);
1612 }
1613 
1614 /// Check that this reference or pointer core constant expression is a valid
1615 /// value for an address or reference constant expression. Return true if we
1616 /// can fold this expression, whether or not it's a constant expression.
1617 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1618  QualType Type, const LValue &LVal) {
1619  bool IsReferenceType = Type->isReferenceType();
1620 
1621  APValue::LValueBase Base = LVal.getLValueBase();
1622  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1623 
1624  // Check that the object is a global. Note that the fake 'this' object we
1625  // manufacture when checking potential constant expressions is conservatively
1626  // assumed to be global here.
1627  if (!IsGlobalLValue(Base)) {
1628  if (Info.getLangOpts().CPlusPlus11) {
1629  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1630  Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1631  << IsReferenceType << !Designator.Entries.empty()
1632  << !!VD << VD;
1633  NoteLValueLocation(Info, Base);
1634  } else {
1635  Info.FFDiag(Loc);
1636  }
1637  // Don't allow references to temporaries to escape.
1638  return false;
1639  }
1640  assert((Info.checkingPotentialConstantExpression() ||
1641  LVal.getLValueCallIndex() == 0) &&
1642  "have call index for global lvalue");
1643 
1644  if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1645  if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1646  // Check if this is a thread-local variable.
1647  if (Var->getTLSKind())
1648  return false;
1649 
1650  // A dllimport variable never acts like a constant.
1651  if (Var->hasAttr<DLLImportAttr>())
1652  return false;
1653  }
1654  if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1655  // __declspec(dllimport) must be handled very carefully:
1656  // We must never initialize an expression with the thunk in C++.
1657  // Doing otherwise would allow the same id-expression to yield
1658  // different addresses for the same function in different translation
1659  // units. However, this means that we must dynamically initialize the
1660  // expression with the contents of the import address table at runtime.
1661  //
1662  // The C language has no notion of ODR; furthermore, it has no notion of
1663  // dynamic initialization. This means that we are permitted to
1664  // perform initialization with the address of the thunk.
1665  if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1666  return false;
1667  }
1668  }
1669 
1670  // Allow address constant expressions to be past-the-end pointers. This is
1671  // an extension: the standard requires them to point to an object.
1672  if (!IsReferenceType)
1673  return true;
1674 
1675  // A reference constant expression must refer to an object.
1676  if (!Base) {
1677  // FIXME: diagnostic
1678  Info.CCEDiag(Loc);
1679  return true;
1680  }
1681 
1682  // Does this refer one past the end of some object?
1683  if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1684  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1685  Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1686  << !Designator.Entries.empty() << !!VD << VD;
1687  NoteLValueLocation(Info, Base);
1688  }
1689 
1690  return true;
1691 }
1692 
1693 /// Member pointers are constant expressions unless they point to a
1694 /// non-virtual dllimport member function.
1695 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1696  SourceLocation Loc,
1697  QualType Type,
1698  const APValue &Value) {
1699  const ValueDecl *Member = Value.getMemberPointerDecl();
1700  const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1701  if (!FD)
1702  return true;
1703  return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1704 }
1705 
1706 /// Check that this core constant expression is of literal type, and if not,
1707 /// produce an appropriate diagnostic.
1708 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1709  const LValue *This = nullptr) {
1710  if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1711  return true;
1712 
1713  // C++1y: A constant initializer for an object o [...] may also invoke
1714  // constexpr constructors for o and its subobjects even if those objects
1715  // are of non-literal class types.
1716  //
1717  // C++11 missed this detail for aggregates, so classes like this:
1718  // struct foo_t { union { int i; volatile int j; } u; };
1719  // are not (obviously) initializable like so:
1720  // __attribute__((__require_constant_initialization__))
1721  // static const foo_t x = {{0}};
1722  // because "i" is a subobject with non-literal initialization (due to the
1723  // volatile member of the union). See:
1724  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1725  // Therefore, we use the C++1y behavior.
1726  if (This && Info.EvaluatingDecl == This->getLValueBase())
1727  return true;
1728 
1729  // Prvalue constant expressions must be of literal types.
1730  if (Info.getLangOpts().CPlusPlus11)
1731  Info.FFDiag(E, diag::note_constexpr_nonliteral)
1732  << E->getType();
1733  else
1734  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1735  return false;
1736 }
1737 
1738 /// Check that this core constant expression value is a valid value for a
1739 /// constant expression. If not, report an appropriate diagnostic. Does not
1740 /// check that the expression is of literal type.
1741 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1742  QualType Type, const APValue &Value) {
1743  if (Value.isUninit()) {
1744  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1745  << true << Type;
1746  return false;
1747  }
1748 
1749  // We allow _Atomic(T) to be initialized from anything that T can be
1750  // initialized from.
1751  if (const AtomicType *AT = Type->getAs<AtomicType>())
1752  Type = AT->getValueType();
1753 
1754  // Core issue 1454: For a literal constant expression of array or class type,
1755  // each subobject of its value shall have been initialized by a constant
1756  // expression.
1757  if (Value.isArray()) {
1758  QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1759  for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1760  if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1761  Value.getArrayInitializedElt(I)))
1762  return false;
1763  }
1764  if (!Value.hasArrayFiller())
1765  return true;
1766  return CheckConstantExpression(Info, DiagLoc, EltTy,
1767  Value.getArrayFiller());
1768  }
1769  if (Value.isUnion() && Value.getUnionField()) {
1770  return CheckConstantExpression(Info, DiagLoc,
1771  Value.getUnionField()->getType(),
1772  Value.getUnionValue());
1773  }
1774  if (Value.isStruct()) {
1775  RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1776  if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1777  unsigned BaseIndex = 0;
1778  for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1779  End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1780  if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1781  Value.getStructBase(BaseIndex)))
1782  return false;
1783  }
1784  }
1785  for (const auto *I : RD->fields()) {
1786  if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1787  Value.getStructField(I->getFieldIndex())))
1788  return false;
1789  }
1790  }
1791 
1792  if (Value.isLValue()) {
1793  LValue LVal;
1794  LVal.setFrom(Info.Ctx, Value);
1795  return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1796  }
1797 
1798  if (Value.isMemberPointer())
1799  return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1800 
1801  // Everything else is fine.
1802  return true;
1803 }
1804 
1805 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1806  return LVal.Base.dyn_cast<const ValueDecl*>();
1807 }
1808 
1809 static bool IsLiteralLValue(const LValue &Value) {
1810  if (Value.CallIndex)
1811  return false;
1812  const Expr *E = Value.Base.dyn_cast<const Expr*>();
1813  return E && !isa<MaterializeTemporaryExpr>(E);
1814 }
1815 
1816 static bool IsWeakLValue(const LValue &Value) {
1817  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1818  return Decl && Decl->isWeak();
1819 }
1820 
1821 static bool isZeroSized(const LValue &Value) {
1822  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1823  if (Decl && isa<VarDecl>(Decl)) {
1824  QualType Ty = Decl->getType();
1825  if (Ty->isArrayType())
1826  return Ty->isIncompleteType() ||
1827  Decl->getASTContext().getTypeSize(Ty) == 0;
1828  }
1829  return false;
1830 }
1831 
1832 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1833  // A null base expression indicates a null pointer. These are always
1834  // evaluatable, and they are false unless the offset is zero.
1835  if (!Value.getLValueBase()) {
1836  Result = !Value.getLValueOffset().isZero();
1837  return true;
1838  }
1839 
1840  // We have a non-null base. These are generally known to be true, but if it's
1841  // a weak declaration it can be null at runtime.
1842  Result = true;
1843  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1844  return !Decl || !Decl->isWeak();
1845 }
1846 
1847 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1848  switch (Val.getKind()) {
1850  return false;
1851  case APValue::Int:
1852  Result = Val.getInt().getBoolValue();
1853  return true;
1854  case APValue::Float:
1855  Result = !Val.getFloat().isZero();
1856  return true;
1857  case APValue::ComplexInt:
1858  Result = Val.getComplexIntReal().getBoolValue() ||
1859  Val.getComplexIntImag().getBoolValue();
1860  return true;
1861  case APValue::ComplexFloat:
1862  Result = !Val.getComplexFloatReal().isZero() ||
1863  !Val.getComplexFloatImag().isZero();
1864  return true;
1865  case APValue::LValue:
1866  return EvalPointerValueAsBool(Val, Result);
1868  Result = Val.getMemberPointerDecl();
1869  return true;
1870  case APValue::Vector:
1871  case APValue::Array:
1872  case APValue::Struct:
1873  case APValue::Union:
1875  return false;
1876  }
1877 
1878  llvm_unreachable("unknown APValue kind");
1879 }
1880 
1881 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1882  EvalInfo &Info) {
1883  assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1884  APValue Val;
1885  if (!Evaluate(Val, Info, E))
1886  return false;
1887  return HandleConversionToBool(Val, Result);
1888 }
1889 
1890 template<typename T>
1891 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1892  const T &SrcValue, QualType DestType) {
1893  Info.CCEDiag(E, diag::note_constexpr_overflow)
1894  << SrcValue << DestType;
1895  return Info.noteUndefinedBehavior();
1896 }
1897 
1898 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1899  QualType SrcType, const APFloat &Value,
1900  QualType DestType, APSInt &Result) {
1901  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1902  // Determine whether we are converting to unsigned or signed.
1903  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1904 
1905  Result = APSInt(DestWidth, !DestSigned);
1906  bool ignored;
1907  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1908  & APFloat::opInvalidOp)
1909  return HandleOverflow(Info, E, Value, DestType);
1910  return true;
1911 }
1912 
1913 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1914  QualType SrcType, QualType DestType,
1915  APFloat &Result) {
1916  APFloat Value = Result;
1917  bool ignored;
1918  if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1919  APFloat::rmNearestTiesToEven, &ignored)
1920  & APFloat::opOverflow)
1921  return HandleOverflow(Info, E, Value, DestType);
1922  return true;
1923 }
1924 
1925 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1926  QualType DestType, QualType SrcType,
1927  const APSInt &Value) {
1928  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1929  APSInt Result = Value;
1930  // Figure out if this is a truncate, extend or noop cast.
1931  // If the input is signed, do a sign extend, noop, or truncate.
1932  Result = Result.extOrTrunc(DestWidth);
1933  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1934  return Result;
1935 }
1936 
1937 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1938  QualType SrcType, const APSInt &Value,
1939  QualType DestType, APFloat &Result) {
1940  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1941  if (Result.convertFromAPInt(Value, Value.isSigned(),
1942  APFloat::rmNearestTiesToEven)
1943  & APFloat::opOverflow)
1944  return HandleOverflow(Info, E, Value, DestType);
1945  return true;
1946 }
1947 
1948 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1949  APValue &Value, const FieldDecl *FD) {
1950  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1951 
1952  if (!Value.isInt()) {
1953  // Trying to store a pointer-cast-to-integer into a bitfield.
1954  // FIXME: In this case, we should provide the diagnostic for casting
1955  // a pointer to an integer.
1956  assert(Value.isLValue() && "integral value neither int nor lvalue?");
1957  Info.FFDiag(E);
1958  return false;
1959  }
1960 
1961  APSInt &Int = Value.getInt();
1962  unsigned OldBitWidth = Int.getBitWidth();
1963  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1964  if (NewBitWidth < OldBitWidth)
1965  Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1966  return true;
1967 }
1968 
1969 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1970  llvm::APInt &Res) {
1971  APValue SVal;
1972  if (!Evaluate(SVal, Info, E))
1973  return false;
1974  if (SVal.isInt()) {
1975  Res = SVal.getInt();
1976  return true;
1977  }
1978  if (SVal.isFloat()) {
1979  Res = SVal.getFloat().bitcastToAPInt();
1980  return true;
1981  }
1982  if (SVal.isVector()) {
1983  QualType VecTy = E->getType();
1984  unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1985  QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1986  unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1987  bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1988  Res = llvm::APInt::getNullValue(VecSize);
1989  for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1990  APValue &Elt = SVal.getVectorElt(i);
1991  llvm::APInt EltAsInt;
1992  if (Elt.isInt()) {
1993  EltAsInt = Elt.getInt();
1994  } else if (Elt.isFloat()) {
1995  EltAsInt = Elt.getFloat().bitcastToAPInt();
1996  } else {
1997  // Don't try to handle vectors of anything other than int or float
1998  // (not sure if it's possible to hit this case).
1999  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2000  return false;
2001  }
2002  unsigned BaseEltSize = EltAsInt.getBitWidth();
2003  if (BigEndian)
2004  Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2005  else
2006  Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2007  }
2008  return true;
2009  }
2010  // Give up if the input isn't an int, float, or vector. For example, we
2011  // reject "(v4i16)(intptr_t)&a".
2012  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2013  return false;
2014 }
2015 
2016 /// Perform the given integer operation, which is known to need at most BitWidth
2017 /// bits, and check for overflow in the original type (if that type was not an
2018 /// unsigned type).
2019 template<typename Operation>
2020 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2021  const APSInt &LHS, const APSInt &RHS,
2022  unsigned BitWidth, Operation Op,
2023  APSInt &Result) {
2024  if (LHS.isUnsigned()) {
2025  Result = Op(LHS, RHS);
2026  return true;
2027  }
2028 
2029  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2030  Result = Value.trunc(LHS.getBitWidth());
2031  if (Result.extend(BitWidth) != Value) {
2032  if (Info.checkingForOverflow())
2033  Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2034  diag::warn_integer_constant_overflow)
2035  << Result.toString(10) << E->getType();
2036  else
2037  return HandleOverflow(Info, E, Value, E->getType());
2038  }
2039  return true;
2040 }
2041 
2042 /// Perform the given binary integer operation.
2043 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2044  BinaryOperatorKind Opcode, APSInt RHS,
2045  APSInt &Result) {
2046  switch (Opcode) {
2047  default:
2048  Info.FFDiag(E);
2049  return false;
2050  case BO_Mul:
2051  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2052  std::multiplies<APSInt>(), Result);
2053  case BO_Add:
2054  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2055  std::plus<APSInt>(), Result);
2056  case BO_Sub:
2057  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2058  std::minus<APSInt>(), Result);
2059  case BO_And: Result = LHS & RHS; return true;
2060  case BO_Xor: Result = LHS ^ RHS; return true;
2061  case BO_Or: Result = LHS | RHS; return true;
2062  case BO_Div:
2063  case BO_Rem:
2064  if (RHS == 0) {
2065  Info.FFDiag(E, diag::note_expr_divide_by_zero);
2066  return false;
2067  }
2068  Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2069  // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2070  // this operation and gives the two's complement result.
2071  if (RHS.isNegative() && RHS.isAllOnesValue() &&
2072  LHS.isSigned() && LHS.isMinSignedValue())
2073  return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2074  E->getType());
2075  return true;
2076  case BO_Shl: {
2077  if (Info.getLangOpts().OpenCL)
2078  // OpenCL 6.3j: shift values are effectively % word size of LHS.
2079  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2080  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2081  RHS.isUnsigned());
2082  else if (RHS.isSigned() && RHS.isNegative()) {
2083  // During constant-folding, a negative shift is an opposite shift. Such
2084  // a shift is not a constant expression.
2085  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2086  RHS = -RHS;
2087  goto shift_right;
2088  }
2089  shift_left:
2090  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2091  // the shifted type.
2092  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2093  if (SA != RHS) {
2094  Info.CCEDiag(E, diag::note_constexpr_large_shift)
2095  << RHS << E->getType() << LHS.getBitWidth();
2096  } else if (LHS.isSigned()) {
2097  // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2098  // operand, and must not overflow the corresponding unsigned type.
2099  if (LHS.isNegative())
2100  Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2101  else if (LHS.countLeadingZeros() < SA)
2102  Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2103  }
2104  Result = LHS << SA;
2105  return true;
2106  }
2107  case BO_Shr: {
2108  if (Info.getLangOpts().OpenCL)
2109  // OpenCL 6.3j: shift values are effectively % word size of LHS.
2110  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2111  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2112  RHS.isUnsigned());
2113  else if (RHS.isSigned() && RHS.isNegative()) {
2114  // During constant-folding, a negative shift is an opposite shift. Such a
2115  // shift is not a constant expression.
2116  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2117  RHS = -RHS;
2118  goto shift_left;
2119  }
2120  shift_right:
2121  // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2122  // shifted type.
2123  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2124  if (SA != RHS)
2125  Info.CCEDiag(E, diag::note_constexpr_large_shift)
2126  << RHS << E->getType() << LHS.getBitWidth();
2127  Result = LHS >> SA;
2128  return true;
2129  }
2130 
2131  case BO_LT: Result = LHS < RHS; return true;
2132  case BO_GT: Result = LHS > RHS; return true;
2133  case BO_LE: Result = LHS <= RHS; return true;
2134  case BO_GE: Result = LHS >= RHS; return true;
2135  case BO_EQ: Result = LHS == RHS; return true;
2136  case BO_NE: Result = LHS != RHS; return true;
2137  }
2138 }
2139 
2140 /// Perform the given binary floating-point operation, in-place, on LHS.
2141 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2142  APFloat &LHS, BinaryOperatorKind Opcode,
2143  const APFloat &RHS) {
2144  switch (Opcode) {
2145  default:
2146  Info.FFDiag(E);
2147  return false;
2148  case BO_Mul:
2149  LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2150  break;
2151  case BO_Add:
2152  LHS.add(RHS, APFloat::rmNearestTiesToEven);
2153  break;
2154  case BO_Sub:
2155  LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2156  break;
2157  case BO_Div:
2158  LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2159  break;
2160  }
2161 
2162  if (LHS.isInfinity() || LHS.isNaN()) {
2163  Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2164  return Info.noteUndefinedBehavior();
2165  }
2166  return true;
2167 }
2168 
2169 /// Cast an lvalue referring to a base subobject to a derived class, by
2170 /// truncating the lvalue's path to the given length.
2171 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2172  const RecordDecl *TruncatedType,
2173  unsigned TruncatedElements) {
2174  SubobjectDesignator &D = Result.Designator;
2175 
2176  // Check we actually point to a derived class object.
2177  if (TruncatedElements == D.Entries.size())
2178  return true;
2179  assert(TruncatedElements >= D.MostDerivedPathLength &&
2180  "not casting to a derived class");
2181  if (!Result.checkSubobject(Info, E, CSK_Derived))
2182  return false;
2183 
2184  // Truncate the path to the subobject, and remove any derived-to-base offsets.
2185  const RecordDecl *RD = TruncatedType;
2186  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2187  if (RD->isInvalidDecl()) return false;
2188  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2189  const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2190  if (isVirtualBaseClass(D.Entries[I]))
2191  Result.Offset -= Layout.getVBaseClassOffset(Base);
2192  else
2193  Result.Offset -= Layout.getBaseClassOffset(Base);
2194  RD = Base;
2195  }
2196  D.Entries.resize(TruncatedElements);
2197  return true;
2198 }
2199 
2200 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2201  const CXXRecordDecl *Derived,
2202  const CXXRecordDecl *Base,
2203  const ASTRecordLayout *RL = nullptr) {
2204  if (!RL) {
2205  if (Derived->isInvalidDecl()) return false;
2206  RL = &Info.Ctx.getASTRecordLayout(Derived);
2207  }
2208 
2209  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2210  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2211  return true;
2212 }
2213 
2214 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2215  const CXXRecordDecl *DerivedDecl,
2216  const CXXBaseSpecifier *Base) {
2217  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2218 
2219  if (!Base->isVirtual())
2220  return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2221 
2222  SubobjectDesignator &D = Obj.Designator;
2223  if (D.Invalid)
2224  return false;
2225 
2226  // Extract most-derived object and corresponding type.
2227  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2228  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2229  return false;
2230 
2231  // Find the virtual base class.
2232  if (DerivedDecl->isInvalidDecl()) return false;
2233  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2234  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2235  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2236  return true;
2237 }
2238 
2239 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2240  QualType Type, LValue &Result) {
2241  for (CastExpr::path_const_iterator PathI = E->path_begin(),
2242  PathE = E->path_end();
2243  PathI != PathE; ++PathI) {
2244  if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2245  *PathI))
2246  return false;
2247  Type = (*PathI)->getType();
2248  }
2249  return true;
2250 }
2251 
2252 /// Update LVal to refer to the given field, which must be a member of the type
2253 /// currently described by LVal.
2254 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2255  const FieldDecl *FD,
2256  const ASTRecordLayout *RL = nullptr) {
2257  if (!RL) {
2258  if (FD->getParent()->isInvalidDecl()) return false;
2259  RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2260  }
2261 
2262  unsigned I = FD->getFieldIndex();
2263  LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2264  LVal.addDecl(Info, E, FD);
2265  return true;
2266 }
2267 
2268 /// Update LVal to refer to the given indirect field.
2269 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2270  LValue &LVal,
2271  const IndirectFieldDecl *IFD) {
2272  for (const auto *C : IFD->chain())
2273  if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2274  return false;
2275  return true;
2276 }
2277 
2278 /// Get the size of the given type in char units.
2279 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2280  QualType Type, CharUnits &Size) {
2281  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2282  // extension.
2283  if (Type->isVoidType() || Type->isFunctionType()) {
2284  Size = CharUnits::One();
2285  return true;
2286  }
2287 
2288  if (Type->isDependentType()) {
2289  Info.FFDiag(Loc);
2290  return false;
2291  }
2292 
2293  if (!Type->isConstantSizeType()) {
2294  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2295  // FIXME: Better diagnostic.
2296  Info.FFDiag(Loc);
2297  return false;
2298  }
2299 
2300  Size = Info.Ctx.getTypeSizeInChars(Type);
2301  return true;
2302 }
2303 
2304 /// Update a pointer value to model pointer arithmetic.
2305 /// \param Info - Information about the ongoing evaluation.
2306 /// \param E - The expression being evaluated, for diagnostic purposes.
2307 /// \param LVal - The pointer value to be updated.
2308 /// \param EltTy - The pointee type represented by LVal.
2309 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2310 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2311  LValue &LVal, QualType EltTy,
2312  APSInt Adjustment) {
2313  CharUnits SizeOfPointee;
2314  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2315  return false;
2316 
2317  LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2318  return true;
2319 }
2320 
2321 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2322  LValue &LVal, QualType EltTy,
2323  int64_t Adjustment) {
2324  return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2325  APSInt::get(Adjustment));
2326 }
2327 
2328 /// Update an lvalue to refer to a component of a complex number.
2329 /// \param Info - Information about the ongoing evaluation.
2330 /// \param LVal - The lvalue to be updated.
2331 /// \param EltTy - The complex number's component type.
2332 /// \param Imag - False for the real component, true for the imaginary.
2333 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2334  LValue &LVal, QualType EltTy,
2335  bool Imag) {
2336  if (Imag) {
2337  CharUnits SizeOfComponent;
2338  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2339  return false;
2340  LVal.Offset += SizeOfComponent;
2341  }
2342  LVal.addComplex(Info, E, EltTy, Imag);
2343  return true;
2344 }
2345 
2346 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2347  QualType Type, const LValue &LVal,
2348  APValue &RVal);
2349 
2350 /// Try to evaluate the initializer for a variable declaration.
2351 ///
2352 /// \param Info Information about the ongoing evaluation.
2353 /// \param E An expression to be used when printing diagnostics.
2354 /// \param VD The variable whose initializer should be obtained.
2355 /// \param Frame The frame in which the variable was created. Must be null
2356 /// if this variable is not local to the evaluation.
2357 /// \param Result Filled in with a pointer to the value of the variable.
2358 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2359  const VarDecl *VD, CallStackFrame *Frame,
2360  APValue *&Result) {
2361 
2362  // If this is a parameter to an active constexpr function call, perform
2363  // argument substitution.
2364  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2365  // Assume arguments of a potential constant expression are unknown
2366  // constant expressions.
2367  if (Info.checkingPotentialConstantExpression())
2368  return false;
2369  if (!Frame || !Frame->Arguments) {
2370  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2371  return false;
2372  }
2373  Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2374  return true;
2375  }
2376 
2377  // If this is a local variable, dig out its value.
2378  if (Frame) {
2379  Result = Frame->getTemporary(VD);
2380  if (!Result) {
2381  // Assume variables referenced within a lambda's call operator that were
2382  // not declared within the call operator are captures and during checking
2383  // of a potential constant expression, assume they are unknown constant
2384  // expressions.
2385  assert(isLambdaCallOperator(Frame->Callee) &&
2386  (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2387  "missing value for local variable");
2388  if (Info.checkingPotentialConstantExpression())
2389  return false;
2390  // FIXME: implement capture evaluation during constant expr evaluation.
2391  Info.FFDiag(E->getLocStart(),
2392  diag::note_unimplemented_constexpr_lambda_feature_ast)
2393  << "captures not currently allowed";
2394  return false;
2395  }
2396  return true;
2397  }
2398 
2399  // Dig out the initializer, and use the declaration which it's attached to.
2400  const Expr *Init = VD->getAnyInitializer(VD);
2401  if (!Init || Init->isValueDependent()) {
2402  // If we're checking a potential constant expression, the variable could be
2403  // initialized later.
2404  if (!Info.checkingPotentialConstantExpression())
2405  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2406  return false;
2407  }
2408 
2409  // If we're currently evaluating the initializer of this declaration, use that
2410  // in-flight value.
2411  if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2412  Result = Info.EvaluatingDeclValue;
2413  return true;
2414  }
2415 
2416  // Never evaluate the initializer of a weak variable. We can't be sure that
2417  // this is the definition which will be used.
2418  if (VD->isWeak()) {
2419  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2420  return false;
2421  }
2422 
2423  // Check that we can fold the initializer. In C++, we will have already done
2424  // this in the cases where it matters for conformance.
2426  if (!VD->evaluateValue(Notes)) {
2427  Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2428  Notes.size() + 1) << VD;
2429  Info.Note(VD->getLocation(), diag::note_declared_at);
2430  Info.addNotes(Notes);
2431  return false;
2432  } else if (!VD->checkInitIsICE()) {
2433  Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2434  Notes.size() + 1) << VD;
2435  Info.Note(VD->getLocation(), diag::note_declared_at);
2436  Info.addNotes(Notes);
2437  }
2438 
2439  Result = VD->getEvaluatedValue();
2440  return true;
2441 }
2442 
2444  Qualifiers Quals = T.getQualifiers();
2445  return Quals.hasConst() && !Quals.hasVolatile();
2446 }
2447 
2448 /// Get the base index of the given base class within an APValue representing
2449 /// the given derived class.
2450 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2451  const CXXRecordDecl *Base) {
2452  Base = Base->getCanonicalDecl();
2453  unsigned Index = 0;
2455  E = Derived->bases_end(); I != E; ++I, ++Index) {
2456  if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2457  return Index;
2458  }
2459 
2460  llvm_unreachable("base class missing from derived class's bases list");
2461 }
2462 
2463 /// Extract the value of a character from a string literal.
2464 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2465  uint64_t Index) {
2466  // FIXME: Support MakeStringConstant
2467  if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2468  std::string Str;
2469  Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2470  assert(Index <= Str.size() && "Index too large");
2471  return APSInt::getUnsigned(Str.c_str()[Index]);
2472  }
2473 
2474  if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2475  Lit = PE->getFunctionName();
2476  const StringLiteral *S = cast<StringLiteral>(Lit);
2477  const ConstantArrayType *CAT =
2478  Info.Ctx.getAsConstantArrayType(S->getType());
2479  assert(CAT && "string literal isn't an array");
2480  QualType CharType = CAT->getElementType();
2481  assert(CharType->isIntegerType() && "unexpected character type");
2482 
2483  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2484  CharType->isUnsignedIntegerType());
2485  if (Index < S->getLength())
2486  Value = S->getCodeUnit(Index);
2487  return Value;
2488 }
2489 
2490 // Expand a string literal into an array of characters.
2491 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2492  APValue &Result) {
2493  const StringLiteral *S = cast<StringLiteral>(Lit);
2494  const ConstantArrayType *CAT =
2495  Info.Ctx.getAsConstantArrayType(S->getType());
2496  assert(CAT && "string literal isn't an array");
2497  QualType CharType = CAT->getElementType();
2498  assert(CharType->isIntegerType() && "unexpected character type");
2499 
2500  unsigned Elts = CAT->getSize().getZExtValue();
2501  Result = APValue(APValue::UninitArray(),
2502  std::min(S->getLength(), Elts), Elts);
2503  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2504  CharType->isUnsignedIntegerType());
2505  if (Result.hasArrayFiller())
2506  Result.getArrayFiller() = APValue(Value);
2507  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2508  Value = S->getCodeUnit(I);
2509  Result.getArrayInitializedElt(I) = APValue(Value);
2510  }
2511 }
2512 
2513 // Expand an array so that it has more than Index filled elements.
2514 static void expandArray(APValue &Array, unsigned Index) {
2515  unsigned Size = Array.getArraySize();
2516  assert(Index < Size);
2517 
2518  // Always at least double the number of elements for which we store a value.
2519  unsigned OldElts = Array.getArrayInitializedElts();
2520  unsigned NewElts = std::max(Index+1, OldElts * 2);
2521  NewElts = std::min(Size, std::max(NewElts, 8u));
2522 
2523  // Copy the data across.
2524  APValue NewValue(APValue::UninitArray(), NewElts, Size);
2525  for (unsigned I = 0; I != OldElts; ++I)
2526  NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2527  for (unsigned I = OldElts; I != NewElts; ++I)
2528  NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2529  if (NewValue.hasArrayFiller())
2530  NewValue.getArrayFiller() = Array.getArrayFiller();
2531  Array.swap(NewValue);
2532 }
2533 
2534 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2535 /// conversion. If it's of class type, we may assume that the copy operation
2536 /// is trivial. Note that this is never true for a union type with fields
2537 /// (because the copy always "reads" the active member) and always true for
2538 /// a non-class type.
2541  if (!RD || (RD->isUnion() && !RD->field_empty()))
2542  return true;
2543  if (RD->isEmpty())
2544  return false;
2545 
2546  for (auto *Field : RD->fields())
2547  if (isReadByLvalueToRvalueConversion(Field->getType()))
2548  return true;
2549 
2550  for (auto &BaseSpec : RD->bases())
2551  if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2552  return true;
2553 
2554  return false;
2555 }
2556 
2557 /// Diagnose an attempt to read from any unreadable field within the specified
2558 /// type, which might be a class type.
2559 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2560  QualType T) {
2562  if (!RD)
2563  return false;
2564 
2565  if (!RD->hasMutableFields())
2566  return false;
2567 
2568  for (auto *Field : RD->fields()) {
2569  // If we're actually going to read this field in some way, then it can't
2570  // be mutable. If we're in a union, then assigning to a mutable field
2571  // (even an empty one) can change the active member, so that's not OK.
2572  // FIXME: Add core issue number for the union case.
2573  if (Field->isMutable() &&
2574  (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2575  Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2576  Info.Note(Field->getLocation(), diag::note_declared_at);
2577  return true;
2578  }
2579 
2580  if (diagnoseUnreadableFields(Info, E, Field->getType()))
2581  return true;
2582  }
2583 
2584  for (auto &BaseSpec : RD->bases())
2585  if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2586  return true;
2587 
2588  // All mutable fields were empty, and thus not actually read.
2589  return false;
2590 }
2591 
2592 /// Kinds of access we can perform on an object, for diagnostics.
2598 };
2599 
2600 namespace {
2601 /// A handle to a complete object (an object that is not a subobject of
2602 /// another object).
2603 struct CompleteObject {
2604  /// The value of the complete object.
2605  APValue *Value;
2606  /// The type of the complete object.
2607  QualType Type;
2608 
2609  CompleteObject() : Value(nullptr) {}
2610  CompleteObject(APValue *Value, QualType Type)
2611  : Value(Value), Type(Type) {
2612  assert(Value && "missing value for complete object");
2613  }
2614 
2615  explicit operator bool() const { return Value; }
2616 };
2617 } // end anonymous namespace
2618 
2619 /// Find the designated sub-object of an rvalue.
2620 template<typename SubobjectHandler>
2621 typename SubobjectHandler::result_type
2622 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2623  const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2624  if (Sub.Invalid)
2625  // A diagnostic will have already been produced.
2626  return handler.failed();
2627  if (Sub.isOnePastTheEnd()) {
2628  if (Info.getLangOpts().CPlusPlus11)
2629  Info.FFDiag(E, diag::note_constexpr_access_past_end)
2630  << handler.AccessKind;
2631  else
2632  Info.FFDiag(E);
2633  return handler.failed();
2634  }
2635 
2636  APValue *O = Obj.Value;
2637  QualType ObjType = Obj.Type;
2638  const FieldDecl *LastField = nullptr;
2639 
2640  // Walk the designator's path to find the subobject.
2641  for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2642  if (O->isUninit()) {
2643  if (!Info.checkingPotentialConstantExpression())
2644  Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2645  return handler.failed();
2646  }
2647 
2648  if (I == N) {
2649  // If we are reading an object of class type, there may still be more
2650  // things we need to check: if there are any mutable subobjects, we
2651  // cannot perform this read. (This only happens when performing a trivial
2652  // copy or assignment.)
2653  if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2654  diagnoseUnreadableFields(Info, E, ObjType))
2655  return handler.failed();
2656 
2657  if (!handler.found(*O, ObjType))
2658  return false;
2659 
2660  // If we modified a bit-field, truncate it to the right width.
2661  if (handler.AccessKind != AK_Read &&
2662  LastField && LastField->isBitField() &&
2663  !truncateBitfieldValue(Info, E, *O, LastField))
2664  return false;
2665 
2666  return true;
2667  }
2668 
2669  LastField = nullptr;
2670  if (ObjType->isArrayType()) {
2671  // Next subobject is an array element.
2672  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2673  assert(CAT && "vla in literal type?");
2674  uint64_t Index = Sub.Entries[I].ArrayIndex;
2675  if (CAT->getSize().ule(Index)) {
2676  // Note, it should not be possible to form a pointer with a valid
2677  // designator which points more than one past the end of the array.
2678  if (Info.getLangOpts().CPlusPlus11)
2679  Info.FFDiag(E, diag::note_constexpr_access_past_end)
2680  << handler.AccessKind;
2681  else
2682  Info.FFDiag(E);
2683  return handler.failed();
2684  }
2685 
2686  ObjType = CAT->getElementType();
2687 
2688  // An array object is represented as either an Array APValue or as an
2689  // LValue which refers to a string literal.
2690  if (O->isLValue()) {
2691  assert(I == N - 1 && "extracting subobject of character?");
2692  assert(!O->hasLValuePath() || O->getLValuePath().empty());
2693  if (handler.AccessKind != AK_Read)
2694  expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2695  *O);
2696  else
2697  return handler.foundString(*O, ObjType, Index);
2698  }
2699 
2700  if (O->getArrayInitializedElts() > Index)
2701  O = &O->getArrayInitializedElt(Index);
2702  else if (handler.AccessKind != AK_Read) {
2703  expandArray(*O, Index);
2704  O = &O->getArrayInitializedElt(Index);
2705  } else
2706  O = &O->getArrayFiller();
2707  } else if (ObjType->isAnyComplexType()) {
2708  // Next subobject is a complex number.
2709  uint64_t Index = Sub.Entries[I].ArrayIndex;
2710  if (Index > 1) {
2711  if (Info.getLangOpts().CPlusPlus11)
2712  Info.FFDiag(E, diag::note_constexpr_access_past_end)
2713  << handler.AccessKind;
2714  else
2715  Info.FFDiag(E);
2716  return handler.failed();
2717  }
2718 
2719  bool WasConstQualified = ObjType.isConstQualified();
2720  ObjType = ObjType->castAs<ComplexType>()->getElementType();
2721  if (WasConstQualified)
2722  ObjType.addConst();
2723 
2724  assert(I == N - 1 && "extracting subobject of scalar?");
2725  if (O->isComplexInt()) {
2726  return handler.found(Index ? O->getComplexIntImag()
2727  : O->getComplexIntReal(), ObjType);
2728  } else {
2729  assert(O->isComplexFloat());
2730  return handler.found(Index ? O->getComplexFloatImag()
2731  : O->getComplexFloatReal(), ObjType);
2732  }
2733  } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2734  if (Field->isMutable() && handler.AccessKind == AK_Read) {
2735  Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2736  << Field;
2737  Info.Note(Field->getLocation(), diag::note_declared_at);
2738  return handler.failed();
2739  }
2740 
2741  // Next subobject is a class, struct or union field.
2742  RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2743  if (RD->isUnion()) {
2744  const FieldDecl *UnionField = O->getUnionField();
2745  if (!UnionField ||
2746  UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2747  Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2748  << handler.AccessKind << Field << !UnionField << UnionField;
2749  return handler.failed();
2750  }
2751  O = &O->getUnionValue();
2752  } else
2753  O = &O->getStructField(Field->getFieldIndex());
2754 
2755  bool WasConstQualified = ObjType.isConstQualified();
2756  ObjType = Field->getType();
2757  if (WasConstQualified && !Field->isMutable())
2758  ObjType.addConst();
2759 
2760  if (ObjType.isVolatileQualified()) {
2761  if (Info.getLangOpts().CPlusPlus) {
2762  // FIXME: Include a description of the path to the volatile subobject.
2763  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2764  << handler.AccessKind << 2 << Field;
2765  Info.Note(Field->getLocation(), diag::note_declared_at);
2766  } else {
2767  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2768  }
2769  return handler.failed();
2770  }
2771 
2772  LastField = Field;
2773  } else {
2774  // Next subobject is a base class.
2775  const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2776  const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2777  O = &O->getStructBase(getBaseIndex(Derived, Base));
2778 
2779  bool WasConstQualified = ObjType.isConstQualified();
2780  ObjType = Info.Ctx.getRecordType(Base);
2781  if (WasConstQualified)
2782  ObjType.addConst();
2783  }
2784  }
2785 }
2786 
2787 namespace {
2788 struct ExtractSubobjectHandler {
2789  EvalInfo &Info;
2790  APValue &Result;
2791 
2792  static const AccessKinds AccessKind = AK_Read;
2793 
2794  typedef bool result_type;
2795  bool failed() { return false; }
2796  bool found(APValue &Subobj, QualType SubobjType) {
2797  Result = Subobj;
2798  return true;
2799  }
2800  bool found(APSInt &Value, QualType SubobjType) {
2801  Result = APValue(Value);
2802  return true;
2803  }
2804  bool found(APFloat &Value, QualType SubobjType) {
2805  Result = APValue(Value);
2806  return true;
2807  }
2808  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2810  Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2811  return true;
2812  }
2813 };
2814 } // end anonymous namespace
2815 
2817 
2818 /// Extract the designated sub-object of an rvalue.
2819 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2820  const CompleteObject &Obj,
2821  const SubobjectDesignator &Sub,
2822  APValue &Result) {
2823  ExtractSubobjectHandler Handler = { Info, Result };
2824  return findSubobject(Info, E, Obj, Sub, Handler);
2825 }
2826 
2827 namespace {
2828 struct ModifySubobjectHandler {
2829  EvalInfo &Info;
2830  APValue &NewVal;
2831  const Expr *E;
2832 
2833  typedef bool result_type;
2834  static const AccessKinds AccessKind = AK_Assign;
2835 
2836  bool checkConst(QualType QT) {
2837  // Assigning to a const object has undefined behavior.
2838  if (QT.isConstQualified()) {
2839  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2840  return false;
2841  }
2842  return true;
2843  }
2844 
2845  bool failed() { return false; }
2846  bool found(APValue &Subobj, QualType SubobjType) {
2847  if (!checkConst(SubobjType))
2848  return false;
2849  // We've been given ownership of NewVal, so just swap it in.
2850  Subobj.swap(NewVal);
2851  return true;
2852  }
2853  bool found(APSInt &Value, QualType SubobjType) {
2854  if (!checkConst(SubobjType))
2855  return false;
2856  if (!NewVal.isInt()) {
2857  // Maybe trying to write a cast pointer value into a complex?
2858  Info.FFDiag(E);
2859  return false;
2860  }
2861  Value = NewVal.getInt();
2862  return true;
2863  }
2864  bool found(APFloat &Value, QualType SubobjType) {
2865  if (!checkConst(SubobjType))
2866  return false;
2867  Value = NewVal.getFloat();
2868  return true;
2869  }
2870  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2871  llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2872  }
2873 };
2874 } // end anonymous namespace
2875 
2877 
2878 /// Update the designated sub-object of an rvalue to the given value.
2879 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2880  const CompleteObject &Obj,
2881  const SubobjectDesignator &Sub,
2882  APValue &NewVal) {
2883  ModifySubobjectHandler Handler = { Info, NewVal, E };
2884  return findSubobject(Info, E, Obj, Sub, Handler);
2885 }
2886 
2887 /// Find the position where two subobject designators diverge, or equivalently
2888 /// the length of the common initial subsequence.
2889 static unsigned FindDesignatorMismatch(QualType ObjType,
2890  const SubobjectDesignator &A,
2891  const SubobjectDesignator &B,
2892  bool &WasArrayIndex) {
2893  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2894  for (/**/; I != N; ++I) {
2895  if (!ObjType.isNull() &&
2896  (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2897  // Next subobject is an array element.
2898  if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2899  WasArrayIndex = true;
2900  return I;
2901  }
2902  if (ObjType->isAnyComplexType())
2903  ObjType = ObjType->castAs<ComplexType>()->getElementType();
2904  else
2905  ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2906  } else {
2907  if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2908  WasArrayIndex = false;
2909  return I;
2910  }
2911  if (const FieldDecl *FD = getAsField(A.Entries[I]))
2912  // Next subobject is a field.
2913  ObjType = FD->getType();
2914  else
2915  // Next subobject is a base class.
2916  ObjType = QualType();
2917  }
2918  }
2919  WasArrayIndex = false;
2920  return I;
2921 }
2922 
2923 /// Determine whether the given subobject designators refer to elements of the
2924 /// same array object.
2925 static bool AreElementsOfSameArray(QualType ObjType,
2926  const SubobjectDesignator &A,
2927  const SubobjectDesignator &B) {
2928  if (A.Entries.size() != B.Entries.size())
2929  return false;
2930 
2931  bool IsArray = A.MostDerivedIsArrayElement;
2932  if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2933  // A is a subobject of the array element.
2934  return false;
2935 
2936  // If A (and B) designates an array element, the last entry will be the array
2937  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2938  // of length 1' case, and the entire path must match.
2939  bool WasArrayIndex;
2940  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2941  return CommonLength >= A.Entries.size() - IsArray;
2942 }
2943 
2944 /// Find the complete object to which an LValue refers.
2945 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2946  AccessKinds AK, const LValue &LVal,
2947  QualType LValType) {
2948  if (!LVal.Base) {
2949  Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2950  return CompleteObject();
2951  }
2952 
2953  CallStackFrame *Frame = nullptr;
2954  if (LVal.CallIndex) {
2955  Frame = Info.getCallFrame(LVal.CallIndex);
2956  if (!Frame) {
2957  Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2958  << AK << LVal.Base.is<const ValueDecl*>();
2959  NoteLValueLocation(Info, LVal.Base);
2960  return CompleteObject();
2961  }
2962  }
2963 
2964  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2965  // is not a constant expression (even if the object is non-volatile). We also
2966  // apply this rule to C++98, in order to conform to the expected 'volatile'
2967  // semantics.
2968  if (LValType.isVolatileQualified()) {
2969  if (Info.getLangOpts().CPlusPlus)
2970  Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
2971  << AK << LValType;
2972  else
2973  Info.FFDiag(E);
2974  return CompleteObject();
2975  }
2976 
2977  // Compute value storage location and type of base object.
2978  APValue *BaseVal = nullptr;
2979  QualType BaseType = getType(LVal.Base);
2980 
2981  if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2982  // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2983  // In C++11, constexpr, non-volatile variables initialized with constant
2984  // expressions are constant expressions too. Inside constexpr functions,
2985  // parameters are constant expressions even if they're non-const.
2986  // In C++1y, objects local to a constant expression (those with a Frame) are
2987  // both readable and writable inside constant expressions.
2988  // In C, such things can also be folded, although they are not ICEs.
2989  const VarDecl *VD = dyn_cast<VarDecl>(D);
2990  if (VD) {
2991  if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2992  VD = VDef;
2993  }
2994  if (!VD || VD->isInvalidDecl()) {
2995  Info.FFDiag(E);
2996  return CompleteObject();
2997  }
2998 
2999  // Accesses of volatile-qualified objects are not allowed.
3000  if (BaseType.isVolatileQualified()) {
3001  if (Info.getLangOpts().CPlusPlus) {
3002  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3003  << AK << 1 << VD;
3004  Info.Note(VD->getLocation(), diag::note_declared_at);
3005  } else {
3006  Info.FFDiag(E);
3007  }
3008  return CompleteObject();
3009  }
3010 
3011  // Unless we're looking at a local variable or argument in a constexpr call,
3012  // the variable we're reading must be const.
3013  if (!Frame) {
3014  if (Info.getLangOpts().CPlusPlus14 &&
3015  VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3016  // OK, we can read and modify an object if we're in the process of
3017  // evaluating its initializer, because its lifetime began in this
3018  // evaluation.
3019  } else if (AK != AK_Read) {
3020  // All the remaining cases only permit reading.
3021  Info.FFDiag(E, diag::note_constexpr_modify_global);
3022  return CompleteObject();
3023  } else if (VD->isConstexpr()) {
3024  // OK, we can read this variable.
3025  } else if (BaseType->isIntegralOrEnumerationType()) {
3026  // In OpenCL if a variable is in constant address space it is a const value.
3027  if (!(BaseType.isConstQualified() ||
3028  (Info.getLangOpts().OpenCL &&
3029  BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3030  if (Info.getLangOpts().CPlusPlus) {
3031  Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3032  Info.Note(VD->getLocation(), diag::note_declared_at);
3033  } else {
3034  Info.FFDiag(E);
3035  }
3036  return CompleteObject();
3037  }
3038  } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3039  // We support folding of const floating-point types, in order to make
3040  // static const data members of such types (supported as an extension)
3041  // more useful.
3042  if (Info.getLangOpts().CPlusPlus11) {
3043  Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3044  Info.Note(VD->getLocation(), diag::note_declared_at);
3045  } else {
3046  Info.CCEDiag(E);
3047  }
3048  } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3049  Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3050  // Keep evaluating to see what we can do.
3051  } else {
3052  // FIXME: Allow folding of values of any literal type in all languages.
3053  if (Info.checkingPotentialConstantExpression() &&
3054  VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3055  // The definition of this variable could be constexpr. We can't
3056  // access it right now, but may be able to in future.
3057  } else if (Info.getLangOpts().CPlusPlus11) {
3058  Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3059  Info.Note(VD->getLocation(), diag::note_declared_at);
3060  } else {
3061  Info.FFDiag(E);
3062  }
3063  return CompleteObject();
3064  }
3065  }
3066 
3067  if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3068  return CompleteObject();
3069  } else {
3070  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3071 
3072  if (!Frame) {
3073  if (const MaterializeTemporaryExpr *MTE =
3074  dyn_cast<MaterializeTemporaryExpr>(Base)) {
3075  assert(MTE->getStorageDuration() == SD_Static &&
3076  "should have a frame for a non-global materialized temporary");
3077 
3078  // Per C++1y [expr.const]p2:
3079  // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3080  // - a [...] glvalue of integral or enumeration type that refers to
3081  // a non-volatile const object [...]
3082  // [...]
3083  // - a [...] glvalue of literal type that refers to a non-volatile
3084  // object whose lifetime began within the evaluation of e.
3085  //
3086  // C++11 misses the 'began within the evaluation of e' check and
3087  // instead allows all temporaries, including things like:
3088  // int &&r = 1;
3089  // int x = ++r;
3090  // constexpr int k = r;
3091  // Therefore we use the C++1y rules in C++11 too.
3092  const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3093  const ValueDecl *ED = MTE->getExtendingDecl();
3094  if (!(BaseType.isConstQualified() &&
3095  BaseType->isIntegralOrEnumerationType()) &&
3096  !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3097  Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3098  Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3099  return CompleteObject();
3100  }
3101 
3102  BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3103  assert(BaseVal && "got reference to unevaluated temporary");
3104  } else {
3105  Info.FFDiag(E);
3106  return CompleteObject();
3107  }
3108  } else {
3109  BaseVal = Frame->getTemporary(Base);
3110  assert(BaseVal && "missing value for temporary");
3111  }
3112 
3113  // Volatile temporary objects cannot be accessed in constant expressions.
3114  if (BaseType.isVolatileQualified()) {
3115  if (Info.getLangOpts().CPlusPlus) {
3116  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3117  << AK << 0;
3118  Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3119  } else {
3120  Info.FFDiag(E);
3121  }
3122  return CompleteObject();
3123  }
3124  }
3125 
3126  // During the construction of an object, it is not yet 'const'.
3127  // FIXME: This doesn't do quite the right thing for const subobjects of the
3128  // object under construction.
3129  if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
3130  BaseType = Info.Ctx.getCanonicalType(BaseType);
3131  BaseType.removeLocalConst();
3132  }
3133 
3134  // In C++1y, we can't safely access any mutable state when we might be
3135  // evaluating after an unmodeled side effect.
3136  //
3137  // FIXME: Not all local state is mutable. Allow local constant subobjects
3138  // to be read here (but take care with 'mutable' fields).
3139  if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3140  Info.EvalStatus.HasSideEffects) ||
3141  (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3142  return CompleteObject();
3143 
3144  return CompleteObject(BaseVal, BaseType);
3145 }
3146 
3147 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3148 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3149 /// glvalue referred to by an entity of reference type.
3150 ///
3151 /// \param Info - Information about the ongoing evaluation.
3152 /// \param Conv - The expression for which we are performing the conversion.
3153 /// Used for diagnostics.
3154 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3155 /// case of a non-class type).
3156 /// \param LVal - The glvalue on which we are attempting to perform this action.
3157 /// \param RVal - The produced value will be placed here.
3158 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3159  QualType Type,
3160  const LValue &LVal, APValue &RVal) {
3161  if (LVal.Designator.Invalid)
3162  return false;
3163 
3164  // Check for special cases where there is no existing APValue to look at.
3165  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3166  if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3167  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3168  // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3169  // initializer until now for such expressions. Such an expression can't be
3170  // an ICE in C, so this only matters for fold.
3171  if (Type.isVolatileQualified()) {
3172  Info.FFDiag(Conv);
3173  return false;
3174  }
3175  APValue Lit;
3176  if (!Evaluate(Lit, Info, CLE->getInitializer()))
3177  return false;
3178  CompleteObject LitObj(&Lit, Base->getType());
3179  return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3180  } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3181  // We represent a string literal array as an lvalue pointing at the
3182  // corresponding expression, rather than building an array of chars.
3183  // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3184  APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3185  CompleteObject StrObj(&Str, Base->getType());
3186  return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3187  }
3188  }
3189 
3190  CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3191  return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3192 }
3193 
3194 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3195 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3196  QualType LValType, APValue &Val) {
3197  if (LVal.Designator.Invalid)
3198  return false;
3199 
3200  if (!Info.getLangOpts().CPlusPlus14) {
3201  Info.FFDiag(E);
3202  return false;
3203  }
3204 
3205  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3206  return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3207 }
3208 
3210  return T->isSignedIntegerType() &&
3211  Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3212 }
3213 
3214 namespace {
3215 struct CompoundAssignSubobjectHandler {
3216  EvalInfo &Info;
3217  const Expr *E;
3218  QualType PromotedLHSType;
3219  BinaryOperatorKind Opcode;
3220  const APValue &RHS;
3221 
3222  static const AccessKinds AccessKind = AK_Assign;
3223 
3224  typedef bool result_type;
3225 
3226  bool checkConst(QualType QT) {
3227  // Assigning to a const object has undefined behavior.
3228  if (QT.isConstQualified()) {
3229  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3230  return false;
3231  }
3232  return true;
3233  }
3234 
3235  bool failed() { return false; }
3236  bool found(APValue &Subobj, QualType SubobjType) {
3237  switch (Subobj.getKind()) {
3238  case APValue::Int:
3239  return found(Subobj.getInt(), SubobjType);
3240  case APValue::Float:
3241  return found(Subobj.getFloat(), SubobjType);
3242  case APValue::ComplexInt:
3243  case APValue::ComplexFloat:
3244  // FIXME: Implement complex compound assignment.
3245  Info.FFDiag(E);
3246  return false;
3247  case APValue::LValue:
3248  return foundPointer(Subobj, SubobjType);
3249  default:
3250  // FIXME: can this happen?
3251  Info.FFDiag(E);
3252  return false;
3253  }
3254  }
3255  bool found(APSInt &Value, QualType SubobjType) {
3256  if (!checkConst(SubobjType))
3257  return false;
3258 
3259  if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3260  // We don't support compound assignment on integer-cast-to-pointer
3261  // values.
3262  Info.FFDiag(E);
3263  return false;
3264  }
3265 
3266  APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3267  SubobjType, Value);
3268  if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3269  return false;
3270  Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3271  return true;
3272  }
3273  bool found(APFloat &Value, QualType SubobjType) {
3274  return checkConst(SubobjType) &&
3275  HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3276  Value) &&
3277  handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3278  HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3279  }
3280  bool foundPointer(APValue &Subobj, QualType SubobjType) {
3281  if (!checkConst(SubobjType))
3282  return false;
3283 
3284  QualType PointeeType;
3285  if (const PointerType *PT = SubobjType->getAs<PointerType>())
3286  PointeeType = PT->getPointeeType();
3287 
3288  if (PointeeType.isNull() || !RHS.isInt() ||
3289  (Opcode != BO_Add && Opcode != BO_Sub)) {
3290  Info.FFDiag(E);
3291  return false;
3292  }
3293 
3294  APSInt Offset = RHS.getInt();
3295  if (Opcode == BO_Sub)
3296  negateAsSigned(Offset);
3297 
3298  LValue LVal;
3299  LVal.setFrom(Info.Ctx, Subobj);
3300  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3301  return false;
3302  LVal.moveInto(Subobj);
3303  return true;
3304  }
3305  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3306  llvm_unreachable("shouldn't encounter string elements here");
3307  }
3308 };
3309 } // end anonymous namespace
3310 
3312 
3313 /// Perform a compound assignment of LVal <op>= RVal.
3315  EvalInfo &Info, const Expr *E,
3316  const LValue &LVal, QualType LValType, QualType PromotedLValType,
3317  BinaryOperatorKind Opcode, const APValue &RVal) {
3318  if (LVal.Designator.Invalid)
3319  return false;
3320 
3321  if (!Info.getLangOpts().CPlusPlus14) {
3322  Info.FFDiag(E);
3323  return false;
3324  }
3325 
3326  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3327  CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3328  RVal };
3329  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3330 }
3331 
3332 namespace {
3333 struct IncDecSubobjectHandler {
3334  EvalInfo &Info;
3335  const Expr *E;
3337  APValue *Old;
3338 
3339  typedef bool result_type;
3340 
3341  bool checkConst(QualType QT) {
3342  // Assigning to a const object has undefined behavior.
3343  if (QT.isConstQualified()) {
3344  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3345  return false;
3346  }
3347  return true;
3348  }
3349 
3350  bool failed() { return false; }
3351  bool found(APValue &Subobj, QualType SubobjType) {
3352  // Stash the old value. Also clear Old, so we don't clobber it later
3353  // if we're post-incrementing a complex.
3354  if (Old) {
3355  *Old = Subobj;
3356  Old = nullptr;
3357  }
3358 
3359  switch (Subobj.getKind()) {
3360  case APValue::Int:
3361  return found(Subobj.getInt(), SubobjType);
3362  case APValue::Float:
3363  return found(Subobj.getFloat(), SubobjType);
3364  case APValue::ComplexInt:
3365  return found(Subobj.getComplexIntReal(),
3366  SubobjType->castAs<ComplexType>()->getElementType()
3367  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3368  case APValue::ComplexFloat:
3369  return found(Subobj.getComplexFloatReal(),
3370  SubobjType->castAs<ComplexType>()->getElementType()
3371  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3372  case APValue::LValue:
3373  return foundPointer(Subobj, SubobjType);
3374  default:
3375  // FIXME: can this happen?
3376  Info.FFDiag(E);
3377  return false;
3378  }
3379  }
3380  bool found(APSInt &Value, QualType SubobjType) {
3381  if (!checkConst(SubobjType))
3382  return false;
3383 
3384  if (!SubobjType->isIntegerType()) {
3385  // We don't support increment / decrement on integer-cast-to-pointer
3386  // values.
3387  Info.FFDiag(E);
3388  return false;
3389  }
3390 
3391  if (Old) *Old = APValue(Value);
3392 
3393  // bool arithmetic promotes to int, and the conversion back to bool
3394  // doesn't reduce mod 2^n, so special-case it.
3395  if (SubobjType->isBooleanType()) {
3396  if (AccessKind == AK_Increment)
3397  Value = 1;
3398  else
3399  Value = !Value;
3400  return true;
3401  }
3402 
3403  bool WasNegative = Value.isNegative();
3404  if (AccessKind == AK_Increment) {
3405  ++Value;
3406 
3407  if (!WasNegative && Value.isNegative() &&
3408  isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3409  APSInt ActualValue(Value, /*IsUnsigned*/true);
3410  return HandleOverflow(Info, E, ActualValue, SubobjType);
3411  }
3412  } else {
3413  --Value;
3414 
3415  if (WasNegative && !Value.isNegative() &&
3416  isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3417  unsigned BitWidth = Value.getBitWidth();
3418  APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3419  ActualValue.setBit(BitWidth);
3420  return HandleOverflow(Info, E, ActualValue, SubobjType);
3421  }
3422  }
3423  return true;
3424  }
3425  bool found(APFloat &Value, QualType SubobjType) {
3426  if (!checkConst(SubobjType))
3427  return false;
3428 
3429  if (Old) *Old = APValue(Value);
3430 
3431  APFloat One(Value.getSemantics(), 1);
3432  if (AccessKind == AK_Increment)
3433  Value.add(One, APFloat::rmNearestTiesToEven);
3434  else
3435  Value.subtract(One, APFloat::rmNearestTiesToEven);
3436  return true;
3437  }
3438  bool foundPointer(APValue &Subobj, QualType SubobjType) {
3439  if (!checkConst(SubobjType))
3440  return false;
3441 
3442  QualType PointeeType;
3443  if (const PointerType *PT = SubobjType->getAs<PointerType>())
3444  PointeeType = PT->getPointeeType();
3445  else {
3446  Info.FFDiag(E);
3447  return false;
3448  }
3449 
3450  LValue LVal;
3451  LVal.setFrom(Info.Ctx, Subobj);
3452  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3453  AccessKind == AK_Increment ? 1 : -1))
3454  return false;
3455  LVal.moveInto(Subobj);
3456  return true;
3457  }
3458  bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3459  llvm_unreachable("shouldn't encounter string elements here");
3460  }
3461 };
3462 } // end anonymous namespace
3463 
3464 /// Perform an increment or decrement on LVal.
3465 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3466  QualType LValType, bool IsIncrement, APValue *Old) {
3467  if (LVal.Designator.Invalid)
3468  return false;
3469 
3470  if (!Info.getLangOpts().CPlusPlus14) {
3471  Info.FFDiag(E);
3472  return false;
3473  }
3474 
3475  AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3476  CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3477  IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3478  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3479 }
3480 
3481 /// Build an lvalue for the object argument of a member function call.
3482 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3483  LValue &This) {
3484  if (Object->getType()->isPointerType())
3485  return EvaluatePointer(Object, This, Info);
3486 
3487  if (Object->isGLValue())
3488  return EvaluateLValue(Object, This, Info);
3489 
3490  if (Object->getType()->isLiteralType(Info.Ctx))
3491  return EvaluateTemporary(Object, This, Info);
3492 
3493  Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3494  return false;
3495 }
3496 
3497 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3498 /// lvalue referring to the result.
3499 ///
3500 /// \param Info - Information about the ongoing evaluation.
3501 /// \param LV - An lvalue referring to the base of the member pointer.
3502 /// \param RHS - The member pointer expression.
3503 /// \param IncludeMember - Specifies whether the member itself is included in
3504 /// the resulting LValue subobject designator. This is not possible when
3505 /// creating a bound member function.
3506 /// \return The field or method declaration to which the member pointer refers,
3507 /// or 0 if evaluation fails.
3508 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3509  QualType LVType,
3510  LValue &LV,
3511  const Expr *RHS,
3512  bool IncludeMember = true) {
3513  MemberPtr MemPtr;
3514  if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3515  return nullptr;
3516 
3517  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3518  // member value, the behavior is undefined.
3519  if (!MemPtr.getDecl()) {
3520  // FIXME: Specific diagnostic.
3521  Info.FFDiag(RHS);
3522  return nullptr;
3523  }
3524 
3525  if (MemPtr.isDerivedMember()) {
3526  // This is a member of some derived class. Truncate LV appropriately.
3527  // The end of the derived-to-base path for the base object must match the
3528  // derived-to-base path for the member pointer.
3529  if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3530  LV.Designator.Entries.size()) {
3531  Info.FFDiag(RHS);
3532  return nullptr;
3533  }
3534  unsigned PathLengthToMember =
3535  LV.Designator.Entries.size() - MemPtr.Path.size();
3536  for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3537  const CXXRecordDecl *LVDecl = getAsBaseClass(
3538  LV.Designator.Entries[PathLengthToMember + I]);
3539  const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3540  if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3541  Info.FFDiag(RHS);
3542  return nullptr;
3543  }
3544  }
3545 
3546  // Truncate the lvalue to the appropriate derived class.
3547  if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3548  PathLengthToMember))
3549  return nullptr;
3550  } else if (!MemPtr.Path.empty()) {
3551  // Extend the LValue path with the member pointer's path.
3552  LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3553  MemPtr.Path.size() + IncludeMember);
3554 
3555  // Walk down to the appropriate base class.
3556  if (const PointerType *PT = LVType->getAs<PointerType>())
3557  LVType = PT->getPointeeType();
3558  const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3559  assert(RD && "member pointer access on non-class-type expression");
3560  // The first class in the path is that of the lvalue.
3561  for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3562  const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3563  if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3564  return nullptr;
3565  RD = Base;
3566  }
3567  // Finally cast to the class containing the member.
3568  if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3569  MemPtr.getContainingRecord()))
3570  return nullptr;
3571  }
3572 
3573  // Add the member. Note that we cannot build bound member functions here.
3574  if (IncludeMember) {
3575  if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3576  if (!HandleLValueMember(Info, RHS, LV, FD))
3577  return nullptr;
3578  } else if (const IndirectFieldDecl *IFD =
3579  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3580  if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3581  return nullptr;
3582  } else {
3583  llvm_unreachable("can't construct reference to bound member function");
3584  }
3585  }
3586 
3587  return MemPtr.getDecl();
3588 }
3589 
3590 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3591  const BinaryOperator *BO,
3592  LValue &LV,
3593  bool IncludeMember = true) {
3594  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3595 
3596  if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3597  if (Info.noteFailure()) {
3598  MemberPtr MemPtr;
3599  EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3600  }
3601  return nullptr;
3602  }
3603 
3604  return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3605  BO->getRHS(), IncludeMember);
3606 }
3607 
3608 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3609 /// the provided lvalue, which currently refers to the base object.
3610 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3611  LValue &Result) {
3612  SubobjectDesignator &D = Result.Designator;
3613  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3614  return false;
3615 
3616  QualType TargetQT = E->getType();
3617  if (const PointerType *PT = TargetQT->getAs<PointerType>())
3618  TargetQT = PT->getPointeeType();
3619 
3620  // Check this cast lands within the final derived-to-base subobject path.
3621  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3622  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3623  << D.MostDerivedType << TargetQT;
3624  return false;
3625  }
3626 
3627  // Check the type of the final cast. We don't need to check the path,
3628  // since a cast can only be formed if the path is unique.
3629  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3630  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3631  const CXXRecordDecl *FinalType;
3632  if (NewEntriesSize == D.MostDerivedPathLength)
3633  FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3634  else
3635  FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3636  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3637  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3638  << D.MostDerivedType << TargetQT;
3639  return false;
3640  }
3641 
3642  // Truncate the lvalue to the appropriate derived class.
3643  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3644 }
3645 
3646 namespace {
3648  /// Evaluation failed.
3649  ESR_Failed,
3650  /// Hit a 'return' statement.
3651  ESR_Returned,
3652  /// Evaluation succeeded.
3653  ESR_Succeeded,
3654  /// Hit a 'continue' statement.
3655  ESR_Continue,
3656  /// Hit a 'break' statement.
3657  ESR_Break,
3658  /// Still scanning for 'case' or 'default' statement.
3659  ESR_CaseNotFound
3660 };
3661 }
3662 
3663 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3664  // We don't need to evaluate the initializer for a static local.
3665  if (!VD->hasLocalStorage())
3666  return true;
3667 
3668  LValue Result;
3669  Result.set(VD, Info.CurrentCall->Index);
3670  APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3671 
3672  const Expr *InitE = VD->getInit();
3673  if (!InitE) {
3674  Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3675  << false << VD->getType();
3676  Val = APValue();
3677  return false;
3678  }
3679 
3680  if (InitE->isValueDependent())
3681  return false;
3682 
3683  if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3684  // Wipe out any partially-computed value, to allow tracking that this
3685  // evaluation failed.
3686  Val = APValue();
3687  return false;
3688  }
3689 
3690  return true;
3691 }
3692 
3693 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3694  bool OK = true;
3695 
3696  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3697  OK &= EvaluateVarDecl(Info, VD);
3698 
3699  if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3700  for (auto *BD : DD->bindings())
3701  if (auto *VD = BD->getHoldingVar())
3702  OK &= EvaluateDecl(Info, VD);
3703 
3704  return OK;
3705 }
3706 
3707 
3708 /// Evaluate a condition (either a variable declaration or an expression).
3709 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3710  const Expr *Cond, bool &Result) {
3711  FullExpressionRAII Scope(Info);
3712  if (CondDecl && !EvaluateDecl(Info, CondDecl))
3713  return false;
3714  return EvaluateAsBooleanCondition(Cond, Result, Info);
3715 }
3716 
3717 namespace {
3718 /// \brief A location where the result (returned value) of evaluating a
3719 /// statement should be stored.
3720 struct StmtResult {
3721  /// The APValue that should be filled in with the returned value.
3722  APValue &Value;
3723  /// The location containing the result, if any (used to support RVO).
3724  const LValue *Slot;
3725 };
3726 }
3727 
3728 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3729  const Stmt *S,
3730  const SwitchCase *SC = nullptr);
3731 
3732 /// Evaluate the body of a loop, and translate the result as appropriate.
3733 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3734  const Stmt *Body,
3735  const SwitchCase *Case = nullptr) {
3736  BlockScopeRAII Scope(Info);
3737  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3738  case ESR_Break:
3739  return ESR_Succeeded;
3740  case ESR_Succeeded:
3741  case ESR_Continue:
3742  return ESR_Continue;
3743  case ESR_Failed:
3744  case ESR_Returned:
3745  case ESR_CaseNotFound:
3746  return ESR;
3747  }
3748  llvm_unreachable("Invalid EvalStmtResult!");
3749 }
3750 
3751 /// Evaluate a switch statement.
3752 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3753  const SwitchStmt *SS) {
3754  BlockScopeRAII Scope(Info);
3755 
3756  // Evaluate the switch condition.
3757  APSInt Value;
3758  {
3759  FullExpressionRAII Scope(Info);
3760  if (const Stmt *Init = SS->getInit()) {
3761  EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3762  if (ESR != ESR_Succeeded)
3763  return ESR;
3764  }
3765  if (SS->getConditionVariable() &&
3766  !EvaluateDecl(Info, SS->getConditionVariable()))
3767  return ESR_Failed;
3768  if (!EvaluateInteger(SS->getCond(), Value, Info))
3769  return ESR_Failed;
3770  }
3771 
3772  // Find the switch case corresponding to the value of the condition.
3773  // FIXME: Cache this lookup.
3774  const SwitchCase *Found = nullptr;
3775  for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3776  SC = SC->getNextSwitchCase()) {
3777  if (isa<DefaultStmt>(SC)) {
3778  Found = SC;
3779  continue;
3780  }
3781 
3782  const CaseStmt *CS = cast<CaseStmt>(SC);
3783  APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3784  APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3785  : LHS;
3786  if (LHS <= Value && Value <= RHS) {
3787  Found = SC;
3788  break;
3789  }
3790  }
3791 
3792  if (!Found)
3793  return ESR_Succeeded;
3794 
3795  // Search the switch body for the switch case and evaluate it from there.
3796  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3797  case ESR_Break:
3798  return ESR_Succeeded;
3799  case ESR_Succeeded:
3800  case ESR_Continue:
3801  case ESR_Failed:
3802  case ESR_Returned:
3803  return ESR;
3804  case ESR_CaseNotFound:
3805  // This can only happen if the switch case is nested within a statement
3806  // expression. We have no intention of supporting that.
3807  Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3808  return ESR_Failed;
3809  }
3810  llvm_unreachable("Invalid EvalStmtResult!");
3811 }
3812 
3813 // Evaluate a statement.
3814 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3815  const Stmt *S, const SwitchCase *Case) {
3816  if (!Info.nextStep(S))
3817  return ESR_Failed;
3818 
3819  // If we're hunting down a 'case' or 'default' label, recurse through
3820  // substatements until we hit the label.
3821  if (Case) {
3822  // FIXME: We don't start the lifetime of objects whose initialization we
3823  // jump over. However, such objects must be of class type with a trivial
3824  // default constructor that initialize all subobjects, so must be empty,
3825  // so this almost never matters.
3826  switch (S->getStmtClass()) {
3827  case Stmt::CompoundStmtClass:
3828  // FIXME: Precompute which substatement of a compound statement we
3829  // would jump to, and go straight there rather than performing a
3830  // linear scan each time.
3831  case Stmt::LabelStmtClass:
3832  case Stmt::AttributedStmtClass:
3833  case Stmt::DoStmtClass:
3834  break;
3835 
3836  case Stmt::CaseStmtClass:
3837  case Stmt::DefaultStmtClass:
3838  if (Case == S)
3839  Case = nullptr;
3840  break;
3841 
3842  case Stmt::IfStmtClass: {
3843  // FIXME: Precompute which side of an 'if' we would jump to, and go
3844  // straight there rather than scanning both sides.
3845  const IfStmt *IS = cast<IfStmt>(S);
3846 
3847  // Wrap the evaluation in a block scope, in case it's a DeclStmt
3848  // preceded by our switch label.
3849  BlockScopeRAII Scope(Info);
3850 
3851  EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3852  if (ESR != ESR_CaseNotFound || !IS->getElse())
3853  return ESR;
3854  return EvaluateStmt(Result, Info, IS->getElse(), Case);
3855  }
3856 
3857  case Stmt::WhileStmtClass: {
3858  EvalStmtResult ESR =
3859  EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3860  if (ESR != ESR_Continue)
3861  return ESR;
3862  break;
3863  }
3864 
3865  case Stmt::ForStmtClass: {
3866  const ForStmt *FS = cast<ForStmt>(S);
3867  EvalStmtResult ESR =
3868  EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3869  if (ESR != ESR_Continue)
3870  return ESR;
3871  if (FS->getInc()) {
3872  FullExpressionRAII IncScope(Info);
3873  if (!EvaluateIgnoredValue(Info, FS->getInc()))
3874  return ESR_Failed;
3875  }
3876  break;
3877  }
3878 
3879  case Stmt::DeclStmtClass:
3880  // FIXME: If the variable has initialization that can't be jumped over,
3881  // bail out of any immediately-surrounding compound-statement too.
3882  default:
3883  return ESR_CaseNotFound;
3884  }
3885  }
3886 
3887  switch (S->getStmtClass()) {
3888  default:
3889  if (const Expr *E = dyn_cast<Expr>(S)) {
3890  // Don't bother evaluating beyond an expression-statement which couldn't
3891  // be evaluated.
3892  FullExpressionRAII Scope(Info);
3893  if (!EvaluateIgnoredValue(Info, E))
3894  return ESR_Failed;
3895  return ESR_Succeeded;
3896  }
3897 
3898  Info.FFDiag(S->getLocStart());
3899  return ESR_Failed;
3900 
3901  case Stmt::NullStmtClass:
3902  return ESR_Succeeded;
3903 
3904  case Stmt::DeclStmtClass: {
3905  const DeclStmt *DS = cast<DeclStmt>(S);
3906  for (const auto *DclIt : DS->decls()) {
3907  // Each declaration initialization is its own full-expression.
3908  // FIXME: This isn't quite right; if we're performing aggregate
3909  // initialization, each braced subexpression is its own full-expression.
3910  FullExpressionRAII Scope(Info);
3911  if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3912  return ESR_Failed;
3913  }
3914  return ESR_Succeeded;
3915  }
3916 
3917  case Stmt::ReturnStmtClass: {
3918  const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3919  FullExpressionRAII Scope(Info);
3920  if (RetExpr &&
3921  !(Result.Slot
3922  ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3923  : Evaluate(Result.Value, Info, RetExpr)))
3924  return ESR_Failed;
3925  return ESR_Returned;
3926  }
3927 
3928  case Stmt::CompoundStmtClass: {
3929  BlockScopeRAII Scope(Info);
3930 
3931  const CompoundStmt *CS = cast<CompoundStmt>(S);
3932  for (const auto *BI : CS->body()) {
3933  EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3934  if (ESR == ESR_Succeeded)
3935  Case = nullptr;
3936  else if (ESR != ESR_CaseNotFound)
3937  return ESR;
3938  }
3939  return Case ? ESR_CaseNotFound : ESR_Succeeded;
3940  }
3941 
3942  case Stmt::IfStmtClass: {
3943  const IfStmt *IS = cast<IfStmt>(S);
3944 
3945  // Evaluate the condition, as either a var decl or as an expression.
3946  BlockScopeRAII Scope(Info);
3947  if (const Stmt *Init = IS->getInit()) {
3948  EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3949  if (ESR != ESR_Succeeded)
3950  return ESR;
3951  }
3952  bool Cond;
3953  if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3954  return ESR_Failed;
3955 
3956  if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3957  EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3958  if (ESR != ESR_Succeeded)
3959  return ESR;
3960  }
3961  return ESR_Succeeded;
3962  }
3963 
3964  case Stmt::WhileStmtClass: {
3965  const WhileStmt *WS = cast<WhileStmt>(S);
3966  while (true) {
3967  BlockScopeRAII Scope(Info);
3968  bool Continue;
3969  if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3970  Continue))
3971  return ESR_Failed;
3972  if (!Continue)
3973  break;
3974 
3975  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3976  if (ESR != ESR_Continue)
3977  return ESR;
3978  }
3979  return ESR_Succeeded;
3980  }
3981 
3982  case Stmt::DoStmtClass: {
3983  const DoStmt *DS = cast<DoStmt>(S);
3984  bool Continue;
3985  do {
3986  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3987  if (ESR != ESR_Continue)
3988  return ESR;
3989  Case = nullptr;
3990 
3991  FullExpressionRAII CondScope(Info);
3992  if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3993  return ESR_Failed;
3994  } while (Continue);
3995  return ESR_Succeeded;
3996  }
3997 
3998  case Stmt::ForStmtClass: {
3999  const ForStmt *FS = cast<ForStmt>(S);
4000  BlockScopeRAII Scope(Info);
4001  if (FS->getInit()) {
4002  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4003  if (ESR != ESR_Succeeded)
4004  return ESR;
4005  }
4006  while (true) {
4007  BlockScopeRAII Scope(Info);
4008  bool Continue = true;
4009  if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4010  FS->getCond(), Continue))
4011  return ESR_Failed;
4012  if (!Continue)
4013  break;
4014 
4015  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4016  if (ESR != ESR_Continue)
4017  return ESR;
4018 
4019  if (FS->getInc()) {
4020  FullExpressionRAII IncScope(Info);
4021  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4022  return ESR_Failed;
4023  }
4024  }
4025  return ESR_Succeeded;
4026  }
4027 
4028  case Stmt::CXXForRangeStmtClass: {
4029  const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4030  BlockScopeRAII Scope(Info);
4031 
4032  // Initialize the __range variable.
4033  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4034  if (ESR != ESR_Succeeded)
4035  return ESR;
4036 
4037  // Create the __begin and __end iterators.
4038  ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4039  if (ESR != ESR_Succeeded)
4040  return ESR;
4041  ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4042  if (ESR != ESR_Succeeded)
4043  return ESR;
4044 
4045  while (true) {
4046  // Condition: __begin != __end.
4047  {
4048  bool Continue = true;
4049  FullExpressionRAII CondExpr(Info);
4050  if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4051  return ESR_Failed;
4052  if (!Continue)
4053  break;
4054  }
4055 
4056  // User's variable declaration, initialized by *__begin.
4057  BlockScopeRAII InnerScope(Info);
4058  ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4059  if (ESR != ESR_Succeeded)
4060  return ESR;
4061 
4062  // Loop body.
4063  ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4064  if (ESR != ESR_Continue)
4065  return ESR;
4066 
4067  // Increment: ++__begin
4068  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4069  return ESR_Failed;
4070  }
4071 
4072  return ESR_Succeeded;
4073  }
4074 
4075  case Stmt::SwitchStmtClass:
4076  return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4077 
4078  case Stmt::ContinueStmtClass:
4079  return ESR_Continue;
4080 
4081  case Stmt::BreakStmtClass:
4082  return ESR_Break;
4083 
4084  case Stmt::LabelStmtClass:
4085  return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4086 
4087  case Stmt::AttributedStmtClass:
4088  // As a general principle, C++11 attributes can be ignored without
4089  // any semantic impact.
4090  return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4091  Case);
4092 
4093  case Stmt::CaseStmtClass:
4094  case Stmt::DefaultStmtClass:
4095  return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4096  }
4097 }
4098 
4099 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4100 /// default constructor. If so, we'll fold it whether or not it's marked as
4101 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4102 /// so we need special handling.
4103 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4104  const CXXConstructorDecl *CD,
4105  bool IsValueInitialization) {
4106  if (!CD->isTrivial() || !CD->isDefaultConstructor())
4107  return false;
4108 
4109  // Value-initialization does not call a trivial default constructor, so such a
4110  // call is a core constant expression whether or not the constructor is
4111  // constexpr.
4112  if (!CD->isConstexpr() && !IsValueInitialization) {
4113  if (Info.getLangOpts().CPlusPlus11) {
4114  // FIXME: If DiagDecl is an implicitly-declared special member function,
4115  // we should be much more explicit about why it's not constexpr.
4116  Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4117  << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4118  Info.Note(CD->getLocation(), diag::note_declared_at);
4119  } else {
4120  Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4121  }
4122  }
4123  return true;
4124 }
4125 
4126 /// CheckConstexprFunction - Check that a function can be called in a constant
4127 /// expression.
4128 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4129  const FunctionDecl *Declaration,
4130  const FunctionDecl *Definition,
4131  const Stmt *Body) {
4132  // Potential constant expressions can contain calls to declared, but not yet
4133  // defined, constexpr functions.
4134  if (Info.checkingPotentialConstantExpression() && !Definition &&
4135  Declaration->isConstexpr())
4136  return false;
4137 
4138  // Bail out with no diagnostic if the function declaration itself is invalid.
4139  // We will have produced a relevant diagnostic while parsing it.
4140  if (Declaration->isInvalidDecl())
4141  return false;
4142 
4143  // Can we evaluate this function call?
4144  if (Definition && Definition->isConstexpr() &&
4145  !Definition->isInvalidDecl() && Body)
4146  return true;
4147 
4148  if (Info.getLangOpts().CPlusPlus11) {
4149  const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4150 
4151  // If this function is not constexpr because it is an inherited
4152  // non-constexpr constructor, diagnose that directly.
4153  auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4154  if (CD && CD->isInheritingConstructor()) {
4155  auto *Inherited = CD->getInheritedConstructor().getConstructor();
4156  if (!Inherited->isConstexpr())
4157  DiagDecl = CD = Inherited;
4158  }
4159 
4160  // FIXME: If DiagDecl is an implicitly-declared special member function
4161  // or an inheriting constructor, we should be much more explicit about why
4162  // it's not constexpr.
4163  if (CD && CD->isInheritingConstructor())
4164  Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4165  << CD->getInheritedConstructor().getConstructor()->getParent();
4166  else
4167  Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4168  << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4169  Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4170  } else {
4171  Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4172  }
4173  return false;
4174 }
4175 
4176 /// Determine if a class has any fields that might need to be copied by a
4177 /// trivial copy or move operation.
4178 static bool hasFields(const CXXRecordDecl *RD) {
4179  if (!RD || RD->isEmpty())
4180  return false;
4181  for (auto *FD : RD->fields()) {
4182  if (FD->isUnnamedBitfield())
4183  continue;
4184  return true;
4185  }
4186  for (auto &Base : RD->bases())
4187  if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4188  return true;
4189  return false;
4190 }
4191 
4192 namespace {
4193 typedef SmallVector<APValue, 8> ArgVector;
4194 }
4195 
4196 /// EvaluateArgs - Evaluate the arguments to a function call.
4197 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4198  EvalInfo &Info) {
4199  bool Success = true;
4200  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4201  I != E; ++I) {
4202  if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4203  // If we're checking for a potential constant expression, evaluate all
4204  // initializers even if some of them fail.
4205  if (!Info.noteFailure())
4206  return false;
4207  Success = false;
4208  }
4209  }
4210  return Success;
4211 }
4212 
4213 /// Evaluate a function call.
4215  const FunctionDecl *Callee, const LValue *This,
4216  ArrayRef<const Expr*> Args, const Stmt *Body,
4217  EvalInfo &Info, APValue &Result,
4218  const LValue *ResultSlot) {
4219  ArgVector ArgValues(Args.size());
4220  if (!EvaluateArgs(Args, ArgValues, Info))
4221  return false;
4222 
4223  if (!Info.CheckCallLimit(CallLoc))
4224  return false;
4225 
4226  CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4227 
4228  // For a trivial copy or move assignment, perform an APValue copy. This is
4229  // essential for unions, where the operations performed by the assignment
4230  // operator cannot be represented as statements.
4231  //
4232  // Skip this for non-union classes with no fields; in that case, the defaulted
4233  // copy/move does not actually read the object.
4234  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4235  if (MD && MD->isDefaulted() &&
4236  (MD->getParent()->isUnion() ||
4237  (MD->isTrivial() && hasFields(MD->getParent())))) {
4238  assert(This &&
4239  (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4240  LValue RHS;
4241  RHS.setFrom(Info.Ctx, ArgValues[0]);
4242  APValue RHSValue;
4243  if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4244  RHS, RHSValue))
4245  return false;
4246  if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4247  RHSValue))
4248  return false;
4249  This->moveInto(Result);
4250  return true;
4251  } else if (MD && isLambdaCallOperator(MD)) {
4252  // We're in a lambda; determine the lambda capture field maps.
4253  MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4254  Frame.LambdaThisCaptureField);
4255  }
4256 
4257  StmtResult Ret = {Result, ResultSlot};
4258  EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4259  if (ESR == ESR_Succeeded) {
4260  if (Callee->getReturnType()->isVoidType())
4261  return true;
4262  Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4263  }
4264  return ESR == ESR_Returned;
4265 }
4266 
4267 /// Evaluate a constructor call.
4268 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4269  APValue *ArgValues,
4270  const CXXConstructorDecl *Definition,
4271  EvalInfo &Info, APValue &Result) {
4272  SourceLocation CallLoc = E->getExprLoc();
4273  if (!Info.CheckCallLimit(CallLoc))
4274  return false;
4275 
4276  const CXXRecordDecl *RD = Definition->getParent();
4277  if (RD->getNumVBases()) {
4278  Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4279  return false;
4280  }
4281 
4282  EvalInfo::EvaluatingConstructorRAII EvalObj(
4283  Info, {This.getLValueBase(), This.CallIndex});
4284  CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4285 
4286  // FIXME: Creating an APValue just to hold a nonexistent return value is
4287  // wasteful.
4288  APValue RetVal;
4289  StmtResult Ret = {RetVal, nullptr};
4290 
4291  // If it's a delegating constructor, delegate.
4292  if (Definition->isDelegatingConstructor()) {
4294  {
4295  FullExpressionRAII InitScope(Info);
4296  if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4297  return false;
4298  }
4299  return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4300  }
4301 
4302  // For a trivial copy or move constructor, perform an APValue copy. This is
4303  // essential for unions (or classes with anonymous union members), where the
4304  // operations performed by the constructor cannot be represented by
4305  // ctor-initializers.
4306  //
4307  // Skip this for empty non-union classes; we should not perform an
4308  // lvalue-to-rvalue conversion on them because their copy constructor does not
4309  // actually read them.
4310  if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4311  (Definition->getParent()->isUnion() ||
4312  (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4313  LValue RHS;
4314  RHS.setFrom(Info.Ctx, ArgValues[0]);
4316  Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4317  RHS, Result);
4318  }
4319 
4320  // Reserve space for the struct members.
4321  if (!RD->isUnion() && Result.isUninit())
4322  Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4323  std::distance(RD->field_begin(), RD->field_end()));
4324 
4325  if (RD->isInvalidDecl()) return false;
4326  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4327 
4328  // A scope for temporaries lifetime-extended by reference members.
4329  BlockScopeRAII LifetimeExtendedScope(Info);
4330 
4331  bool Success = true;
4332  unsigned BasesSeen = 0;
4333 #ifndef NDEBUG
4335 #endif
4336  for (const auto *I : Definition->inits()) {
4337  LValue Subobject = This;
4338  APValue *Value = &Result;
4339 
4340  // Determine the subobject to initialize.
4341  FieldDecl *FD = nullptr;
4342  if (I->isBaseInitializer()) {
4343  QualType BaseType(I->getBaseClass(), 0);
4344 #ifndef NDEBUG
4345  // Non-virtual base classes are initialized in the order in the class
4346  // definition. We have already checked for virtual base classes.
4347  assert(!BaseIt->isVirtual() && "virtual base for literal type");
4348  assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4349  "base class initializers not in expected order");
4350  ++BaseIt;
4351 #endif
4352  if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4353  BaseType->getAsCXXRecordDecl(), &Layout))
4354  return false;
4355  Value = &Result.getStructBase(BasesSeen++);
4356  } else if ((FD = I->getMember())) {
4357  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4358  return false;
4359  if (RD->isUnion()) {
4360  Result = APValue(FD);
4361  Value = &Result.getUnionValue();
4362  } else {
4363  Value = &Result.getStructField(FD->getFieldIndex());
4364  }
4365  } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4366  // Walk the indirect field decl's chain to find the object to initialize,
4367  // and make sure we've initialized every step along it.
4368  for (auto *C : IFD->chain()) {
4369  FD = cast<FieldDecl>(C);
4370  CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4371  // Switch the union field if it differs. This happens if we had
4372  // preceding zero-initialization, and we're now initializing a union
4373  // subobject other than the first.
4374  // FIXME: In this case, the values of the other subobjects are
4375  // specified, since zero-initialization sets all padding bits to zero.
4376  if (Value->isUninit() ||
4377  (Value->isUnion() && Value->getUnionField() != FD)) {
4378  if (CD->isUnion())
4379  *Value = APValue(FD);
4380  else
4381  *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4382  std::distance(CD->field_begin(), CD->field_end()));
4383  }
4384  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4385  return false;
4386  if (CD->isUnion())
4387  Value = &Value->getUnionValue();
4388  else
4389  Value = &Value->getStructField(FD->getFieldIndex());
4390  }
4391  } else {
4392  llvm_unreachable("unknown base initializer kind");
4393  }
4394 
4395  FullExpressionRAII InitScope(Info);
4396  if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4397  (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4398  *Value, FD))) {
4399  // If we're checking for a potential constant expression, evaluate all
4400  // initializers even if some of them fail.
4401  if (!Info.noteFailure())
4402  return false;
4403  Success = false;
4404  }
4405  }
4406 
4407  return Success &&
4408  EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4409 }
4410 
4411 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4412  ArrayRef<const Expr*> Args,
4413  const CXXConstructorDecl *Definition,
4414  EvalInfo &Info, APValue &Result) {
4415  ArgVector ArgValues(Args.size());
4416  if (!EvaluateArgs(Args, ArgValues, Info))
4417  return false;
4418 
4419  return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4420  Info, Result);
4421 }
4422 
4423 //===----------------------------------------------------------------------===//
4424 // Generic Evaluation
4425 //===----------------------------------------------------------------------===//
4426 namespace {
4427 
4428 template <class Derived>
4429 class ExprEvaluatorBase
4430  : public ConstStmtVisitor<Derived, bool> {
4431 private:
4432  Derived &getDerived() { return static_cast<Derived&>(*this); }
4433  bool DerivedSuccess(const APValue &V, const Expr *E) {
4434  return getDerived().Success(V, E);
4435  }
4436  bool DerivedZeroInitialization(const Expr *E) {
4437  return getDerived().ZeroInitialization(E);
4438  }
4439 
4440  // Check whether a conditional operator with a non-constant condition is a
4441  // potential constant expression. If neither arm is a potential constant
4442  // expression, then the conditional operator is not either.
4443  template<typename ConditionalOperator>
4444  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4445  assert(Info.checkingPotentialConstantExpression());
4446 
4447  // Speculatively evaluate both arms.
4449  {
4450  SpeculativeEvaluationRAII Speculate(Info, &Diag);
4451  StmtVisitorTy::Visit(E->getFalseExpr());
4452  if (Diag.empty())
4453  return;
4454  }
4455 
4456  {
4457  SpeculativeEvaluationRAII Speculate(Info, &Diag);
4458  Diag.clear();
4459  StmtVisitorTy::Visit(E->getTrueExpr());
4460  if (Diag.empty())
4461  return;
4462  }
4463 
4464  Error(E, diag::note_constexpr_conditional_never_const);
4465  }
4466 
4467 
4468  template<typename ConditionalOperator>
4469  bool HandleConditionalOperator(const ConditionalOperator *E) {
4470  bool BoolResult;
4471  if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4472  if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4473  CheckPotentialConstantConditional(E);
4474  return false;
4475  }
4476  if (Info.noteFailure()) {
4477  StmtVisitorTy::Visit(E->getTrueExpr());
4478  StmtVisitorTy::Visit(E->getFalseExpr());
4479  }
4480  return false;
4481  }
4482 
4483  Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4484  return StmtVisitorTy::Visit(EvalExpr);
4485  }
4486 
4487 protected:
4488  EvalInfo &Info;
4489  typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4490  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4491 
4492  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4493  return Info.CCEDiag(E, D);
4494  }
4495 
4496  bool ZeroInitialization(const Expr *E) { return Error(E); }
4497 
4498 public:
4499  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4500 
4501  EvalInfo &getEvalInfo() { return Info; }
4502 
4503  /// Report an evaluation error. This should only be called when an error is
4504  /// first discovered. When propagating an error, just return false.
4505  bool Error(const Expr *E, diag::kind D) {
4506  Info.FFDiag(E, D);
4507  return false;
4508  }
4509  bool Error(const Expr *E) {
4510  return Error(E, diag::note_invalid_subexpr_in_const_expr);
4511  }
4512 
4513  bool VisitStmt(const Stmt *) {
4514  llvm_unreachable("Expression evaluator should not be called on stmts");
4515  }
4516  bool VisitExpr(const Expr *E) {
4517  return Error(E);
4518  }
4519 
4520  bool VisitParenExpr(const ParenExpr *E)
4521  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4522  bool VisitUnaryExtension(const UnaryOperator *E)
4523  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4524  bool VisitUnaryPlus(const UnaryOperator *E)
4525  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4526  bool VisitChooseExpr(const ChooseExpr *E)
4527  { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4528  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4529  { return StmtVisitorTy::Visit(E->getResultExpr()); }
4530  bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4531  { return StmtVisitorTy::Visit(E->getReplacement()); }
4532  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4533  { return StmtVisitorTy::Visit(E->getExpr()); }
4534  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4535  // The initializer may not have been parsed yet, or might be erroneous.
4536  if (!E->getExpr())
4537  return Error(E);
4538  return StmtVisitorTy::Visit(E->getExpr());
4539  }
4540  // We cannot create any objects for which cleanups are required, so there is
4541  // nothing to do here; all cleanups must come from unevaluated subexpressions.
4542  bool VisitExprWithCleanups(const ExprWithCleanups *E)
4543  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4544 
4545  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4546  CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4547  return static_cast<Derived*>(this)->VisitCastExpr(E);
4548  }
4549  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4550  CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4551  return static_cast<Derived*>(this)->VisitCastExpr(E);
4552  }
4553 
4554  bool VisitBinaryOperator(const BinaryOperator *E) {
4555  switch (E->getOpcode()) {
4556  default:
4557  return Error(E);
4558 
4559  case BO_Comma:
4560  VisitIgnoredValue(E->getLHS());
4561  return StmtVisitorTy::Visit(E->getRHS());
4562 
4563  case BO_PtrMemD:
4564  case BO_PtrMemI: {
4565  LValue Obj;
4566  if (!HandleMemberPointerAccess(Info, E, Obj))
4567  return false;
4568  APValue Result;
4569  if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4570  return false;
4571  return DerivedSuccess(Result, E);
4572  }
4573  }
4574  }
4575 
4576  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4577  // Evaluate and cache the common expression. We treat it as a temporary,
4578  // even though it's not quite the same thing.
4579  if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4580  Info, E->getCommon()))
4581  return false;
4582 
4583  return HandleConditionalOperator(E);
4584  }
4585 
4586  bool VisitConditionalOperator(const ConditionalOperator *E) {
4587  bool IsBcpCall = false;
4588  // If the condition (ignoring parens) is a __builtin_constant_p call,
4589  // the result is a constant expression if it can be folded without
4590  // side-effects. This is an important GNU extension. See GCC PR38377
4591  // for discussion.
4592  if (const CallExpr *CallCE =
4593  dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4594  if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4595  IsBcpCall = true;
4596 
4597  // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4598  // constant expression; we can't check whether it's potentially foldable.
4599  if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4600  return false;
4601 
4602  FoldConstant Fold(Info, IsBcpCall);
4603  if (!HandleConditionalOperator(E)) {
4604  Fold.keepDiagnostics();
4605  return false;
4606  }
4607 
4608  return true;
4609  }
4610 
4611  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4612  if (APValue *Value = Info.CurrentCall->getTemporary(E))
4613  return DerivedSuccess(*Value, E);
4614 
4615  const Expr *Source = E->getSourceExpr();
4616  if (!Source)
4617  return Error(E);
4618  if (Source == E) { // sanity checking.
4619  assert(0 && "OpaqueValueExpr recursively refers to itself");
4620  return Error(E);
4621  }
4622  return StmtVisitorTy::Visit(Source);
4623  }
4624 
4625  bool VisitCallExpr(const CallExpr *E) {
4626  APValue Result;
4627  if (!handleCallExpr(E, Result, nullptr))
4628  return false;
4629  return DerivedSuccess(Result, E);
4630  }
4631 
4632  bool handleCallExpr(const CallExpr *E, APValue &Result,
4633  const LValue *ResultSlot) {
4634  const Expr *Callee = E->getCallee()->IgnoreParens();
4635  QualType CalleeType = Callee->getType();
4636 
4637  const FunctionDecl *FD = nullptr;
4638  LValue *This = nullptr, ThisVal;
4639  auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4640  bool HasQualifier = false;
4641 
4642  // Extract function decl and 'this' pointer from the callee.
4643  if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4644  const ValueDecl *Member = nullptr;
4645  if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4646  // Explicit bound member calls, such as x.f() or p->g();
4647  if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4648  return false;
4649  Member = ME->getMemberDecl();
4650  This = &ThisVal;
4651  HasQualifier = ME->hasQualifier();
4652  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4653  // Indirect bound member calls ('.*' or '->*').
4654  Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4655  if (!Member) return false;
4656  This = &ThisVal;
4657  } else
4658  return Error(Callee);
4659 
4660  FD = dyn_cast<FunctionDecl>(Member);
4661  if (!FD)
4662  return Error(Callee);
4663  } else if (CalleeType->isFunctionPointerType()) {
4664  LValue Call;
4665  if (!EvaluatePointer(Callee, Call, Info))
4666  return false;
4667 
4668  if (!Call.getLValueOffset().isZero())
4669  return Error(Callee);
4670  FD = dyn_cast_or_null<FunctionDecl>(
4671  Call.getLValueBase().dyn_cast<const ValueDecl*>());
4672  if (!FD)
4673  return Error(Callee);
4674  // Don't call function pointers which have been cast to some other type.
4675  // Per DR (no number yet), the caller and callee can differ in noexcept.
4676  if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4677  CalleeType->getPointeeType(), FD->getType())) {
4678  return Error(E);
4679  }
4680 
4681  // Overloaded operator calls to member functions are represented as normal
4682  // calls with '*this' as the first argument.
4683  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4684  if (MD && !MD->isStatic()) {
4685  // FIXME: When selecting an implicit conversion for an overloaded
4686  // operator delete, we sometimes try to evaluate calls to conversion
4687  // operators without a 'this' parameter!
4688  if (Args.empty())
4689  return Error(E);
4690 
4691  if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4692  return false;
4693  This = &ThisVal;
4694  Args = Args.slice(1);
4695  } else if (MD && MD->isLambdaStaticInvoker()) {
4696  // Map the static invoker for the lambda back to the call operator.
4697  // Conveniently, we don't have to slice out the 'this' argument (as is
4698  // being done for the non-static case), since a static member function
4699  // doesn't have an implicit argument passed in.
4700  const CXXRecordDecl *ClosureClass = MD->getParent();
4701  assert(
4702  ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4703  "Number of captures must be zero for conversion to function-ptr");
4704 
4705  const CXXMethodDecl *LambdaCallOp =
4706  ClosureClass->getLambdaCallOperator();
4707 
4708  // Set 'FD', the function that will be called below, to the call
4709  // operator. If the closure object represents a generic lambda, find
4710  // the corresponding specialization of the call operator.
4711 
4712  if (ClosureClass->isGenericLambda()) {
4713  assert(MD->isFunctionTemplateSpecialization() &&
4714  "A generic lambda's static-invoker function must be a "
4715  "template specialization");
4717  FunctionTemplateDecl *CallOpTemplate =
4718  LambdaCallOp->getDescribedFunctionTemplate();
4719  void *InsertPos = nullptr;
4720  FunctionDecl *CorrespondingCallOpSpecialization =
4721  CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4722  assert(CorrespondingCallOpSpecialization &&
4723  "We must always have a function call operator specialization "
4724  "that corresponds to our static invoker specialization");
4725  FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4726  } else
4727  FD = LambdaCallOp;
4728  }
4729 
4730 
4731  } else
4732  return Error(E);
4733 
4734  if (This && !This->checkSubobject(Info, E, CSK_This))
4735  return false;
4736 
4737  // DR1358 allows virtual constexpr functions in some cases. Don't allow
4738  // calls to such functions in constant expressions.
4739  if (This && !HasQualifier &&
4740  isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4741  return Error(E, diag::note_constexpr_virtual_call);
4742 
4743  const FunctionDecl *Definition = nullptr;
4744  Stmt *Body = FD->getBody(Definition);
4745 
4746  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4747  !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4748  Result, ResultSlot))
4749  return false;
4750 
4751  return true;
4752  }
4753 
4754  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4755  return StmtVisitorTy::Visit(E->getInitializer());
4756  }
4757  bool VisitInitListExpr(const InitListExpr *E) {
4758  if (E->getNumInits() == 0)
4759  return DerivedZeroInitialization(E);
4760  if (E->getNumInits() == 1)
4761  return StmtVisitorTy::Visit(E->getInit(0));
4762  return Error(E);
4763  }
4764  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4765  return DerivedZeroInitialization(E);
4766  }
4767  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4768  return DerivedZeroInitialization(E);
4769  }
4770  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4771  return DerivedZeroInitialization(E);
4772  }
4773 
4774  /// A member expression where the object is a prvalue is itself a prvalue.
4775  bool VisitMemberExpr(const MemberExpr *E) {
4776  assert(!E->isArrow() && "missing call to bound member function?");
4777 
4778  APValue Val;
4779  if (!Evaluate(Val, Info, E->getBase()))
4780  return false;
4781 
4782  QualType BaseTy = E->getBase()->getType();
4783 
4784  const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4785  if (!FD) return Error(E);
4786  assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4787  assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4788  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4789 
4790  CompleteObject Obj(&Val, BaseTy);
4791  SubobjectDesignator Designator(BaseTy);
4792  Designator.addDeclUnchecked(FD);
4793 
4794  APValue Result;
4795  return extractSubobject(Info, E, Obj, Designator, Result) &&
4796  DerivedSuccess(Result, E);
4797  }
4798 
4799  bool VisitCastExpr(const CastExpr *E) {
4800  switch (E->getCastKind()) {
4801  default:
4802  break;
4803 
4804  case CK_AtomicToNonAtomic: {
4805  APValue AtomicVal;
4806  // This does not need to be done in place even for class/array types:
4807  // atomic-to-non-atomic conversion implies copying the object
4808  // representation.
4809  if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4810  return false;
4811  return DerivedSuccess(AtomicVal, E);
4812  }
4813 
4814  case CK_NoOp:
4815  case CK_UserDefinedConversion:
4816  return StmtVisitorTy::Visit(E->getSubExpr());
4817 
4818  case CK_LValueToRValue: {
4819  LValue LVal;
4820  if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4821  return false;
4822  APValue RVal;
4823  // Note, we use the subexpression's type in order to retain cv-qualifiers.
4824  if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4825  LVal, RVal))
4826  return false;
4827  return DerivedSuccess(RVal, E);
4828  }
4829  }
4830 
4831  return Error(E);
4832  }
4833 
4834  bool VisitUnaryPostInc(const UnaryOperator *UO) {
4835  return VisitUnaryPostIncDec(UO);
4836  }
4837  bool VisitUnaryPostDec(const UnaryOperator *UO) {
4838  return VisitUnaryPostIncDec(UO);
4839  }
4840  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4841  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4842  return Error(UO);
4843 
4844  LValue LVal;
4845  if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4846  return false;
4847  APValue RVal;
4848  if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4849  UO->isIncrementOp(), &RVal))
4850  return false;
4851  return DerivedSuccess(RVal, UO);
4852  }
4853 
4854  bool VisitStmtExpr(const StmtExpr *E) {
4855  // We will have checked the full-expressions inside the statement expression
4856  // when they were completed, and don't need to check them again now.
4857  if (Info.checkingForOverflow())
4858  return Error(E);
4859 
4860  BlockScopeRAII Scope(Info);
4861  const CompoundStmt *CS = E->getSubStmt();
4862  if (CS->body_empty())
4863  return true;
4864 
4866  BE = CS->body_end();
4867  /**/; ++BI) {
4868  if (BI + 1 == BE) {
4869  const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4870  if (!FinalExpr) {
4871  Info.FFDiag((*BI)->getLocStart(),
4872  diag::note_constexpr_stmt_expr_unsupported);
4873  return false;
4874  }
4875  return this->Visit(FinalExpr);
4876  }
4877 
4878  APValue ReturnValue;
4879  StmtResult Result = { ReturnValue, nullptr };
4880  EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4881  if (ESR != ESR_Succeeded) {
4882  // FIXME: If the statement-expression terminated due to 'return',
4883  // 'break', or 'continue', it would be nice to propagate that to
4884  // the outer statement evaluation rather than bailing out.
4885  if (ESR != ESR_Failed)
4886  Info.FFDiag((*BI)->getLocStart(),
4887  diag::note_constexpr_stmt_expr_unsupported);
4888  return false;
4889  }
4890  }
4891 
4892  llvm_unreachable("Return from function from the loop above.");
4893  }
4894 
4895  /// Visit a value which is evaluated, but whose value is ignored.
4896  void VisitIgnoredValue(const Expr *E) {
4897  EvaluateIgnoredValue(Info, E);
4898  }
4899 
4900  /// Potentially visit a MemberExpr's base expression.
4901  void VisitIgnoredBaseExpression(const Expr *E) {
4902  // While MSVC doesn't evaluate the base expression, it does diagnose the
4903  // presence of side-effecting behavior.
4904  if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4905  return;
4906  VisitIgnoredValue(E);
4907  }
4908 };
4909 
4910 }
4911 
4912 //===----------------------------------------------------------------------===//
4913 // Common base class for lvalue and temporary evaluation.
4914 //===----------------------------------------------------------------------===//
4915 namespace {
4916 template<class Derived>
4917 class LValueExprEvaluatorBase
4918  : public ExprEvaluatorBase<Derived> {
4919 protected:
4920  LValue &Result;
4921  bool InvalidBaseOK;
4922  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4923  typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4924 
4925  bool Success(APValue::LValueBase B) {
4926  Result.set(B);
4927  return true;
4928  }
4929 
4930  bool evaluatePointer(const Expr *E, LValue &Result) {
4931  return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4932  }
4933 
4934 public:
4935  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4936  : ExprEvaluatorBaseTy(Info), Result(Result),
4937  InvalidBaseOK(InvalidBaseOK) {}
4938 
4939  bool Success(const APValue &V, const Expr *E) {
4940  Result.setFrom(this->Info.Ctx, V);
4941  return true;
4942  }
4943 
4944  bool VisitMemberExpr(const MemberExpr *E) {
4945  // Handle non-static data members.
4946  QualType BaseTy;
4947  bool EvalOK;
4948  if (E->isArrow()) {
4949  EvalOK = evaluatePointer(E->getBase(), Result);
4950  BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4951  } else if (E->getBase()->isRValue()) {
4952  assert(E->getBase()->getType()->isRecordType());
4953  EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4954  BaseTy = E->getBase()->getType();
4955  } else {
4956  EvalOK = this->Visit(E->getBase());
4957  BaseTy = E->getBase()->getType();
4958  }
4959  if (!EvalOK) {
4960  if (!InvalidBaseOK)
4961  return false;
4962  Result.setInvalid(E);
4963  return true;
4964  }
4965 
4966  const ValueDecl *MD = E->getMemberDecl();
4967  if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4968  assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4969  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4970  (void)BaseTy;
4971  if (!HandleLValueMember(this->Info, E, Result, FD))
4972  return false;
4973  } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4974  if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4975  return false;
4976  } else
4977  return this->Error(E);
4978 
4979  if (MD->getType()->isReferenceType()) {
4980  APValue RefValue;
4981  if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4982  RefValue))
4983  return false;
4984  return Success(RefValue, E);
4985  }
4986  return true;
4987  }
4988 
4989  bool VisitBinaryOperator(const BinaryOperator *E) {
4990  switch (E->getOpcode()) {
4991  default:
4992  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4993 
4994  case BO_PtrMemD:
4995  case BO_PtrMemI:
4996  return HandleMemberPointerAccess(this->Info, E, Result);
4997  }
4998  }
4999 
5000  bool VisitCastExpr(const CastExpr *E) {
5001  switch (E->getCastKind()) {
5002  default:
5003  return ExprEvaluatorBaseTy::VisitCastExpr(E);
5004 
5005  case CK_DerivedToBase:
5006  case CK_UncheckedDerivedToBase:
5007  if (!this->Visit(E->getSubExpr()))
5008  return false;
5009 
5010  // Now figure out the necessary offset to add to the base LV to get from
5011  // the derived class to the base class.
5012  return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5013  Result);
5014  }
5015  }
5016 };
5017 }
5018 
5019 //===----------------------------------------------------------------------===//
5020 // LValue Evaluation
5021 //
5022 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5023 // function designators (in C), decl references to void objects (in C), and
5024 // temporaries (if building with -Wno-address-of-temporary).
5025 //
5026 // LValue evaluation produces values comprising a base expression of one of the
5027 // following types:
5028 // - Declarations
5029 // * VarDecl
5030 // * FunctionDecl
5031 // - Literals
5032 // * CompoundLiteralExpr in C (and in global scope in C++)
5033 // * StringLiteral
5034 // * CXXTypeidExpr
5035 // * PredefinedExpr
5036 // * ObjCStringLiteralExpr
5037 // * ObjCEncodeExpr
5038 // * AddrLabelExpr
5039 // * BlockExpr
5040 // * CallExpr for a MakeStringConstant builtin
5041 // - Locals and temporaries
5042 // * MaterializeTemporaryExpr
5043 // * Any Expr, with a CallIndex indicating the function in which the temporary
5044 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
5045 // from the AST (FIXME).
5046 // * A MaterializeTemporaryExpr that has static storage duration, with no
5047 // CallIndex, for a lifetime-extended temporary.
5048 // plus an offset in bytes.
5049 //===----------------------------------------------------------------------===//
5050 namespace {
5051 class LValueExprEvaluator
5052  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5053 public:
5054  LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5055  LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5056 
5057  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5058  bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5059 
5060  bool VisitDeclRefExpr(const DeclRefExpr *E);
5061  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5062  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5063  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5064  bool VisitMemberExpr(const MemberExpr *E);
5065  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5066  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5067  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5068  bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5069  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5070  bool VisitUnaryDeref(const UnaryOperator *E);
5071  bool VisitUnaryReal(const UnaryOperator *E);
5072  bool VisitUnaryImag(const UnaryOperator *E);
5073  bool VisitUnaryPreInc(const UnaryOperator *UO) {
5074  return VisitUnaryPreIncDec(UO);
5075  }
5076  bool VisitUnaryPreDec(const UnaryOperator *UO) {
5077  return VisitUnaryPreIncDec(UO);
5078  }
5079  bool VisitBinAssign(const BinaryOperator *BO);
5080  bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5081 
5082  bool VisitCastExpr(const CastExpr *E) {
5083  switch (E->getCastKind()) {
5084  default:
5085  return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5086 
5087  case CK_LValueBitCast:
5088  this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5089  if (!Visit(E->getSubExpr()))
5090  return false;
5091  Result.Designator.setInvalid();
5092  return true;
5093 
5094  case CK_BaseToDerived:
5095  if (!Visit(E->getSubExpr()))
5096  return false;
5097  return HandleBaseToDerivedCast(Info, E, Result);
5098  }
5099  }
5100 };
5101 } // end anonymous namespace
5102 
5103 /// Evaluate an expression as an lvalue. This can be legitimately called on
5104 /// expressions which are not glvalues, in three cases:
5105 /// * function designators in C, and
5106 /// * "extern void" objects
5107 /// * @selector() expressions in Objective-C
5108 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5109  bool InvalidBaseOK) {
5110  assert(E->isGLValue() || E->getType()->isFunctionType() ||
5111  E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5112  return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5113 }
5114 
5115 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5116  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5117  return Success(FD);
5118  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5119  return VisitVarDecl(E, VD);
5120  if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5121  return Visit(BD->getBinding());
5122  return Error(E);
5123 }
5124 
5125 
5126 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5127 
5128  // If we are within a lambda's call operator, check whether the 'VD' referred
5129  // to within 'E' actually represents a lambda-capture that maps to a
5130  // data-member/field within the closure object, and if so, evaluate to the
5131  // field or what the field refers to.
5132  if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5133  if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5134  if (Info.checkingPotentialConstantExpression())
5135  return false;
5136  // Start with 'Result' referring to the complete closure object...
5137  Result = *Info.CurrentCall->This;
5138  // ... then update it to refer to the field of the closure object
5139  // that represents the capture.
5140  if (!HandleLValueMember(Info, E, Result, FD))
5141  return false;
5142  // And if the field is of reference type, update 'Result' to refer to what
5143  // the field refers to.
5144  if (FD->getType()->isReferenceType()) {
5145  APValue RVal;
5146  if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5147  RVal))
5148  return false;
5149  Result.setFrom(Info.Ctx, RVal);
5150  }
5151  return true;
5152  }
5153  }
5154  CallStackFrame *Frame = nullptr;
5155  if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5156  // Only if a local variable was declared in the function currently being
5157  // evaluated, do we expect to be able to find its value in the current
5158  // frame. (Otherwise it was likely declared in an enclosing context and
5159  // could either have a valid evaluatable value (for e.g. a constexpr
5160  // variable) or be ill-formed (and trigger an appropriate evaluation
5161  // diagnostic)).
5162  if (Info.CurrentCall->Callee &&
5163  Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5164  Frame = Info.CurrentCall;
5165  }
5166  }
5167 
5168  if (!VD->getType()->isReferenceType()) {
5169  if (Frame) {
5170  Result.set(VD, Frame->Index);
5171  return true;
5172  }
5173  return Success(VD);
5174  }
5175 
5176  APValue *V;
5177  if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5178  return false;
5179  if (V->isUninit()) {
5180  if (!Info.checkingPotentialConstantExpression())
5181  Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5182  return false;
5183  }
5184  return Success(*V, E);
5185 }
5186 
5187 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5188  const MaterializeTemporaryExpr *E) {
5189  // Walk through the expression to find the materialized temporary itself.
5190  SmallVector<const Expr *, 2> CommaLHSs;
5192  const Expr *Inner = E->GetTemporaryExpr()->
5193  skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5194 
5195  // If we passed any comma operators, evaluate their LHSs.
5196  for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5197  if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5198  return false;
5199 
5200  // A materialized temporary with static storage duration can appear within the
5201  // result of a constant expression evaluation, so we need to preserve its
5202  // value for use outside this evaluation.
5203  APValue *Value;
5204  if (E->getStorageDuration() == SD_Static) {
5205  Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5206  *Value = APValue();
5207  Result.set(E);
5208  } else {
5209  Value = &Info.CurrentCall->
5210  createTemporary(E, E->getStorageDuration() == SD_Automatic);
5211  Result.set(E, Info.CurrentCall->Index);
5212  }
5213 
5214  QualType Type = Inner->getType();
5215 
5216  // Materialize the temporary itself.
5217  if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5218  (E->getStorageDuration() == SD_Static &&
5219  !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5220  *Value = APValue();
5221  return false;
5222  }
5223 
5224  // Adjust our lvalue to refer to the desired subobject.
5225  for (unsigned I = Adjustments.size(); I != 0; /**/) {
5226  --I;
5227  switch (Adjustments[I].Kind) {
5229  if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5230  Type, Result))
5231  return false;
5232  Type = Adjustments[I].DerivedToBase.BasePath->getType();
5233  break;
5234 
5236  if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5237  return false;
5238  Type = Adjustments[I].Field->getType();
5239  break;
5240 
5242  if (!HandleMemberPointerAccess(this->Info, Type, Result,
5243  Adjustments[I].Ptr.RHS))
5244  return false;
5245  Type = Adjustments[I].Ptr.MPT->getPointeeType();
5246  break;
5247  }
5248  }
5249 
5250  return true;
5251 }
5252 
5253 bool
5254 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5255  assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5256  "lvalue compound literal in c++?");
5257  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5258  // only see this when folding in C, so there's no standard to follow here.
5259  return Success(E);
5260 }
5261 
5262 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5263  if (!E->isPotentiallyEvaluated())
5264  return Success(E);
5265 
5266  Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5267  << E->getExprOperand()->getType()
5268  << E->getExprOperand()->getSourceRange();
5269  return false;
5270 }
5271 
5272 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5273  return Success(E);
5274 }
5275 
5276 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5277  // Handle static data members.
5278  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5279  VisitIgnoredBaseExpression(E->getBase());
5280  return VisitVarDecl(E, VD);
5281  }
5282 
5283  // Handle static member functions.
5284  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5285  if (MD->isStatic()) {
5286  VisitIgnoredBaseExpression(E->getBase());
5287  return Success(MD);
5288  }
5289  }
5290 
5291  // Handle non-static data members.
5292  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5293 }
5294 
5295 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5296  // FIXME: Deal with vectors as array subscript bases.
5297  if (E->getBase()->getType()->isVectorType())
5298  return Error(E);
5299 
5300  bool Success = true;
5301  if (!evaluatePointer(E->getBase(), Result)) {
5302  if (!Info.noteFailure())
5303  return false;
5304  Success = false;
5305  }
5306 
5307  APSInt Index;
5308  if (!EvaluateInteger(E->getIdx(), Index, Info))
5309  return false;
5310 
5311  return Success &&
5312  HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5313 }
5314 
5315 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5316  return evaluatePointer(E->getSubExpr(), Result);
5317 }
5318 
5319 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5320  if (!Visit(E->getSubExpr()))
5321  return false;
5322  // __real is a no-op on scalar lvalues.
5323  if (E->getSubExpr()->getType()->isAnyComplexType())
5324  HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5325  return true;
5326 }
5327 
5328 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5329  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5330  "lvalue __imag__ on scalar?");
5331  if (!Visit(E->getSubExpr()))
5332  return false;
5333  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5334  return true;
5335 }
5336 
5337 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5338  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5339  return Error(UO);
5340 
5341  if (!this->Visit(UO->getSubExpr()))
5342  return false;
5343 
5344  return handleIncDec(
5345  this->Info, UO, Result, UO->getSubExpr()->getType(),
5346  UO->isIncrementOp(), nullptr);
5347 }
5348 
5349 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5350  const CompoundAssignOperator *CAO) {
5351  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5352  return Error(CAO);
5353 
5354  APValue RHS;
5355 
5356  // The overall lvalue result is the result of evaluating the LHS.
5357  if (!this->Visit(CAO->getLHS())) {
5358  if (Info.noteFailure())
5359  Evaluate(RHS, this->Info, CAO->getRHS());
5360  return false;
5361  }
5362 
5363  if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5364  return false;
5365 
5366  return handleCompoundAssignment(
5367  this->Info, CAO,
5368  Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5369  CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5370 }
5371 
5372 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5373  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5374  return Error(E);
5375 
5376  APValue NewVal;
5377 
5378  if (!this->Visit(E->getLHS())) {
5379  if (Info.noteFailure())
5380  Evaluate(NewVal, this->Info, E->getRHS());
5381  return false;
5382  }
5383 
5384  if (!Evaluate(NewVal, this->Info, E->getRHS()))
5385  return false;
5386 
5387  return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5388  NewVal);
5389 }
5390 
5391 //===----------------------------------------------------------------------===//
5392 // Pointer Evaluation
5393 //===----------------------------------------------------------------------===//
5394 
5395 /// \brief Attempts to compute the number of bytes available at the pointer
5396 /// returned by a function with the alloc_size attribute. Returns true if we
5397 /// were successful. Places an unsigned number into `Result`.
5398 ///
5399 /// This expects the given CallExpr to be a call to a function with an
5400 /// alloc_size attribute.
5402  const CallExpr *Call,
5403  llvm::APInt &Result) {
5404  const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5405 
5406  // alloc_size args are 1-indexed, 0 means not present.
5407  assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5408  unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5409  unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5410  if (Call->getNumArgs() <= SizeArgNo)
5411  return false;
5412 
5413  auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5414  if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5415  return false;
5416  if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5417  return false;
5418  Into = Into.zextOrSelf(BitsInSizeT);
5419  return true;
5420  };
5421 
5422  APSInt SizeOfElem;
5423  if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5424  return false;
5425 
5426  if (!AllocSize->getNumElemsParam()) {
5427  Result = std::move(SizeOfElem);
5428  return true;
5429  }
5430 
5431  APSInt NumberOfElems;
5432  // Argument numbers start at 1
5433  unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5434  if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5435  return false;
5436 
5437  bool Overflow;
5438  llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5439  if (Overflow)
5440  return false;
5441 
5442  Result = std::move(BytesAvailable);
5443  return true;
5444 }
5445 
5446 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5447 /// function.
5449  const LValue &LVal,
5450  llvm::APInt &Result) {
5451  assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5452  "Can't get the size of a non alloc_size function");
5453  const auto *Base = LVal.getLValueBase().get<const Expr *>();
5454  const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5455  return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5456 }
5457 
5458 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5459 /// a function with the alloc_size attribute. If it was possible to do so, this
5460 /// function will return true, make Result's Base point to said function call,
5461 /// and mark Result's Base as invalid.
5462 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5463  LValue &Result) {
5464  if (Base.isNull())
5465  return false;
5466 
5467  // Because we do no form of static analysis, we only support const variables.
5468  //
5469  // Additionally, we can't support parameters, nor can we support static
5470  // variables (in the latter case, use-before-assign isn't UB; in the former,
5471  // we have no clue what they'll be assigned to).
5472  const auto *VD =
5473  dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5474  if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5475  return false;
5476 
5477  const Expr *Init = VD->getAnyInitializer();
5478  if (!Init)
5479  return false;
5480 
5481  const Expr *E = Init->IgnoreParens();
5482  if (!tryUnwrapAllocSizeCall(E))
5483  return false;
5484 
5485  // Store E instead of E unwrapped so that the type of the LValue's base is
5486  // what the user wanted.
5487  Result.setInvalid(E);
5488 
5489  QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5490  Result.addUnsizedArray(Info, Pointee);
5491  return true;
5492 }
5493 
5494 namespace {
5495 class PointerExprEvaluator
5496  : public ExprEvaluatorBase<PointerExprEvaluator> {
5497  LValue &Result;
5498  bool InvalidBaseOK;
5499 
5500  bool Success(const Expr *E) {
5501  Result.set(E);
5502  return true;
5503  }
5504 
5505  bool evaluateLValue(const Expr *E, LValue &Result) {
5506  return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5507  }
5508 
5509  bool evaluatePointer(const Expr *E, LValue &Result) {
5510  return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5511  }
5512 
5513  bool visitNonBuiltinCallExpr(const CallExpr *E);
5514 public:
5515 
5516  PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5517  : ExprEvaluatorBaseTy(info), Result(Result),
5518  InvalidBaseOK(InvalidBaseOK) {}
5519 
5520  bool Success(const APValue &V, const Expr *E) {
5521  Result.setFrom(Info.Ctx, V);
5522  return true;
5523  }
5524  bool ZeroInitialization(const Expr *E) {
5525  auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5526  Result.setNull(E->getType(), TargetVal);
5527  return true;
5528  }
5529 
5530  bool VisitBinaryOperator(const BinaryOperator *E);
5531  bool VisitCastExpr(const CastExpr* E);
5532  bool VisitUnaryAddrOf(const UnaryOperator *E);
5533  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5534  { return Success(E); }
5535  bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5536  if (Info.noteFailure())
5537  EvaluateIgnoredValue(Info, E->getSubExpr());
5538  return Error(E);
5539  }
5540  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5541  { return Success(E); }
5542  bool VisitCallExpr(const CallExpr *E);
5543  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5544  bool VisitBlockExpr(const BlockExpr *E) {
5545  if (!E->getBlockDecl()->hasCaptures())
5546  return Success(E);
5547  return Error(E);
5548  }
5549  bool VisitCXXThisExpr(const CXXThisExpr *E) {
5550  // Can't look at 'this' when checking a potential constant expression.
5551  if (Info.checkingPotentialConstantExpression())
5552  return false;
5553  if (!Info.CurrentCall->This) {
5554  if (Info.getLangOpts().CPlusPlus11)
5555  Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5556  else
5557  Info.FFDiag(E);
5558  return false;
5559  }
5560  Result = *Info.CurrentCall->This;
5561  // If we are inside a lambda's call operator, the 'this' expression refers
5562  // to the enclosing '*this' object (either by value or reference) which is
5563  // either copied into the closure object's field that represents the '*this'
5564  // or refers to '*this'.
5565  if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5566  // Update 'Result' to refer to the data member/field of the closure object
5567  // that represents the '*this' capture.
5568  if (!HandleLValueMember(Info, E, Result,
5569  Info.CurrentCall->LambdaThisCaptureField))
5570  return false;
5571  // If we captured '*this' by reference, replace the field with its referent.
5572  if (Info.CurrentCall->LambdaThisCaptureField->getType()
5573  ->isPointerType()) {
5574  APValue RVal;
5575  if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5576  RVal))
5577  return false;
5578 
5579  Result.setFrom(Info.Ctx, RVal);
5580  }
5581  }
5582  return true;
5583  }
5584 
5585  // FIXME: Missing: @protocol, @selector
5586 };
5587 } // end anonymous namespace
5588 
5589 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5590  bool InvalidBaseOK) {
5591  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5592  return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5593 }
5594 
5595 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5596  if (E->getOpcode() != BO_Add &&
5597  E->getOpcode() != BO_Sub)
5598  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5599 
5600  const Expr *PExp = E->getLHS();
5601  const Expr *IExp = E->getRHS();
5602  if (IExp->getType()->isPointerType())
5603  std::swap(PExp, IExp);
5604 
5605  bool EvalPtrOK = evaluatePointer(PExp, Result);
5606  if (!EvalPtrOK && !Info.noteFailure())
5607  return false;
5608 
5609  llvm::APSInt Offset;
5610  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5611  return false;
5612 
5613  if (E->getOpcode() == BO_Sub)
5614  negateAsSigned(Offset);
5615 
5616  QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5617  return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5618 }
5619 
5620 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5621  return evaluateLValue(E->getSubExpr(), Result);
5622 }
5623 
5624 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5625  const Expr* SubExpr = E->getSubExpr();
5626 
5627  switch (E->getCastKind()) {
5628  default:
5629  break;
5630 
5631  case CK_BitCast:
5632  case CK_CPointerToObjCPointerCast:
5633  case CK_BlockPointerToObjCPointerCast:
5634  case CK_AnyPointerToBlockPointerCast:
5635  case CK_AddressSpaceConversion:
5636  if (!Visit(SubExpr))
5637  return false;
5638  // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5639  // permitted in constant expressions in C++11. Bitcasts from cv void* are
5640  // also static_casts, but we disallow them as a resolution to DR1312.
5641  if (!E->getType()->isVoidPointerType()) {
5642  Result.Designator.setInvalid();
5643  if (SubExpr->getType()->isVoidPointerType())
5644  CCEDiag(E, diag::note_constexpr_invalid_cast)
5645  << 3 << SubExpr->getType();
5646  else
5647  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5648  }
5649  if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5650  ZeroInitialization(E);
5651  return true;
5652 
5653  case CK_DerivedToBase:
5654  case CK_UncheckedDerivedToBase:
5655  if (!evaluatePointer(E->getSubExpr(), Result))
5656  return false;
5657  if (!Result.Base && Result.Offset.isZero())
5658  return true;
5659 
5660  // Now figure out the necessary offset to add to the base LV to get from
5661  // the derived class to the base class.
5662  return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5663  castAs<PointerType>()->getPointeeType(),
5664  Result);
5665 
5666  case CK_BaseToDerived:
5667  if (!Visit(E->getSubExpr()))
5668  return false;
5669  if (!Result.Base && Result.Offset.isZero())
5670  return true;
5671  return HandleBaseToDerivedCast(Info, E, Result);
5672 
5673  case CK_NullToPointer:
5674  VisitIgnoredValue(E->getSubExpr());
5675  return ZeroInitialization(E);
5676 
5677  case CK_IntegralToPointer: {
5678  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5679 
5680  APValue Value;
5681  if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5682  break;
5683 
5684  if (Value.isInt()) {
5685  unsigned Size = Info.Ctx.getTypeSize(E->getType());
5686  uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5687  Result.Base = (Expr*)nullptr;
5688  Result.InvalidBase = false;
5689  Result.Offset = CharUnits::fromQuantity(N);
5690  Result.CallIndex = 0;
5691  Result.Designator.setInvalid();
5692  Result.IsNullPtr = false;
5693  return true;
5694  } else {
5695  // Cast is of an lvalue, no need to change value.
5696  Result.setFrom(Info.Ctx, Value);
5697  return true;
5698  }
5699  }
5700  case CK_ArrayToPointerDecay:
5701  if (SubExpr->isGLValue()) {
5702  if (!evaluateLValue(SubExpr, Result))
5703  return false;
5704  } else {
5705  Result.set(SubExpr, Info.CurrentCall->Index);
5706  if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5707  Info, Result, SubExpr))
5708  return false;
5709  }
5710  // The result is a pointer to the first element of the array.
5711  if (const ConstantArrayType *CAT
5712  = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5713  Result.addArray(Info, E, CAT);
5714  else
5715  Result.Designator.setInvalid();
5716  return true;
5717 
5718  case CK_FunctionToPointerDecay:
5719  return evaluateLValue(SubExpr, Result);
5720 
5721  case CK_LValueToRValue: {
5722  LValue LVal;
5723  if (!evaluateLValue(E->getSubExpr(), LVal))
5724  return false;
5725 
5726  APValue RVal;
5727  // Note, we use the subexpression's type in order to retain cv-qualifiers.
5728  if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5729  LVal, RVal))
5730  return InvalidBaseOK &&
5731  evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5732  return Success(RVal, E);
5733  }
5734  }
5735 
5736  return ExprEvaluatorBaseTy::VisitCastExpr(E);
5737 }
5738 
5739 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5740  // C++ [expr.alignof]p3:
5741  // When alignof is applied to a reference type, the result is the
5742  // alignment of the referenced type.
5743  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5744  T = Ref->getPointeeType();
5745 
5746  // __alignof is defined to return the preferred alignment.
5747  if (T.getQualifiers().hasUnaligned())
5748  return CharUnits::One();
5749  return Info.Ctx.toCharUnitsFromBits(
5750  Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5751 }
5752 
5753 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5754  E = E->IgnoreParens();
5755 
5756  // The kinds of expressions that we have special-case logic here for
5757  // should be kept up to date with the special checks for those
5758  // expressions in Sema.
5759 
5760  // alignof decl is always accepted, even if it doesn't make sense: we default
5761  // to 1 in those cases.
5762  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5763  return Info.Ctx.getDeclAlign(DRE->getDecl(),
5764  /*RefAsPointee*/true);
5765 
5766  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5767  return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5768  /*RefAsPointee*/true);
5769 
5770  return GetAlignOfType(Info, E->getType());
5771 }
5772 
5773 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5774 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5775  if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5776  return true;
5777 
5778  if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5779  return false;
5780 
5781  Result.setInvalid(E);
5782  QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5783  Result.addUnsizedArray(Info, PointeeTy);
5784  return true;
5785 }
5786 
5787 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5788  if (IsStringLiteralCall(E))
5789  return Success(E);
5790 
5791  if (unsigned BuiltinOp = E->getBuiltinCallee())
5792  return VisitBuiltinCallExpr(E, BuiltinOp);
5793 
5794  return visitNonBuiltinCallExpr(E);
5795 }
5796 
5797 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5798  unsigned BuiltinOp) {
5799  switch (BuiltinOp) {
5800  case Builtin::BI__builtin_addressof:
5801  return evaluateLValue(E->getArg(0), Result);
5802  case Builtin::BI__builtin_assume_aligned: {
5803  // We need to be very careful here because: if the pointer does not have the
5804  // asserted alignment, then the behavior is undefined, and undefined
5805  // behavior is non-constant.
5806  if (!evaluatePointer(E->getArg(0), Result))
5807  return false;
5808 
5809  LValue OffsetResult(Result);
5810  APSInt Alignment;
5811  if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5812  return false;
5813  CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5814 
5815  if (E->getNumArgs() > 2) {
5816  APSInt Offset;
5817  if (!EvaluateInteger(E->getArg(2), Offset, Info))
5818  return false;
5819 
5820  int64_t AdditionalOffset = -Offset.getZExtValue();
5821  OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5822  }
5823 
5824  // If there is a base object, then it must have the correct alignment.
5825  if (OffsetResult.Base) {
5826  CharUnits BaseAlignment;
5827  if (const ValueDecl *VD =
5828  OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5829  BaseAlignment = Info.Ctx.getDeclAlign(VD);
5830  } else {
5831  BaseAlignment =
5832  GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5833  }
5834 
5835  if (BaseAlignment < Align) {
5836  Result.Designator.setInvalid();
5837  // FIXME: Add support to Diagnostic for long / long long.
5838  CCEDiag(E->getArg(0),
5839  diag::note_constexpr_baa_insufficient_alignment) << 0
5840  << (unsigned)BaseAlignment.getQuantity()
5841  << (unsigned)Align.getQuantity();
5842  return false;
5843  }
5844  }
5845 
5846  // The offset must also have the correct alignment.
5847  if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5848  Result.Designator.setInvalid();
5849 
5850  (OffsetResult.Base
5851  ? CCEDiag(E->getArg(0),
5852  diag::note_constexpr_baa_insufficient_alignment) << 1
5853  : CCEDiag(E->getArg(0),
5854  diag::note_constexpr_baa_value_insufficient_alignment))
5855  << (int)OffsetResult.Offset.getQuantity()
5856  << (unsigned)Align.getQuantity();
5857  return false;
5858  }
5859 
5860  return true;
5861  }
5862 
5863  case Builtin::BIstrchr:
5864  case Builtin::BIwcschr:
5865  case Builtin::BImemchr:
5866  case Builtin::BIwmemchr:
5867  if (Info.getLangOpts().CPlusPlus11)
5868  Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5869  << /*isConstexpr*/0 << /*isConstructor*/0
5870  << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5871  else
5872  Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5873  // Fall through.
5874  case Builtin::BI__builtin_strchr:
5875  case Builtin::BI__builtin_wcschr:
5876  case Builtin::BI__builtin_memchr:
5877  case Builtin::BI__builtin_char_memchr:
5878  case Builtin::BI__builtin_wmemchr: {
5879  if (!Visit(E->getArg(0)))
5880  return false;
5881  APSInt Desired;
5882  if (!EvaluateInteger(E->getArg(1), Desired, Info))
5883  return false;
5884  uint64_t MaxLength = uint64_t(-1);
5885  if (BuiltinOp != Builtin::BIstrchr &&
5886  BuiltinOp != Builtin::BIwcschr &&
5887  BuiltinOp != Builtin::BI__builtin_strchr &&
5888  BuiltinOp != Builtin::BI__builtin_wcschr) {
5889  APSInt N;
5890  if (!EvaluateInteger(E->getArg(2), N, Info))
5891  return false;
5892  MaxLength = N.getExtValue();
5893  }
5894 
5895  QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5896 
5897  // Figure out what value we're actually looking for (after converting to
5898  // the corresponding unsigned type if necessary).
5899  uint64_t DesiredVal;
5900  bool StopAtNull = false;
5901  switch (BuiltinOp) {
5902  case Builtin::BIstrchr:
5903  case Builtin::BI__builtin_strchr:
5904  // strchr compares directly to the passed integer, and therefore
5905  // always fails if given an int that is not a char.
5906  if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5907  E->getArg(1)->getType(),
5908  Desired),
5909  Desired))
5910  return ZeroInitialization(E);
5911  StopAtNull = true;
5912  // Fall through.
5913  case Builtin::BImemchr:
5914  case Builtin::BI__builtin_memchr:
5915  case Builtin::BI__builtin_char_memchr:
5916  // memchr compares by converting both sides to unsigned char. That's also
5917  // correct for strchr if we get this far (to cope with plain char being
5918  // unsigned in the strchr case).
5919  DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5920  break;
5921 
5922  case Builtin::BIwcschr:
5923  case Builtin::BI__builtin_wcschr:
5924  StopAtNull = true;
5925  // Fall through.
5926  case Builtin::BIwmemchr:
5927  case Builtin::BI__builtin_wmemchr:
5928  // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5929  DesiredVal = Desired.getZExtValue();
5930  break;
5931  }
5932 
5933  for (; MaxLength; --MaxLength) {
5934  APValue Char;
5935  if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5936  !Char.isInt())
5937  return false;
5938  if (Char.getInt().getZExtValue() == DesiredVal)
5939  return true;
5940  if (StopAtNull && !Char.getInt())
5941  break;
5942  if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5943  return false;
5944  }
5945  // Not found: return nullptr.
5946  return ZeroInitialization(E);
5947  }
5948 
5949  default:
5950  return visitNonBuiltinCallExpr(E);
5951  }
5952 }
5953 
5954 //===----------------------------------------------------------------------===//
5955 // Member Pointer Evaluation
5956 //===----------------------------------------------------------------------===//
5957 
5958 namespace {
5959 class MemberPointerExprEvaluator
5960  : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5961  MemberPtr &Result;
5962 
5963  bool Success(const ValueDecl *D) {
5964  Result = MemberPtr(D);
5965  return true;
5966  }
5967 public:
5968 
5969  MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5970  : ExprEvaluatorBaseTy(Info), Result(Result) {}
5971 
5972  bool Success(const APValue &V, const Expr *E) {
5973  Result.setFrom(V);
5974  return true;
5975  }
5976  bool ZeroInitialization(const Expr *E) {
5977  return Success((const ValueDecl*)nullptr);
5978  }
5979 
5980  bool VisitCastExpr(const CastExpr *E);
5981  bool VisitUnaryAddrOf(const UnaryOperator *E);
5982 };
5983 } // end anonymous namespace
5984 
5985 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5986  EvalInfo &Info) {
5987  assert(E->isRValue() && E->getType()->isMemberPointerType());
5988  return MemberPointerExprEvaluator