• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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"
38 #include "clang/AST/ASTDiagnostic.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/Expr.h"
41 #include "clang/AST/RecordLayout.h"
42 #include "clang/AST/StmtVisitor.h"
43 #include "clang/AST/TypeLoc.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.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 
getType(APValue::LValueBase B)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)) {
73       SmallVector<const Expr *, 2> CommaLHSs;
74       SmallVector<SubobjectAdjustment, 2> Adjustments;
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.
80       if (Inner != Temp)
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
getAsBaseOrMember(APValue::LValuePathEntry E)90   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91     APValue::BaseOrMemberType Value;
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.
getAsField(APValue::LValuePathEntry E)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.
getAsBaseClass(APValue::LValuePathEntry E)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.
isVirtualBaseClass(APValue::LValuePathEntry E)108   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109     return getAsBaseOrMember(E).getInt();
110   }
111 
112   /// Find the path length and type of the most-derived subobject in the given
113   /// path, and find the size of the containing array, if any.
114   static
findMostDerivedSubobject(ASTContext & Ctx,QualType Base,ArrayRef<APValue::LValuePathEntry> Path,uint64_t & ArraySize,QualType & Type)115   unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116                                     ArrayRef<APValue::LValuePathEntry> Path,
117                                     uint64_t &ArraySize, QualType &Type) {
118     unsigned MostDerivedLength = 0;
119     Type = Base;
120     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
121       if (Type->isArrayType()) {
122         const ConstantArrayType *CAT =
123           cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124         Type = CAT->getElementType();
125         ArraySize = CAT->getSize().getZExtValue();
126         MostDerivedLength = I + 1;
127       } else if (Type->isAnyComplexType()) {
128         const ComplexType *CT = Type->castAs<ComplexType>();
129         Type = CT->getElementType();
130         ArraySize = 2;
131         MostDerivedLength = I + 1;
132       } else if (const FieldDecl *FD = getAsField(Path[I])) {
133         Type = FD->getType();
134         ArraySize = 0;
135         MostDerivedLength = I + 1;
136       } else {
137         // Path[I] describes a base class.
138         ArraySize = 0;
139       }
140     }
141     return MostDerivedLength;
142   }
143 
144   // The order of this enum is important for diagnostics.
145   enum CheckSubobjectKind {
146     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
147     CSK_This, CSK_Real, CSK_Imag
148   };
149 
150   /// A path from a glvalue to a subobject of that glvalue.
151   struct SubobjectDesignator {
152     /// True if the subobject was named in a manner not supported by C++11. Such
153     /// lvalues can still be folded, but they are not core constant expressions
154     /// and we cannot perform lvalue-to-rvalue conversions on them.
155     bool Invalid : 1;
156 
157     /// Is this a pointer one past the end of an object?
158     bool IsOnePastTheEnd : 1;
159 
160     /// The length of the path to the most-derived object of which this is a
161     /// subobject.
162     unsigned MostDerivedPathLength : 30;
163 
164     /// The size of the array of which the most-derived object is an element, or
165     /// 0 if the most-derived object is not an array element.
166     uint64_t MostDerivedArraySize;
167 
168     /// The type of the most derived object referred to by this address.
169     QualType MostDerivedType;
170 
171     typedef APValue::LValuePathEntry PathEntry;
172 
173     /// The entries on the path from the glvalue to the designated subobject.
174     SmallVector<PathEntry, 8> Entries;
175 
SubobjectDesignator__anona626307c0111::SubobjectDesignator176     SubobjectDesignator() : Invalid(true) {}
177 
SubobjectDesignator__anona626307c0111::SubobjectDesignator178     explicit SubobjectDesignator(QualType T)
179       : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180         MostDerivedArraySize(0), MostDerivedType(T) {}
181 
SubobjectDesignator__anona626307c0111::SubobjectDesignator182     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183       : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184         MostDerivedPathLength(0), MostDerivedArraySize(0) {
185       if (!Invalid) {
186         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
187         ArrayRef<PathEntry> VEntries = V.getLValuePath();
188         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189         if (V.getLValueBase())
190           MostDerivedPathLength =
191               findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192                                        V.getLValuePath(), MostDerivedArraySize,
193                                        MostDerivedType);
194       }
195     }
196 
setInvalid__anona626307c0111::SubobjectDesignator197     void setInvalid() {
198       Invalid = true;
199       Entries.clear();
200     }
201 
202     /// Determine whether this is a one-past-the-end pointer.
isOnePastTheEnd__anona626307c0111::SubobjectDesignator203     bool isOnePastTheEnd() const {
204       assert(!Invalid);
205       if (IsOnePastTheEnd)
206         return true;
207       if (MostDerivedArraySize &&
208           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
209         return true;
210       return false;
211     }
212 
213     /// Check that this refers to a valid subobject.
isValidSubobject__anona626307c0111::SubobjectDesignator214     bool isValidSubobject() const {
215       if (Invalid)
216         return false;
217       return !isOnePastTheEnd();
218     }
219     /// Check that this refers to a valid subobject, and if not, produce a
220     /// relevant diagnostic and set the designator as invalid.
221     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
222 
223     /// Update this designator to refer to the first element within this array.
addArrayUnchecked__anona626307c0111::SubobjectDesignator224     void addArrayUnchecked(const ConstantArrayType *CAT) {
225       PathEntry Entry;
226       Entry.ArrayIndex = 0;
227       Entries.push_back(Entry);
228 
229       // This is a most-derived object.
230       MostDerivedType = CAT->getElementType();
231       MostDerivedArraySize = CAT->getSize().getZExtValue();
232       MostDerivedPathLength = Entries.size();
233     }
234     /// Update this designator to refer to the given base or member of this
235     /// object.
addDeclUnchecked__anona626307c0111::SubobjectDesignator236     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
237       PathEntry Entry;
238       APValue::BaseOrMemberType Value(D, Virtual);
239       Entry.BaseOrMember = Value.getOpaqueValue();
240       Entries.push_back(Entry);
241 
242       // If this isn't a base class, it's a new most-derived object.
243       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
244         MostDerivedType = FD->getType();
245         MostDerivedArraySize = 0;
246         MostDerivedPathLength = Entries.size();
247       }
248     }
249     /// Update this designator to refer to the given complex component.
addComplexUnchecked__anona626307c0111::SubobjectDesignator250     void addComplexUnchecked(QualType EltTy, bool Imag) {
251       PathEntry Entry;
252       Entry.ArrayIndex = Imag;
253       Entries.push_back(Entry);
254 
255       // This is technically a most-derived object, though in practice this
256       // is unlikely to matter.
257       MostDerivedType = EltTy;
258       MostDerivedArraySize = 2;
259       MostDerivedPathLength = Entries.size();
260     }
261     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
262     /// Add N to the address of this subobject.
adjustIndex__anona626307c0111::SubobjectDesignator263     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
264       if (Invalid) return;
265       if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
266         Entries.back().ArrayIndex += N;
267         if (Entries.back().ArrayIndex > MostDerivedArraySize) {
268           diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
269           setInvalid();
270         }
271         return;
272       }
273       // [expr.add]p4: For the purposes of these operators, a pointer to a
274       // nonarray object behaves the same as a pointer to the first element of
275       // an array of length one with the type of the object as its element type.
276       if (IsOnePastTheEnd && N == (uint64_t)-1)
277         IsOnePastTheEnd = false;
278       else if (!IsOnePastTheEnd && N == 1)
279         IsOnePastTheEnd = true;
280       else if (N != 0) {
281         diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
282         setInvalid();
283       }
284     }
285   };
286 
287   /// A stack frame in the constexpr call stack.
288   struct CallStackFrame {
289     EvalInfo &Info;
290 
291     /// Parent - The caller of this stack frame.
292     CallStackFrame *Caller;
293 
294     /// CallLoc - The location of the call expression for this call.
295     SourceLocation CallLoc;
296 
297     /// Callee - The function which was called.
298     const FunctionDecl *Callee;
299 
300     /// Index - The call index of this call.
301     unsigned Index;
302 
303     /// This - The binding for the this pointer in this call, if any.
304     const LValue *This;
305 
306     /// Arguments - Parameter bindings for this function call, indexed by
307     /// parameters' function scope indices.
308     APValue *Arguments;
309 
310     // Note that we intentionally use std::map here so that references to
311     // values are stable.
312     typedef std::map<const void*, APValue> MapTy;
313     typedef MapTy::const_iterator temp_iterator;
314     /// Temporaries - Temporary lvalues materialized within this stack frame.
315     MapTy Temporaries;
316 
317     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
318                    const FunctionDecl *Callee, const LValue *This,
319                    APValue *Arguments);
320     ~CallStackFrame();
321 
getTemporary__anona626307c0111::CallStackFrame322     APValue *getTemporary(const void *Key) {
323       MapTy::iterator I = Temporaries.find(Key);
324       return I == Temporaries.end() ? nullptr : &I->second;
325     }
326     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
327   };
328 
329   /// Temporarily override 'this'.
330   class ThisOverrideRAII {
331   public:
ThisOverrideRAII(CallStackFrame & Frame,const LValue * NewThis,bool Enable)332     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
333         : Frame(Frame), OldThis(Frame.This) {
334       if (Enable)
335         Frame.This = NewThis;
336     }
~ThisOverrideRAII()337     ~ThisOverrideRAII() {
338       Frame.This = OldThis;
339     }
340   private:
341     CallStackFrame &Frame;
342     const LValue *OldThis;
343   };
344 
345   /// A partial diagnostic which we might know in advance that we are not going
346   /// to emit.
347   class OptionalDiagnostic {
348     PartialDiagnostic *Diag;
349 
350   public:
OptionalDiagnostic(PartialDiagnostic * Diag=nullptr)351     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
352       : Diag(Diag) {}
353 
354     template<typename T>
operator <<(const T & v)355     OptionalDiagnostic &operator<<(const T &v) {
356       if (Diag)
357         *Diag << v;
358       return *this;
359     }
360 
operator <<(const APSInt & I)361     OptionalDiagnostic &operator<<(const APSInt &I) {
362       if (Diag) {
363         SmallVector<char, 32> Buffer;
364         I.toString(Buffer);
365         *Diag << StringRef(Buffer.data(), Buffer.size());
366       }
367       return *this;
368     }
369 
operator <<(const APFloat & F)370     OptionalDiagnostic &operator<<(const APFloat &F) {
371       if (Diag) {
372         // FIXME: Force the precision of the source value down so we don't
373         // print digits which are usually useless (we don't really care here if
374         // we truncate a digit by accident in edge cases).  Ideally,
375         // APFloat::toString would automatically print the shortest
376         // representation which rounds to the correct value, but it's a bit
377         // tricky to implement.
378         unsigned precision =
379             llvm::APFloat::semanticsPrecision(F.getSemantics());
380         precision = (precision * 59 + 195) / 196;
381         SmallVector<char, 32> Buffer;
382         F.toString(Buffer, precision);
383         *Diag << StringRef(Buffer.data(), Buffer.size());
384       }
385       return *this;
386     }
387   };
388 
389   /// A cleanup, and a flag indicating whether it is lifetime-extended.
390   class Cleanup {
391     llvm::PointerIntPair<APValue*, 1, bool> Value;
392 
393   public:
Cleanup(APValue * Val,bool IsLifetimeExtended)394     Cleanup(APValue *Val, bool IsLifetimeExtended)
395         : Value(Val, IsLifetimeExtended) {}
396 
isLifetimeExtended() const397     bool isLifetimeExtended() const { return Value.getInt(); }
endLifetime()398     void endLifetime() {
399       *Value.getPointer() = APValue();
400     }
401   };
402 
403   /// EvalInfo - This is a private struct used by the evaluator to capture
404   /// information about a subexpression as it is folded.  It retains information
405   /// about the AST context, but also maintains information about the folded
406   /// expression.
407   ///
408   /// If an expression could be evaluated, it is still possible it is not a C
409   /// "integer constant expression" or constant expression.  If not, this struct
410   /// captures information about how and why not.
411   ///
412   /// One bit of information passed *into* the request for constant folding
413   /// indicates whether the subexpression is "evaluated" or not according to C
414   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
415   /// evaluate the expression regardless of what the RHS is, but C only allows
416   /// certain things in certain situations.
417   struct EvalInfo {
418     ASTContext &Ctx;
419 
420     /// EvalStatus - Contains information about the evaluation.
421     Expr::EvalStatus &EvalStatus;
422 
423     /// CurrentCall - The top of the constexpr call stack.
424     CallStackFrame *CurrentCall;
425 
426     /// CallStackDepth - The number of calls in the call stack right now.
427     unsigned CallStackDepth;
428 
429     /// NextCallIndex - The next call index to assign.
430     unsigned NextCallIndex;
431 
432     /// StepsLeft - The remaining number of evaluation steps we're permitted
433     /// to perform. This is essentially a limit for the number of statements
434     /// we will evaluate.
435     unsigned StepsLeft;
436 
437     /// BottomFrame - The frame in which evaluation started. This must be
438     /// initialized after CurrentCall and CallStackDepth.
439     CallStackFrame BottomFrame;
440 
441     /// A stack of values whose lifetimes end at the end of some surrounding
442     /// evaluation frame.
443     llvm::SmallVector<Cleanup, 16> CleanupStack;
444 
445     /// EvaluatingDecl - This is the declaration whose initializer is being
446     /// evaluated, if any.
447     APValue::LValueBase EvaluatingDecl;
448 
449     /// EvaluatingDeclValue - This is the value being constructed for the
450     /// declaration whose initializer is being evaluated, if any.
451     APValue *EvaluatingDeclValue;
452 
453     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
454     /// notes attached to it will also be stored, otherwise they will not be.
455     bool HasActiveDiagnostic;
456 
457     enum EvaluationMode {
458       /// Evaluate as a constant expression. Stop if we find that the expression
459       /// is not a constant expression.
460       EM_ConstantExpression,
461 
462       /// Evaluate as a potential constant expression. Keep going if we hit a
463       /// construct that we can't evaluate yet (because we don't yet know the
464       /// value of something) but stop if we hit something that could never be
465       /// a constant expression.
466       EM_PotentialConstantExpression,
467 
468       /// Fold the expression to a constant. Stop if we hit a side-effect that
469       /// we can't model.
470       EM_ConstantFold,
471 
472       /// Evaluate the expression looking for integer overflow and similar
473       /// issues. Don't worry about side-effects, and try to visit all
474       /// subexpressions.
475       EM_EvaluateForOverflow,
476 
477       /// Evaluate in any way we know how. Don't worry about side-effects that
478       /// can't be modeled.
479       EM_IgnoreSideEffects,
480 
481       /// Evaluate as a constant expression. Stop if we find that the expression
482       /// is not a constant expression. Some expressions can be retried in the
483       /// optimizer if we don't constant fold them here, but in an unevaluated
484       /// context we try to fold them immediately since the optimizer never
485       /// gets a chance to look at it.
486       EM_ConstantExpressionUnevaluated,
487 
488       /// Evaluate as a potential constant expression. Keep going if we hit a
489       /// construct that we can't evaluate yet (because we don't yet know the
490       /// value of something) but stop if we hit something that could never be
491       /// a constant expression. Some expressions can be retried in the
492       /// optimizer if we don't constant fold them here, but in an unevaluated
493       /// context we try to fold them immediately since the optimizer never
494       /// gets a chance to look at it.
495       EM_PotentialConstantExpressionUnevaluated
496     } EvalMode;
497 
498     /// Are we checking whether the expression is a potential constant
499     /// expression?
checkingPotentialConstantExpression__anona626307c0111::EvalInfo500     bool checkingPotentialConstantExpression() const {
501       return EvalMode == EM_PotentialConstantExpression ||
502              EvalMode == EM_PotentialConstantExpressionUnevaluated;
503     }
504 
505     /// Are we checking an expression for overflow?
506     // FIXME: We should check for any kind of undefined or suspicious behavior
507     // in such constructs, not just overflow.
checkingForOverflow__anona626307c0111::EvalInfo508     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
509 
EvalInfo__anona626307c0111::EvalInfo510     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
511       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
512         CallStackDepth(0), NextCallIndex(1),
513         StepsLeft(getLangOpts().ConstexprStepLimit),
514         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
515         EvaluatingDecl((const ValueDecl *)nullptr),
516         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
517         EvalMode(Mode) {}
518 
setEvaluatingDecl__anona626307c0111::EvalInfo519     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
520       EvaluatingDecl = Base;
521       EvaluatingDeclValue = &Value;
522     }
523 
getLangOpts__anona626307c0111::EvalInfo524     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
525 
CheckCallLimit__anona626307c0111::EvalInfo526     bool CheckCallLimit(SourceLocation Loc) {
527       // Don't perform any constexpr calls (other than the call we're checking)
528       // when checking a potential constant expression.
529       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
530         return false;
531       if (NextCallIndex == 0) {
532         // NextCallIndex has wrapped around.
533         Diag(Loc, diag::note_constexpr_call_limit_exceeded);
534         return false;
535       }
536       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
537         return true;
538       Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
539         << getLangOpts().ConstexprCallDepth;
540       return false;
541     }
542 
getCallFrame__anona626307c0111::EvalInfo543     CallStackFrame *getCallFrame(unsigned CallIndex) {
544       assert(CallIndex && "no call index in getCallFrame");
545       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
546       // be null in this loop.
547       CallStackFrame *Frame = CurrentCall;
548       while (Frame->Index > CallIndex)
549         Frame = Frame->Caller;
550       return (Frame->Index == CallIndex) ? Frame : nullptr;
551     }
552 
nextStep__anona626307c0111::EvalInfo553     bool nextStep(const Stmt *S) {
554       if (!StepsLeft) {
555         Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
556         return false;
557       }
558       --StepsLeft;
559       return true;
560     }
561 
562   private:
563     /// Add a diagnostic to the diagnostics list.
addDiag__anona626307c0111::EvalInfo564     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
565       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
566       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
567       return EvalStatus.Diag->back().second;
568     }
569 
570     /// Add notes containing a call stack to the current point of evaluation.
571     void addCallStack(unsigned Limit);
572 
573   public:
574     /// Diagnose that the evaluation cannot be folded.
Diag__anona626307c0111::EvalInfo575     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
576                               = diag::note_invalid_subexpr_in_const_expr,
577                             unsigned ExtraNotes = 0) {
578       if (EvalStatus.Diag) {
579         // If we have a prior diagnostic, it will be noting that the expression
580         // isn't a constant expression. This diagnostic is more important,
581         // unless we require this evaluation to produce a constant expression.
582         //
583         // FIXME: We might want to show both diagnostics to the user in
584         // EM_ConstantFold mode.
585         if (!EvalStatus.Diag->empty()) {
586           switch (EvalMode) {
587           case EM_ConstantFold:
588           case EM_IgnoreSideEffects:
589           case EM_EvaluateForOverflow:
590             if (!EvalStatus.HasSideEffects)
591               break;
592             // We've had side-effects; we want the diagnostic from them, not
593             // some later problem.
594           case EM_ConstantExpression:
595           case EM_PotentialConstantExpression:
596           case EM_ConstantExpressionUnevaluated:
597           case EM_PotentialConstantExpressionUnevaluated:
598             HasActiveDiagnostic = false;
599             return OptionalDiagnostic();
600           }
601         }
602 
603         unsigned CallStackNotes = CallStackDepth - 1;
604         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
605         if (Limit)
606           CallStackNotes = std::min(CallStackNotes, Limit + 1);
607         if (checkingPotentialConstantExpression())
608           CallStackNotes = 0;
609 
610         HasActiveDiagnostic = true;
611         EvalStatus.Diag->clear();
612         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
613         addDiag(Loc, DiagId);
614         if (!checkingPotentialConstantExpression())
615           addCallStack(Limit);
616         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
617       }
618       HasActiveDiagnostic = false;
619       return OptionalDiagnostic();
620     }
621 
Diag__anona626307c0111::EvalInfo622     OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
623                               = diag::note_invalid_subexpr_in_const_expr,
624                             unsigned ExtraNotes = 0) {
625       if (EvalStatus.Diag)
626         return Diag(E->getExprLoc(), DiagId, ExtraNotes);
627       HasActiveDiagnostic = false;
628       return OptionalDiagnostic();
629     }
630 
631     /// Diagnose that the evaluation does not produce a C++11 core constant
632     /// expression.
633     ///
634     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
635     /// EM_PotentialConstantExpression mode and we produce one of these.
636     template<typename LocArg>
CCEDiag__anona626307c0111::EvalInfo637     OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
638                                  = diag::note_invalid_subexpr_in_const_expr,
639                                unsigned ExtraNotes = 0) {
640       // Don't override a previous diagnostic. Don't bother collecting
641       // diagnostics if we're evaluating for overflow.
642       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
643         HasActiveDiagnostic = false;
644         return OptionalDiagnostic();
645       }
646       return Diag(Loc, DiagId, ExtraNotes);
647     }
648 
649     /// Add a note to a prior diagnostic.
Note__anona626307c0111::EvalInfo650     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
651       if (!HasActiveDiagnostic)
652         return OptionalDiagnostic();
653       return OptionalDiagnostic(&addDiag(Loc, DiagId));
654     }
655 
656     /// Add a stack of notes to a prior diagnostic.
addNotes__anona626307c0111::EvalInfo657     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
658       if (HasActiveDiagnostic) {
659         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
660                                 Diags.begin(), Diags.end());
661       }
662     }
663 
664     /// Should we continue evaluation after encountering a side-effect that we
665     /// couldn't model?
keepEvaluatingAfterSideEffect__anona626307c0111::EvalInfo666     bool keepEvaluatingAfterSideEffect() {
667       switch (EvalMode) {
668       case EM_PotentialConstantExpression:
669       case EM_PotentialConstantExpressionUnevaluated:
670       case EM_EvaluateForOverflow:
671       case EM_IgnoreSideEffects:
672         return true;
673 
674       case EM_ConstantExpression:
675       case EM_ConstantExpressionUnevaluated:
676       case EM_ConstantFold:
677         return false;
678       }
679       llvm_unreachable("Missed EvalMode case");
680     }
681 
682     /// Note that we have had a side-effect, and determine whether we should
683     /// keep evaluating.
noteSideEffect__anona626307c0111::EvalInfo684     bool noteSideEffect() {
685       EvalStatus.HasSideEffects = true;
686       return keepEvaluatingAfterSideEffect();
687     }
688 
689     /// Should we continue evaluation as much as possible after encountering a
690     /// construct which can't be reduced to a value?
keepEvaluatingAfterFailure__anona626307c0111::EvalInfo691     bool keepEvaluatingAfterFailure() {
692       if (!StepsLeft)
693         return false;
694 
695       switch (EvalMode) {
696       case EM_PotentialConstantExpression:
697       case EM_PotentialConstantExpressionUnevaluated:
698       case EM_EvaluateForOverflow:
699         return true;
700 
701       case EM_ConstantExpression:
702       case EM_ConstantExpressionUnevaluated:
703       case EM_ConstantFold:
704       case EM_IgnoreSideEffects:
705         return false;
706       }
707       llvm_unreachable("Missed EvalMode case");
708     }
709   };
710 
711   /// Object used to treat all foldable expressions as constant expressions.
712   struct FoldConstant {
713     EvalInfo &Info;
714     bool Enabled;
715     bool HadNoPriorDiags;
716     EvalInfo::EvaluationMode OldMode;
717 
FoldConstant__anona626307c0111::FoldConstant718     explicit FoldConstant(EvalInfo &Info, bool Enabled)
719       : Info(Info),
720         Enabled(Enabled),
721         HadNoPriorDiags(Info.EvalStatus.Diag &&
722                         Info.EvalStatus.Diag->empty() &&
723                         !Info.EvalStatus.HasSideEffects),
724         OldMode(Info.EvalMode) {
725       if (Enabled &&
726           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
727            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
728         Info.EvalMode = EvalInfo::EM_ConstantFold;
729     }
keepDiagnostics__anona626307c0111::FoldConstant730     void keepDiagnostics() { Enabled = false; }
~FoldConstant__anona626307c0111::FoldConstant731     ~FoldConstant() {
732       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
733           !Info.EvalStatus.HasSideEffects)
734         Info.EvalStatus.Diag->clear();
735       Info.EvalMode = OldMode;
736     }
737   };
738 
739   /// RAII object used to suppress diagnostics and side-effects from a
740   /// speculative evaluation.
741   class SpeculativeEvaluationRAII {
742     EvalInfo &Info;
743     Expr::EvalStatus Old;
744 
745   public:
SpeculativeEvaluationRAII(EvalInfo & Info,SmallVectorImpl<PartialDiagnosticAt> * NewDiag=nullptr)746     SpeculativeEvaluationRAII(EvalInfo &Info,
747                         SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
748       : Info(Info), Old(Info.EvalStatus) {
749       Info.EvalStatus.Diag = NewDiag;
750       // If we're speculatively evaluating, we may have skipped over some
751       // evaluations and missed out a side effect.
752       Info.EvalStatus.HasSideEffects = true;
753     }
~SpeculativeEvaluationRAII()754     ~SpeculativeEvaluationRAII() {
755       Info.EvalStatus = Old;
756     }
757   };
758 
759   /// RAII object wrapping a full-expression or block scope, and handling
760   /// the ending of the lifetime of temporaries created within it.
761   template<bool IsFullExpression>
762   class ScopeRAII {
763     EvalInfo &Info;
764     unsigned OldStackSize;
765   public:
ScopeRAII(EvalInfo & Info)766     ScopeRAII(EvalInfo &Info)
767         : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
~ScopeRAII()768     ~ScopeRAII() {
769       // Body moved to a static method to encourage the compiler to inline away
770       // instances of this class.
771       cleanup(Info, OldStackSize);
772     }
773   private:
cleanup(EvalInfo & Info,unsigned OldStackSize)774     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
775       unsigned NewEnd = OldStackSize;
776       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
777            I != N; ++I) {
778         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
779           // Full-expression cleanup of a lifetime-extended temporary: nothing
780           // to do, just move this cleanup to the right place in the stack.
781           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
782           ++NewEnd;
783         } else {
784           // End the lifetime of the object.
785           Info.CleanupStack[I].endLifetime();
786         }
787       }
788       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
789                               Info.CleanupStack.end());
790     }
791   };
792   typedef ScopeRAII<false> BlockScopeRAII;
793   typedef ScopeRAII<true> FullExpressionRAII;
794 }
795 
checkSubobject(EvalInfo & Info,const Expr * E,CheckSubobjectKind CSK)796 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
797                                          CheckSubobjectKind CSK) {
798   if (Invalid)
799     return false;
800   if (isOnePastTheEnd()) {
801     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
802       << CSK;
803     setInvalid();
804     return false;
805   }
806   return true;
807 }
808 
diagnosePointerArithmetic(EvalInfo & Info,const Expr * E,uint64_t N)809 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
810                                                     const Expr *E, uint64_t N) {
811   if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
812     Info.CCEDiag(E, diag::note_constexpr_array_index)
813       << static_cast<int>(N) << /*array*/ 0
814       << static_cast<unsigned>(MostDerivedArraySize);
815   else
816     Info.CCEDiag(E, diag::note_constexpr_array_index)
817       << static_cast<int>(N) << /*non-array*/ 1;
818   setInvalid();
819 }
820 
CallStackFrame(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,APValue * Arguments)821 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
822                                const FunctionDecl *Callee, const LValue *This,
823                                APValue *Arguments)
824     : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
825       Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
826   Info.CurrentCall = this;
827   ++Info.CallStackDepth;
828 }
829 
~CallStackFrame()830 CallStackFrame::~CallStackFrame() {
831   assert(Info.CurrentCall == this && "calls retired out of order");
832   --Info.CallStackDepth;
833   Info.CurrentCall = Caller;
834 }
835 
createTemporary(const void * Key,bool IsLifetimeExtended)836 APValue &CallStackFrame::createTemporary(const void *Key,
837                                          bool IsLifetimeExtended) {
838   APValue &Result = Temporaries[Key];
839   assert(Result.isUninit() && "temporary created multiple times");
840   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
841   return Result;
842 }
843 
844 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
845 
addCallStack(unsigned Limit)846 void EvalInfo::addCallStack(unsigned Limit) {
847   // Determine which calls to skip, if any.
848   unsigned ActiveCalls = CallStackDepth - 1;
849   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
850   if (Limit && Limit < ActiveCalls) {
851     SkipStart = Limit / 2 + Limit % 2;
852     SkipEnd = ActiveCalls - Limit / 2;
853   }
854 
855   // Walk the call stack and add the diagnostics.
856   unsigned CallIdx = 0;
857   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
858        Frame = Frame->Caller, ++CallIdx) {
859     // Skip this call?
860     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
861       if (CallIdx == SkipStart) {
862         // Note that we're skipping calls.
863         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
864           << unsigned(ActiveCalls - Limit);
865       }
866       continue;
867     }
868 
869     SmallVector<char, 128> Buffer;
870     llvm::raw_svector_ostream Out(Buffer);
871     describeCall(Frame, Out);
872     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
873   }
874 }
875 
876 namespace {
877   struct ComplexValue {
878   private:
879     bool IsInt;
880 
881   public:
882     APSInt IntReal, IntImag;
883     APFloat FloatReal, FloatImag;
884 
ComplexValue__anona626307c0211::ComplexValue885     ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
886 
makeComplexFloat__anona626307c0211::ComplexValue887     void makeComplexFloat() { IsInt = false; }
isComplexFloat__anona626307c0211::ComplexValue888     bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anona626307c0211::ComplexValue889     APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anona626307c0211::ComplexValue890     APFloat &getComplexFloatImag() { return FloatImag; }
891 
makeComplexInt__anona626307c0211::ComplexValue892     void makeComplexInt() { IsInt = true; }
isComplexInt__anona626307c0211::ComplexValue893     bool isComplexInt() const { return IsInt; }
getComplexIntReal__anona626307c0211::ComplexValue894     APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anona626307c0211::ComplexValue895     APSInt &getComplexIntImag() { return IntImag; }
896 
moveInto__anona626307c0211::ComplexValue897     void moveInto(APValue &v) const {
898       if (isComplexFloat())
899         v = APValue(FloatReal, FloatImag);
900       else
901         v = APValue(IntReal, IntImag);
902     }
setFrom__anona626307c0211::ComplexValue903     void setFrom(const APValue &v) {
904       assert(v.isComplexFloat() || v.isComplexInt());
905       if (v.isComplexFloat()) {
906         makeComplexFloat();
907         FloatReal = v.getComplexFloatReal();
908         FloatImag = v.getComplexFloatImag();
909       } else {
910         makeComplexInt();
911         IntReal = v.getComplexIntReal();
912         IntImag = v.getComplexIntImag();
913       }
914     }
915   };
916 
917   struct LValue {
918     APValue::LValueBase Base;
919     CharUnits Offset;
920     unsigned CallIndex;
921     SubobjectDesignator Designator;
922 
getLValueBase__anona626307c0211::LValue923     const APValue::LValueBase getLValueBase() const { return Base; }
getLValueOffset__anona626307c0211::LValue924     CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anona626307c0211::LValue925     const CharUnits &getLValueOffset() const { return Offset; }
getLValueCallIndex__anona626307c0211::LValue926     unsigned getLValueCallIndex() const { return CallIndex; }
getLValueDesignator__anona626307c0211::LValue927     SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anona626307c0211::LValue928     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
929 
moveInto__anona626307c0211::LValue930     void moveInto(APValue &V) const {
931       if (Designator.Invalid)
932         V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
933       else
934         V = APValue(Base, Offset, Designator.Entries,
935                     Designator.IsOnePastTheEnd, CallIndex);
936     }
setFrom__anona626307c0211::LValue937     void setFrom(ASTContext &Ctx, const APValue &V) {
938       assert(V.isLValue());
939       Base = V.getLValueBase();
940       Offset = V.getLValueOffset();
941       CallIndex = V.getLValueCallIndex();
942       Designator = SubobjectDesignator(Ctx, V);
943     }
944 
set__anona626307c0211::LValue945     void set(APValue::LValueBase B, unsigned I = 0) {
946       Base = B;
947       Offset = CharUnits::Zero();
948       CallIndex = I;
949       Designator = SubobjectDesignator(getType(B));
950     }
951 
952     // Check that this LValue is not based on a null pointer. If it is, produce
953     // a diagnostic and mark the designator as invalid.
checkNullPointer__anona626307c0211::LValue954     bool checkNullPointer(EvalInfo &Info, const Expr *E,
955                           CheckSubobjectKind CSK) {
956       if (Designator.Invalid)
957         return false;
958       if (!Base) {
959         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
960           << CSK;
961         Designator.setInvalid();
962         return false;
963       }
964       return true;
965     }
966 
967     // Check this LValue refers to an object. If not, set the designator to be
968     // invalid and emit a diagnostic.
checkSubobject__anona626307c0211::LValue969     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
970       // Outside C++11, do not build a designator referring to a subobject of
971       // any object: we won't use such a designator for anything.
972       if (!Info.getLangOpts().CPlusPlus11)
973         Designator.setInvalid();
974       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
975              Designator.checkSubobject(Info, E, CSK);
976     }
977 
addDecl__anona626307c0211::LValue978     void addDecl(EvalInfo &Info, const Expr *E,
979                  const Decl *D, bool Virtual = false) {
980       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
981         Designator.addDeclUnchecked(D, Virtual);
982     }
addArray__anona626307c0211::LValue983     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
984       if (checkSubobject(Info, E, CSK_ArrayToPointer))
985         Designator.addArrayUnchecked(CAT);
986     }
addComplex__anona626307c0211::LValue987     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
988       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
989         Designator.addComplexUnchecked(EltTy, Imag);
990     }
adjustIndex__anona626307c0211::LValue991     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
992       if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
993         Designator.adjustIndex(Info, E, N);
994     }
995   };
996 
997   struct MemberPtr {
MemberPtr__anona626307c0211::MemberPtr998     MemberPtr() {}
MemberPtr__anona626307c0211::MemberPtr999     explicit MemberPtr(const ValueDecl *Decl) :
1000       DeclAndIsDerivedMember(Decl, false), Path() {}
1001 
1002     /// The member or (direct or indirect) field referred to by this member
1003     /// pointer, or 0 if this is a null member pointer.
getDecl__anona626307c0211::MemberPtr1004     const ValueDecl *getDecl() const {
1005       return DeclAndIsDerivedMember.getPointer();
1006     }
1007     /// Is this actually a member of some type derived from the relevant class?
isDerivedMember__anona626307c0211::MemberPtr1008     bool isDerivedMember() const {
1009       return DeclAndIsDerivedMember.getInt();
1010     }
1011     /// Get the class which the declaration actually lives in.
getContainingRecord__anona626307c0211::MemberPtr1012     const CXXRecordDecl *getContainingRecord() const {
1013       return cast<CXXRecordDecl>(
1014           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1015     }
1016 
moveInto__anona626307c0211::MemberPtr1017     void moveInto(APValue &V) const {
1018       V = APValue(getDecl(), isDerivedMember(), Path);
1019     }
setFrom__anona626307c0211::MemberPtr1020     void setFrom(const APValue &V) {
1021       assert(V.isMemberPointer());
1022       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1023       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1024       Path.clear();
1025       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1026       Path.insert(Path.end(), P.begin(), P.end());
1027     }
1028 
1029     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1030     /// whether the member is a member of some class derived from the class type
1031     /// of the member pointer.
1032     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1033     /// Path - The path of base/derived classes from the member declaration's
1034     /// class (exclusive) to the class type of the member pointer (inclusive).
1035     SmallVector<const CXXRecordDecl*, 4> Path;
1036 
1037     /// Perform a cast towards the class of the Decl (either up or down the
1038     /// hierarchy).
castBack__anona626307c0211::MemberPtr1039     bool castBack(const CXXRecordDecl *Class) {
1040       assert(!Path.empty());
1041       const CXXRecordDecl *Expected;
1042       if (Path.size() >= 2)
1043         Expected = Path[Path.size() - 2];
1044       else
1045         Expected = getContainingRecord();
1046       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1047         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1048         // if B does not contain the original member and is not a base or
1049         // derived class of the class containing the original member, the result
1050         // of the cast is undefined.
1051         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1052         // (D::*). We consider that to be a language defect.
1053         return false;
1054       }
1055       Path.pop_back();
1056       return true;
1057     }
1058     /// Perform a base-to-derived member pointer cast.
castToDerived__anona626307c0211::MemberPtr1059     bool castToDerived(const CXXRecordDecl *Derived) {
1060       if (!getDecl())
1061         return true;
1062       if (!isDerivedMember()) {
1063         Path.push_back(Derived);
1064         return true;
1065       }
1066       if (!castBack(Derived))
1067         return false;
1068       if (Path.empty())
1069         DeclAndIsDerivedMember.setInt(false);
1070       return true;
1071     }
1072     /// Perform a derived-to-base member pointer cast.
castToBase__anona626307c0211::MemberPtr1073     bool castToBase(const CXXRecordDecl *Base) {
1074       if (!getDecl())
1075         return true;
1076       if (Path.empty())
1077         DeclAndIsDerivedMember.setInt(true);
1078       if (isDerivedMember()) {
1079         Path.push_back(Base);
1080         return true;
1081       }
1082       return castBack(Base);
1083     }
1084   };
1085 
1086   /// Compare two member pointers, which are assumed to be of the same type.
operator ==(const MemberPtr & LHS,const MemberPtr & RHS)1087   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1088     if (!LHS.getDecl() || !RHS.getDecl())
1089       return !LHS.getDecl() && !RHS.getDecl();
1090     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1091       return false;
1092     return LHS.Path == RHS.Path;
1093   }
1094 }
1095 
1096 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1097 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1098                             const LValue &This, const Expr *E,
1099                             bool AllowNonLiteralTypes = false);
1100 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1101 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1102 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1103                                   EvalInfo &Info);
1104 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1105 static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
1106 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1107                                     EvalInfo &Info);
1108 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1109 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1110 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1111 
1112 //===----------------------------------------------------------------------===//
1113 // Misc utilities
1114 //===----------------------------------------------------------------------===//
1115 
1116 /// Produce a string describing the given constexpr call.
describeCall(CallStackFrame * Frame,raw_ostream & Out)1117 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1118   unsigned ArgIndex = 0;
1119   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1120                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1121                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1122 
1123   if (!IsMemberCall)
1124     Out << *Frame->Callee << '(';
1125 
1126   if (Frame->This && IsMemberCall) {
1127     APValue Val;
1128     Frame->This->moveInto(Val);
1129     Val.printPretty(Out, Frame->Info.Ctx,
1130                     Frame->This->Designator.MostDerivedType);
1131     // FIXME: Add parens around Val if needed.
1132     Out << "->" << *Frame->Callee << '(';
1133     IsMemberCall = false;
1134   }
1135 
1136   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1137        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1138     if (ArgIndex > (unsigned)IsMemberCall)
1139       Out << ", ";
1140 
1141     const ParmVarDecl *Param = *I;
1142     const APValue &Arg = Frame->Arguments[ArgIndex];
1143     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1144 
1145     if (ArgIndex == 0 && IsMemberCall)
1146       Out << "->" << *Frame->Callee << '(';
1147   }
1148 
1149   Out << ')';
1150 }
1151 
1152 /// Evaluate an expression to see if it had side-effects, and discard its
1153 /// result.
1154 /// \return \c true if the caller should keep evaluating.
EvaluateIgnoredValue(EvalInfo & Info,const Expr * E)1155 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1156   APValue Scratch;
1157   if (!Evaluate(Scratch, Info, E))
1158     // We don't need the value, but we might have skipped a side effect here.
1159     return Info.noteSideEffect();
1160   return true;
1161 }
1162 
1163 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1164 /// return its existing value.
getExtValue(const APSInt & Value)1165 static int64_t getExtValue(const APSInt &Value) {
1166   return Value.isSigned() ? Value.getSExtValue()
1167                           : static_cast<int64_t>(Value.getZExtValue());
1168 }
1169 
1170 /// Should this call expression be treated as a string literal?
IsStringLiteralCall(const CallExpr * E)1171 static bool IsStringLiteralCall(const CallExpr *E) {
1172   unsigned Builtin = E->getBuiltinCallee();
1173   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1174           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1175 }
1176 
IsGlobalLValue(APValue::LValueBase B)1177 static bool IsGlobalLValue(APValue::LValueBase B) {
1178   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1179   // constant expression of pointer type that evaluates to...
1180 
1181   // ... a null pointer value, or a prvalue core constant expression of type
1182   // std::nullptr_t.
1183   if (!B) return true;
1184 
1185   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1186     // ... the address of an object with static storage duration,
1187     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1188       return VD->hasGlobalStorage();
1189     // ... the address of a function,
1190     return isa<FunctionDecl>(D);
1191   }
1192 
1193   const Expr *E = B.get<const Expr*>();
1194   switch (E->getStmtClass()) {
1195   default:
1196     return false;
1197   case Expr::CompoundLiteralExprClass: {
1198     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1199     return CLE->isFileScope() && CLE->isLValue();
1200   }
1201   case Expr::MaterializeTemporaryExprClass:
1202     // A materialized temporary might have been lifetime-extended to static
1203     // storage duration.
1204     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1205   // A string literal has static storage duration.
1206   case Expr::StringLiteralClass:
1207   case Expr::PredefinedExprClass:
1208   case Expr::ObjCStringLiteralClass:
1209   case Expr::ObjCEncodeExprClass:
1210   case Expr::CXXTypeidExprClass:
1211   case Expr::CXXUuidofExprClass:
1212     return true;
1213   case Expr::CallExprClass:
1214     return IsStringLiteralCall(cast<CallExpr>(E));
1215   // For GCC compatibility, &&label has static storage duration.
1216   case Expr::AddrLabelExprClass:
1217     return true;
1218   // A Block literal expression may be used as the initialization value for
1219   // Block variables at global or local static scope.
1220   case Expr::BlockExprClass:
1221     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1222   case Expr::ImplicitValueInitExprClass:
1223     // FIXME:
1224     // We can never form an lvalue with an implicit value initialization as its
1225     // base through expression evaluation, so these only appear in one case: the
1226     // implicit variable declaration we invent when checking whether a constexpr
1227     // constructor can produce a constant expression. We must assume that such
1228     // an expression might be a global lvalue.
1229     return true;
1230   }
1231 }
1232 
NoteLValueLocation(EvalInfo & Info,APValue::LValueBase Base)1233 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1234   assert(Base && "no location for a null lvalue");
1235   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1236   if (VD)
1237     Info.Note(VD->getLocation(), diag::note_declared_at);
1238   else
1239     Info.Note(Base.get<const Expr*>()->getExprLoc(),
1240               diag::note_constexpr_temporary_here);
1241 }
1242 
1243 /// Check that this reference or pointer core constant expression is a valid
1244 /// value for an address or reference constant expression. Return true if we
1245 /// can fold this expression, whether or not it's a constant expression.
CheckLValueConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const LValue & LVal)1246 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1247                                           QualType Type, const LValue &LVal) {
1248   bool IsReferenceType = Type->isReferenceType();
1249 
1250   APValue::LValueBase Base = LVal.getLValueBase();
1251   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1252 
1253   // Check that the object is a global. Note that the fake 'this' object we
1254   // manufacture when checking potential constant expressions is conservatively
1255   // assumed to be global here.
1256   if (!IsGlobalLValue(Base)) {
1257     if (Info.getLangOpts().CPlusPlus11) {
1258       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1259       Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1260         << IsReferenceType << !Designator.Entries.empty()
1261         << !!VD << VD;
1262       NoteLValueLocation(Info, Base);
1263     } else {
1264       Info.Diag(Loc);
1265     }
1266     // Don't allow references to temporaries to escape.
1267     return false;
1268   }
1269   assert((Info.checkingPotentialConstantExpression() ||
1270           LVal.getLValueCallIndex() == 0) &&
1271          "have call index for global lvalue");
1272 
1273   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1274     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1275       // Check if this is a thread-local variable.
1276       if (Var->getTLSKind())
1277         return false;
1278 
1279       // A dllimport variable never acts like a constant.
1280       if (Var->hasAttr<DLLImportAttr>())
1281         return false;
1282     }
1283     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1284       // __declspec(dllimport) must be handled very carefully:
1285       // We must never initialize an expression with the thunk in C++.
1286       // Doing otherwise would allow the same id-expression to yield
1287       // different addresses for the same function in different translation
1288       // units.  However, this means that we must dynamically initialize the
1289       // expression with the contents of the import address table at runtime.
1290       //
1291       // The C language has no notion of ODR; furthermore, it has no notion of
1292       // dynamic initialization.  This means that we are permitted to
1293       // perform initialization with the address of the thunk.
1294       if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1295         return false;
1296     }
1297   }
1298 
1299   // Allow address constant expressions to be past-the-end pointers. This is
1300   // an extension: the standard requires them to point to an object.
1301   if (!IsReferenceType)
1302     return true;
1303 
1304   // A reference constant expression must refer to an object.
1305   if (!Base) {
1306     // FIXME: diagnostic
1307     Info.CCEDiag(Loc);
1308     return true;
1309   }
1310 
1311   // Does this refer one past the end of some object?
1312   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1313     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1314     Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1315       << !Designator.Entries.empty() << !!VD << VD;
1316     NoteLValueLocation(Info, Base);
1317   }
1318 
1319   return true;
1320 }
1321 
1322 /// Check that this core constant expression is of literal type, and if not,
1323 /// produce an appropriate diagnostic.
CheckLiteralType(EvalInfo & Info,const Expr * E,const LValue * This=nullptr)1324 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1325                              const LValue *This = nullptr) {
1326   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1327     return true;
1328 
1329   // C++1y: A constant initializer for an object o [...] may also invoke
1330   // constexpr constructors for o and its subobjects even if those objects
1331   // are of non-literal class types.
1332   if (Info.getLangOpts().CPlusPlus14 && This &&
1333       Info.EvaluatingDecl == This->getLValueBase())
1334     return true;
1335 
1336   // Prvalue constant expressions must be of literal types.
1337   if (Info.getLangOpts().CPlusPlus11)
1338     Info.Diag(E, diag::note_constexpr_nonliteral)
1339       << E->getType();
1340   else
1341     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1342   return false;
1343 }
1344 
1345 /// Check that this core constant expression value is a valid value for a
1346 /// constant expression. If not, report an appropriate diagnostic. Does not
1347 /// check that the expression is of literal type.
CheckConstantExpression(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value)1348 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1349                                     QualType Type, const APValue &Value) {
1350   if (Value.isUninit()) {
1351     Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1352       << true << Type;
1353     return false;
1354   }
1355 
1356   // We allow _Atomic(T) to be initialized from anything that T can be
1357   // initialized from.
1358   if (const AtomicType *AT = Type->getAs<AtomicType>())
1359     Type = AT->getValueType();
1360 
1361   // Core issue 1454: For a literal constant expression of array or class type,
1362   // each subobject of its value shall have been initialized by a constant
1363   // expression.
1364   if (Value.isArray()) {
1365     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1366     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1367       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1368                                    Value.getArrayInitializedElt(I)))
1369         return false;
1370     }
1371     if (!Value.hasArrayFiller())
1372       return true;
1373     return CheckConstantExpression(Info, DiagLoc, EltTy,
1374                                    Value.getArrayFiller());
1375   }
1376   if (Value.isUnion() && Value.getUnionField()) {
1377     return CheckConstantExpression(Info, DiagLoc,
1378                                    Value.getUnionField()->getType(),
1379                                    Value.getUnionValue());
1380   }
1381   if (Value.isStruct()) {
1382     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1383     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1384       unsigned BaseIndex = 0;
1385       for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1386              End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1387         if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1388                                      Value.getStructBase(BaseIndex)))
1389           return false;
1390       }
1391     }
1392     for (const auto *I : RD->fields()) {
1393       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1394                                    Value.getStructField(I->getFieldIndex())))
1395         return false;
1396     }
1397   }
1398 
1399   if (Value.isLValue()) {
1400     LValue LVal;
1401     LVal.setFrom(Info.Ctx, Value);
1402     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1403   }
1404 
1405   // Everything else is fine.
1406   return true;
1407 }
1408 
GetLValueBaseDecl(const LValue & LVal)1409 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1410   return LVal.Base.dyn_cast<const ValueDecl*>();
1411 }
1412 
IsLiteralLValue(const LValue & Value)1413 static bool IsLiteralLValue(const LValue &Value) {
1414   if (Value.CallIndex)
1415     return false;
1416   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1417   return E && !isa<MaterializeTemporaryExpr>(E);
1418 }
1419 
IsWeakLValue(const LValue & Value)1420 static bool IsWeakLValue(const LValue &Value) {
1421   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1422   return Decl && Decl->isWeak();
1423 }
1424 
isZeroSized(const LValue & Value)1425 static bool isZeroSized(const LValue &Value) {
1426   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1427   if (Decl && isa<VarDecl>(Decl)) {
1428     QualType Ty = Decl->getType();
1429     if (Ty->isArrayType())
1430       return Ty->isIncompleteType() ||
1431              Decl->getASTContext().getTypeSize(Ty) == 0;
1432   }
1433   return false;
1434 }
1435 
EvalPointerValueAsBool(const APValue & Value,bool & Result)1436 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1437   // A null base expression indicates a null pointer.  These are always
1438   // evaluatable, and they are false unless the offset is zero.
1439   if (!Value.getLValueBase()) {
1440     Result = !Value.getLValueOffset().isZero();
1441     return true;
1442   }
1443 
1444   // We have a non-null base.  These are generally known to be true, but if it's
1445   // a weak declaration it can be null at runtime.
1446   Result = true;
1447   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1448   return !Decl || !Decl->isWeak();
1449 }
1450 
HandleConversionToBool(const APValue & Val,bool & Result)1451 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1452   switch (Val.getKind()) {
1453   case APValue::Uninitialized:
1454     return false;
1455   case APValue::Int:
1456     Result = Val.getInt().getBoolValue();
1457     return true;
1458   case APValue::Float:
1459     Result = !Val.getFloat().isZero();
1460     return true;
1461   case APValue::ComplexInt:
1462     Result = Val.getComplexIntReal().getBoolValue() ||
1463              Val.getComplexIntImag().getBoolValue();
1464     return true;
1465   case APValue::ComplexFloat:
1466     Result = !Val.getComplexFloatReal().isZero() ||
1467              !Val.getComplexFloatImag().isZero();
1468     return true;
1469   case APValue::LValue:
1470     return EvalPointerValueAsBool(Val, Result);
1471   case APValue::MemberPointer:
1472     Result = Val.getMemberPointerDecl();
1473     return true;
1474   case APValue::Vector:
1475   case APValue::Array:
1476   case APValue::Struct:
1477   case APValue::Union:
1478   case APValue::AddrLabelDiff:
1479     return false;
1480   }
1481 
1482   llvm_unreachable("unknown APValue kind");
1483 }
1484 
EvaluateAsBooleanCondition(const Expr * E,bool & Result,EvalInfo & Info)1485 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1486                                        EvalInfo &Info) {
1487   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1488   APValue Val;
1489   if (!Evaluate(Val, Info, E))
1490     return false;
1491   return HandleConversionToBool(Val, Result);
1492 }
1493 
1494 template<typename T>
HandleOverflow(EvalInfo & Info,const Expr * E,const T & SrcValue,QualType DestType)1495 static void HandleOverflow(EvalInfo &Info, const Expr *E,
1496                            const T &SrcValue, QualType DestType) {
1497   Info.CCEDiag(E, diag::note_constexpr_overflow)
1498     << SrcValue << DestType;
1499 }
1500 
HandleFloatToIntCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APFloat & Value,QualType DestType,APSInt & Result)1501 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1502                                  QualType SrcType, const APFloat &Value,
1503                                  QualType DestType, APSInt &Result) {
1504   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1505   // Determine whether we are converting to unsigned or signed.
1506   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1507 
1508   Result = APSInt(DestWidth, !DestSigned);
1509   bool ignored;
1510   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1511       & APFloat::opInvalidOp)
1512     HandleOverflow(Info, E, Value, DestType);
1513   return true;
1514 }
1515 
HandleFloatToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,QualType DestType,APFloat & Result)1516 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1517                                    QualType SrcType, QualType DestType,
1518                                    APFloat &Result) {
1519   APFloat Value = Result;
1520   bool ignored;
1521   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1522                      APFloat::rmNearestTiesToEven, &ignored)
1523       & APFloat::opOverflow)
1524     HandleOverflow(Info, E, Value, DestType);
1525   return true;
1526 }
1527 
HandleIntToIntCast(EvalInfo & Info,const Expr * E,QualType DestType,QualType SrcType,APSInt & Value)1528 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1529                                  QualType DestType, QualType SrcType,
1530                                  APSInt &Value) {
1531   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1532   APSInt Result = Value;
1533   // Figure out if this is a truncate, extend or noop cast.
1534   // If the input is signed, do a sign extend, noop, or truncate.
1535   Result = Result.extOrTrunc(DestWidth);
1536   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1537   return Result;
1538 }
1539 
HandleIntToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APSInt & Value,QualType DestType,APFloat & Result)1540 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1541                                  QualType SrcType, const APSInt &Value,
1542                                  QualType DestType, APFloat &Result) {
1543   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1544   if (Result.convertFromAPInt(Value, Value.isSigned(),
1545                               APFloat::rmNearestTiesToEven)
1546       & APFloat::opOverflow)
1547     HandleOverflow(Info, E, Value, DestType);
1548   return true;
1549 }
1550 
truncateBitfieldValue(EvalInfo & Info,const Expr * E,APValue & Value,const FieldDecl * FD)1551 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1552                                   APValue &Value, const FieldDecl *FD) {
1553   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1554 
1555   if (!Value.isInt()) {
1556     // Trying to store a pointer-cast-to-integer into a bitfield.
1557     // FIXME: In this case, we should provide the diagnostic for casting
1558     // a pointer to an integer.
1559     assert(Value.isLValue() && "integral value neither int nor lvalue?");
1560     Info.Diag(E);
1561     return false;
1562   }
1563 
1564   APSInt &Int = Value.getInt();
1565   unsigned OldBitWidth = Int.getBitWidth();
1566   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1567   if (NewBitWidth < OldBitWidth)
1568     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1569   return true;
1570 }
1571 
EvalAndBitcastToAPInt(EvalInfo & Info,const Expr * E,llvm::APInt & Res)1572 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1573                                   llvm::APInt &Res) {
1574   APValue SVal;
1575   if (!Evaluate(SVal, Info, E))
1576     return false;
1577   if (SVal.isInt()) {
1578     Res = SVal.getInt();
1579     return true;
1580   }
1581   if (SVal.isFloat()) {
1582     Res = SVal.getFloat().bitcastToAPInt();
1583     return true;
1584   }
1585   if (SVal.isVector()) {
1586     QualType VecTy = E->getType();
1587     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1588     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1589     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1590     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1591     Res = llvm::APInt::getNullValue(VecSize);
1592     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1593       APValue &Elt = SVal.getVectorElt(i);
1594       llvm::APInt EltAsInt;
1595       if (Elt.isInt()) {
1596         EltAsInt = Elt.getInt();
1597       } else if (Elt.isFloat()) {
1598         EltAsInt = Elt.getFloat().bitcastToAPInt();
1599       } else {
1600         // Don't try to handle vectors of anything other than int or float
1601         // (not sure if it's possible to hit this case).
1602         Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1603         return false;
1604       }
1605       unsigned BaseEltSize = EltAsInt.getBitWidth();
1606       if (BigEndian)
1607         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1608       else
1609         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1610     }
1611     return true;
1612   }
1613   // Give up if the input isn't an int, float, or vector.  For example, we
1614   // reject "(v4i16)(intptr_t)&a".
1615   Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1616   return false;
1617 }
1618 
1619 /// Perform the given integer operation, which is known to need at most BitWidth
1620 /// bits, and check for overflow in the original type (if that type was not an
1621 /// unsigned type).
1622 template<typename Operation>
CheckedIntArithmetic(EvalInfo & Info,const Expr * E,const APSInt & LHS,const APSInt & RHS,unsigned BitWidth,Operation Op)1623 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1624                                    const APSInt &LHS, const APSInt &RHS,
1625                                    unsigned BitWidth, Operation Op) {
1626   if (LHS.isUnsigned())
1627     return Op(LHS, RHS);
1628 
1629   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1630   APSInt Result = Value.trunc(LHS.getBitWidth());
1631   if (Result.extend(BitWidth) != Value) {
1632     if (Info.checkingForOverflow())
1633       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1634         diag::warn_integer_constant_overflow)
1635           << Result.toString(10) << E->getType();
1636     else
1637       HandleOverflow(Info, E, Value, E->getType());
1638   }
1639   return Result;
1640 }
1641 
1642 /// Perform the given binary integer operation.
handleIntIntBinOp(EvalInfo & Info,const Expr * E,const APSInt & LHS,BinaryOperatorKind Opcode,APSInt RHS,APSInt & Result)1643 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1644                               BinaryOperatorKind Opcode, APSInt RHS,
1645                               APSInt &Result) {
1646   switch (Opcode) {
1647   default:
1648     Info.Diag(E);
1649     return false;
1650   case BO_Mul:
1651     Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1652                                   std::multiplies<APSInt>());
1653     return true;
1654   case BO_Add:
1655     Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1656                                   std::plus<APSInt>());
1657     return true;
1658   case BO_Sub:
1659     Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1660                                   std::minus<APSInt>());
1661     return true;
1662   case BO_And: Result = LHS & RHS; return true;
1663   case BO_Xor: Result = LHS ^ RHS; return true;
1664   case BO_Or:  Result = LHS | RHS; return true;
1665   case BO_Div:
1666   case BO_Rem:
1667     if (RHS == 0) {
1668       Info.Diag(E, diag::note_expr_divide_by_zero);
1669       return false;
1670     }
1671     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1672     if (RHS.isNegative() && RHS.isAllOnesValue() &&
1673         LHS.isSigned() && LHS.isMinSignedValue())
1674       HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1675     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1676     return true;
1677   case BO_Shl: {
1678     if (Info.getLangOpts().OpenCL)
1679       // OpenCL 6.3j: shift values are effectively % word size of LHS.
1680       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1681                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1682                     RHS.isUnsigned());
1683     else if (RHS.isSigned() && RHS.isNegative()) {
1684       // During constant-folding, a negative shift is an opposite shift. Such
1685       // a shift is not a constant expression.
1686       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1687       RHS = -RHS;
1688       goto shift_right;
1689     }
1690   shift_left:
1691     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1692     // the shifted type.
1693     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1694     if (SA != RHS) {
1695       Info.CCEDiag(E, diag::note_constexpr_large_shift)
1696         << RHS << E->getType() << LHS.getBitWidth();
1697     } else if (LHS.isSigned()) {
1698       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1699       // operand, and must not overflow the corresponding unsigned type.
1700       if (LHS.isNegative())
1701         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1702       else if (LHS.countLeadingZeros() < SA)
1703         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1704     }
1705     Result = LHS << SA;
1706     return true;
1707   }
1708   case BO_Shr: {
1709     if (Info.getLangOpts().OpenCL)
1710       // OpenCL 6.3j: shift values are effectively % word size of LHS.
1711       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1712                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1713                     RHS.isUnsigned());
1714     else if (RHS.isSigned() && RHS.isNegative()) {
1715       // During constant-folding, a negative shift is an opposite shift. Such a
1716       // shift is not a constant expression.
1717       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1718       RHS = -RHS;
1719       goto shift_left;
1720     }
1721   shift_right:
1722     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1723     // shifted type.
1724     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1725     if (SA != RHS)
1726       Info.CCEDiag(E, diag::note_constexpr_large_shift)
1727         << RHS << E->getType() << LHS.getBitWidth();
1728     Result = LHS >> SA;
1729     return true;
1730   }
1731 
1732   case BO_LT: Result = LHS < RHS; return true;
1733   case BO_GT: Result = LHS > RHS; return true;
1734   case BO_LE: Result = LHS <= RHS; return true;
1735   case BO_GE: Result = LHS >= RHS; return true;
1736   case BO_EQ: Result = LHS == RHS; return true;
1737   case BO_NE: Result = LHS != RHS; return true;
1738   }
1739 }
1740 
1741 /// Perform the given binary floating-point operation, in-place, on LHS.
handleFloatFloatBinOp(EvalInfo & Info,const Expr * E,APFloat & LHS,BinaryOperatorKind Opcode,const APFloat & RHS)1742 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1743                                   APFloat &LHS, BinaryOperatorKind Opcode,
1744                                   const APFloat &RHS) {
1745   switch (Opcode) {
1746   default:
1747     Info.Diag(E);
1748     return false;
1749   case BO_Mul:
1750     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1751     break;
1752   case BO_Add:
1753     LHS.add(RHS, APFloat::rmNearestTiesToEven);
1754     break;
1755   case BO_Sub:
1756     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1757     break;
1758   case BO_Div:
1759     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1760     break;
1761   }
1762 
1763   if (LHS.isInfinity() || LHS.isNaN())
1764     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1765   return true;
1766 }
1767 
1768 /// Cast an lvalue referring to a base subobject to a derived class, by
1769 /// truncating the lvalue's path to the given length.
CastToDerivedClass(EvalInfo & Info,const Expr * E,LValue & Result,const RecordDecl * TruncatedType,unsigned TruncatedElements)1770 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1771                                const RecordDecl *TruncatedType,
1772                                unsigned TruncatedElements) {
1773   SubobjectDesignator &D = Result.Designator;
1774 
1775   // Check we actually point to a derived class object.
1776   if (TruncatedElements == D.Entries.size())
1777     return true;
1778   assert(TruncatedElements >= D.MostDerivedPathLength &&
1779          "not casting to a derived class");
1780   if (!Result.checkSubobject(Info, E, CSK_Derived))
1781     return false;
1782 
1783   // Truncate the path to the subobject, and remove any derived-to-base offsets.
1784   const RecordDecl *RD = TruncatedType;
1785   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1786     if (RD->isInvalidDecl()) return false;
1787     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1788     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1789     if (isVirtualBaseClass(D.Entries[I]))
1790       Result.Offset -= Layout.getVBaseClassOffset(Base);
1791     else
1792       Result.Offset -= Layout.getBaseClassOffset(Base);
1793     RD = Base;
1794   }
1795   D.Entries.resize(TruncatedElements);
1796   return true;
1797 }
1798 
HandleLValueDirectBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,const ASTRecordLayout * RL=nullptr)1799 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1800                                    const CXXRecordDecl *Derived,
1801                                    const CXXRecordDecl *Base,
1802                                    const ASTRecordLayout *RL = nullptr) {
1803   if (!RL) {
1804     if (Derived->isInvalidDecl()) return false;
1805     RL = &Info.Ctx.getASTRecordLayout(Derived);
1806   }
1807 
1808   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1809   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1810   return true;
1811 }
1812 
HandleLValueBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * DerivedDecl,const CXXBaseSpecifier * Base)1813 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1814                              const CXXRecordDecl *DerivedDecl,
1815                              const CXXBaseSpecifier *Base) {
1816   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1817 
1818   if (!Base->isVirtual())
1819     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1820 
1821   SubobjectDesignator &D = Obj.Designator;
1822   if (D.Invalid)
1823     return false;
1824 
1825   // Extract most-derived object and corresponding type.
1826   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1827   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1828     return false;
1829 
1830   // Find the virtual base class.
1831   if (DerivedDecl->isInvalidDecl()) return false;
1832   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1833   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1834   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1835   return true;
1836 }
1837 
HandleLValueBasePath(EvalInfo & Info,const CastExpr * E,QualType Type,LValue & Result)1838 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1839                                  QualType Type, LValue &Result) {
1840   for (CastExpr::path_const_iterator PathI = E->path_begin(),
1841                                      PathE = E->path_end();
1842        PathI != PathE; ++PathI) {
1843     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1844                           *PathI))
1845       return false;
1846     Type = (*PathI)->getType();
1847   }
1848   return true;
1849 }
1850 
1851 /// Update LVal to refer to the given field, which must be a member of the type
1852 /// currently described by LVal.
HandleLValueMember(EvalInfo & Info,const Expr * E,LValue & LVal,const FieldDecl * FD,const ASTRecordLayout * RL=nullptr)1853 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1854                                const FieldDecl *FD,
1855                                const ASTRecordLayout *RL = nullptr) {
1856   if (!RL) {
1857     if (FD->getParent()->isInvalidDecl()) return false;
1858     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1859   }
1860 
1861   unsigned I = FD->getFieldIndex();
1862   LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1863   LVal.addDecl(Info, E, FD);
1864   return true;
1865 }
1866 
1867 /// Update LVal to refer to the given indirect field.
HandleLValueIndirectMember(EvalInfo & Info,const Expr * E,LValue & LVal,const IndirectFieldDecl * IFD)1868 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1869                                        LValue &LVal,
1870                                        const IndirectFieldDecl *IFD) {
1871   for (const auto *C : IFD->chain())
1872     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
1873       return false;
1874   return true;
1875 }
1876 
1877 /// Get the size of the given type in char units.
HandleSizeof(EvalInfo & Info,SourceLocation Loc,QualType Type,CharUnits & Size)1878 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1879                          QualType Type, CharUnits &Size) {
1880   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1881   // extension.
1882   if (Type->isVoidType() || Type->isFunctionType()) {
1883     Size = CharUnits::One();
1884     return true;
1885   }
1886 
1887   if (!Type->isConstantSizeType()) {
1888     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1889     // FIXME: Better diagnostic.
1890     Info.Diag(Loc);
1891     return false;
1892   }
1893 
1894   Size = Info.Ctx.getTypeSizeInChars(Type);
1895   return true;
1896 }
1897 
1898 /// Update a pointer value to model pointer arithmetic.
1899 /// \param Info - Information about the ongoing evaluation.
1900 /// \param E - The expression being evaluated, for diagnostic purposes.
1901 /// \param LVal - The pointer value to be updated.
1902 /// \param EltTy - The pointee type represented by LVal.
1903 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,int64_t Adjustment)1904 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1905                                         LValue &LVal, QualType EltTy,
1906                                         int64_t Adjustment) {
1907   CharUnits SizeOfPointee;
1908   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1909     return false;
1910 
1911   // Compute the new offset in the appropriate width.
1912   LVal.Offset += Adjustment * SizeOfPointee;
1913   LVal.adjustIndex(Info, E, Adjustment);
1914   return true;
1915 }
1916 
1917 /// Update an lvalue to refer to a component of a complex number.
1918 /// \param Info - Information about the ongoing evaluation.
1919 /// \param LVal - The lvalue to be updated.
1920 /// \param EltTy - The complex number's component type.
1921 /// \param Imag - False for the real component, true for the imaginary.
HandleLValueComplexElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,bool Imag)1922 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1923                                        LValue &LVal, QualType EltTy,
1924                                        bool Imag) {
1925   if (Imag) {
1926     CharUnits SizeOfComponent;
1927     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1928       return false;
1929     LVal.Offset += SizeOfComponent;
1930   }
1931   LVal.addComplex(Info, E, EltTy, Imag);
1932   return true;
1933 }
1934 
1935 /// Try to evaluate the initializer for a variable declaration.
1936 ///
1937 /// \param Info   Information about the ongoing evaluation.
1938 /// \param E      An expression to be used when printing diagnostics.
1939 /// \param VD     The variable whose initializer should be obtained.
1940 /// \param Frame  The frame in which the variable was created. Must be null
1941 ///               if this variable is not local to the evaluation.
1942 /// \param Result Filled in with a pointer to the value of the variable.
evaluateVarDeclInit(EvalInfo & Info,const Expr * E,const VarDecl * VD,CallStackFrame * Frame,APValue * & Result)1943 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1944                                 const VarDecl *VD, CallStackFrame *Frame,
1945                                 APValue *&Result) {
1946   // If this is a parameter to an active constexpr function call, perform
1947   // argument substitution.
1948   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1949     // Assume arguments of a potential constant expression are unknown
1950     // constant expressions.
1951     if (Info.checkingPotentialConstantExpression())
1952       return false;
1953     if (!Frame || !Frame->Arguments) {
1954       Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1955       return false;
1956     }
1957     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
1958     return true;
1959   }
1960 
1961   // If this is a local variable, dig out its value.
1962   if (Frame) {
1963     Result = Frame->getTemporary(VD);
1964     assert(Result && "missing value for local variable");
1965     return true;
1966   }
1967 
1968   // Dig out the initializer, and use the declaration which it's attached to.
1969   const Expr *Init = VD->getAnyInitializer(VD);
1970   if (!Init || Init->isValueDependent()) {
1971     // If we're checking a potential constant expression, the variable could be
1972     // initialized later.
1973     if (!Info.checkingPotentialConstantExpression())
1974       Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1975     return false;
1976   }
1977 
1978   // If we're currently evaluating the initializer of this declaration, use that
1979   // in-flight value.
1980   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
1981     Result = Info.EvaluatingDeclValue;
1982     return true;
1983   }
1984 
1985   // Never evaluate the initializer of a weak variable. We can't be sure that
1986   // this is the definition which will be used.
1987   if (VD->isWeak()) {
1988     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1989     return false;
1990   }
1991 
1992   // Check that we can fold the initializer. In C++, we will have already done
1993   // this in the cases where it matters for conformance.
1994   SmallVector<PartialDiagnosticAt, 8> Notes;
1995   if (!VD->evaluateValue(Notes)) {
1996     Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1997               Notes.size() + 1) << VD;
1998     Info.Note(VD->getLocation(), diag::note_declared_at);
1999     Info.addNotes(Notes);
2000     return false;
2001   } else if (!VD->checkInitIsICE()) {
2002     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2003                  Notes.size() + 1) << VD;
2004     Info.Note(VD->getLocation(), diag::note_declared_at);
2005     Info.addNotes(Notes);
2006   }
2007 
2008   Result = VD->getEvaluatedValue();
2009   return true;
2010 }
2011 
IsConstNonVolatile(QualType T)2012 static bool IsConstNonVolatile(QualType T) {
2013   Qualifiers Quals = T.getQualifiers();
2014   return Quals.hasConst() && !Quals.hasVolatile();
2015 }
2016 
2017 /// Get the base index of the given base class within an APValue representing
2018 /// the given derived class.
getBaseIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)2019 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2020                              const CXXRecordDecl *Base) {
2021   Base = Base->getCanonicalDecl();
2022   unsigned Index = 0;
2023   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2024          E = Derived->bases_end(); I != E; ++I, ++Index) {
2025     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2026       return Index;
2027   }
2028 
2029   llvm_unreachable("base class missing from derived class's bases list");
2030 }
2031 
2032 /// Extract the value of a character from a string literal.
extractStringLiteralCharacter(EvalInfo & Info,const Expr * Lit,uint64_t Index)2033 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2034                                             uint64_t Index) {
2035   // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2036   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2037     Lit = PE->getFunctionName();
2038   const StringLiteral *S = cast<StringLiteral>(Lit);
2039   const ConstantArrayType *CAT =
2040       Info.Ctx.getAsConstantArrayType(S->getType());
2041   assert(CAT && "string literal isn't an array");
2042   QualType CharType = CAT->getElementType();
2043   assert(CharType->isIntegerType() && "unexpected character type");
2044 
2045   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2046                CharType->isUnsignedIntegerType());
2047   if (Index < S->getLength())
2048     Value = S->getCodeUnit(Index);
2049   return Value;
2050 }
2051 
2052 // Expand a string literal into an array of characters.
expandStringLiteral(EvalInfo & Info,const Expr * Lit,APValue & Result)2053 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2054                                 APValue &Result) {
2055   const StringLiteral *S = cast<StringLiteral>(Lit);
2056   const ConstantArrayType *CAT =
2057       Info.Ctx.getAsConstantArrayType(S->getType());
2058   assert(CAT && "string literal isn't an array");
2059   QualType CharType = CAT->getElementType();
2060   assert(CharType->isIntegerType() && "unexpected character type");
2061 
2062   unsigned Elts = CAT->getSize().getZExtValue();
2063   Result = APValue(APValue::UninitArray(),
2064                    std::min(S->getLength(), Elts), Elts);
2065   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2066                CharType->isUnsignedIntegerType());
2067   if (Result.hasArrayFiller())
2068     Result.getArrayFiller() = APValue(Value);
2069   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2070     Value = S->getCodeUnit(I);
2071     Result.getArrayInitializedElt(I) = APValue(Value);
2072   }
2073 }
2074 
2075 // Expand an array so that it has more than Index filled elements.
expandArray(APValue & Array,unsigned Index)2076 static void expandArray(APValue &Array, unsigned Index) {
2077   unsigned Size = Array.getArraySize();
2078   assert(Index < Size);
2079 
2080   // Always at least double the number of elements for which we store a value.
2081   unsigned OldElts = Array.getArrayInitializedElts();
2082   unsigned NewElts = std::max(Index+1, OldElts * 2);
2083   NewElts = std::min(Size, std::max(NewElts, 8u));
2084 
2085   // Copy the data across.
2086   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2087   for (unsigned I = 0; I != OldElts; ++I)
2088     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2089   for (unsigned I = OldElts; I != NewElts; ++I)
2090     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2091   if (NewValue.hasArrayFiller())
2092     NewValue.getArrayFiller() = Array.getArrayFiller();
2093   Array.swap(NewValue);
2094 }
2095 
2096 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2097 /// conversion. If it's of class type, we may assume that the copy operation
2098 /// is trivial. Note that this is never true for a union type with fields
2099 /// (because the copy always "reads" the active member) and always true for
2100 /// a non-class type.
isReadByLvalueToRvalueConversion(QualType T)2101 static bool isReadByLvalueToRvalueConversion(QualType T) {
2102   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2103   if (!RD || (RD->isUnion() && !RD->field_empty()))
2104     return true;
2105   if (RD->isEmpty())
2106     return false;
2107 
2108   for (auto *Field : RD->fields())
2109     if (isReadByLvalueToRvalueConversion(Field->getType()))
2110       return true;
2111 
2112   for (auto &BaseSpec : RD->bases())
2113     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2114       return true;
2115 
2116   return false;
2117 }
2118 
2119 /// Diagnose an attempt to read from any unreadable field within the specified
2120 /// type, which might be a class type.
diagnoseUnreadableFields(EvalInfo & Info,const Expr * E,QualType T)2121 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2122                                      QualType T) {
2123   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2124   if (!RD)
2125     return false;
2126 
2127   if (!RD->hasMutableFields())
2128     return false;
2129 
2130   for (auto *Field : RD->fields()) {
2131     // If we're actually going to read this field in some way, then it can't
2132     // be mutable. If we're in a union, then assigning to a mutable field
2133     // (even an empty one) can change the active member, so that's not OK.
2134     // FIXME: Add core issue number for the union case.
2135     if (Field->isMutable() &&
2136         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2137       Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2138       Info.Note(Field->getLocation(), diag::note_declared_at);
2139       return true;
2140     }
2141 
2142     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2143       return true;
2144   }
2145 
2146   for (auto &BaseSpec : RD->bases())
2147     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2148       return true;
2149 
2150   // All mutable fields were empty, and thus not actually read.
2151   return false;
2152 }
2153 
2154 /// Kinds of access we can perform on an object, for diagnostics.
2155 enum AccessKinds {
2156   AK_Read,
2157   AK_Assign,
2158   AK_Increment,
2159   AK_Decrement
2160 };
2161 
2162 /// A handle to a complete object (an object that is not a subobject of
2163 /// another object).
2164 struct CompleteObject {
2165   /// The value of the complete object.
2166   APValue *Value;
2167   /// The type of the complete object.
2168   QualType Type;
2169 
CompleteObjectCompleteObject2170   CompleteObject() : Value(nullptr) {}
CompleteObjectCompleteObject2171   CompleteObject(APValue *Value, QualType Type)
2172       : Value(Value), Type(Type) {
2173     assert(Value && "missing value for complete object");
2174   }
2175 
operator boolCompleteObject2176   explicit operator bool() const { return Value; }
2177 };
2178 
2179 /// Find the designated sub-object of an rvalue.
2180 template<typename SubobjectHandler>
2181 typename SubobjectHandler::result_type
findSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,SubobjectHandler & handler)2182 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2183               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2184   if (Sub.Invalid)
2185     // A diagnostic will have already been produced.
2186     return handler.failed();
2187   if (Sub.isOnePastTheEnd()) {
2188     if (Info.getLangOpts().CPlusPlus11)
2189       Info.Diag(E, diag::note_constexpr_access_past_end)
2190         << handler.AccessKind;
2191     else
2192       Info.Diag(E);
2193     return handler.failed();
2194   }
2195 
2196   APValue *O = Obj.Value;
2197   QualType ObjType = Obj.Type;
2198   const FieldDecl *LastField = nullptr;
2199 
2200   // Walk the designator's path to find the subobject.
2201   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2202     if (O->isUninit()) {
2203       if (!Info.checkingPotentialConstantExpression())
2204         Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2205       return handler.failed();
2206     }
2207 
2208     if (I == N) {
2209       // If we are reading an object of class type, there may still be more
2210       // things we need to check: if there are any mutable subobjects, we
2211       // cannot perform this read. (This only happens when performing a trivial
2212       // copy or assignment.)
2213       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2214           diagnoseUnreadableFields(Info, E, ObjType))
2215         return handler.failed();
2216 
2217       if (!handler.found(*O, ObjType))
2218         return false;
2219 
2220       // If we modified a bit-field, truncate it to the right width.
2221       if (handler.AccessKind != AK_Read &&
2222           LastField && LastField->isBitField() &&
2223           !truncateBitfieldValue(Info, E, *O, LastField))
2224         return false;
2225 
2226       return true;
2227     }
2228 
2229     LastField = nullptr;
2230     if (ObjType->isArrayType()) {
2231       // Next subobject is an array element.
2232       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2233       assert(CAT && "vla in literal type?");
2234       uint64_t Index = Sub.Entries[I].ArrayIndex;
2235       if (CAT->getSize().ule(Index)) {
2236         // Note, it should not be possible to form a pointer with a valid
2237         // designator which points more than one past the end of the array.
2238         if (Info.getLangOpts().CPlusPlus11)
2239           Info.Diag(E, diag::note_constexpr_access_past_end)
2240             << handler.AccessKind;
2241         else
2242           Info.Diag(E);
2243         return handler.failed();
2244       }
2245 
2246       ObjType = CAT->getElementType();
2247 
2248       // An array object is represented as either an Array APValue or as an
2249       // LValue which refers to a string literal.
2250       if (O->isLValue()) {
2251         assert(I == N - 1 && "extracting subobject of character?");
2252         assert(!O->hasLValuePath() || O->getLValuePath().empty());
2253         if (handler.AccessKind != AK_Read)
2254           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2255                               *O);
2256         else
2257           return handler.foundString(*O, ObjType, Index);
2258       }
2259 
2260       if (O->getArrayInitializedElts() > Index)
2261         O = &O->getArrayInitializedElt(Index);
2262       else if (handler.AccessKind != AK_Read) {
2263         expandArray(*O, Index);
2264         O = &O->getArrayInitializedElt(Index);
2265       } else
2266         O = &O->getArrayFiller();
2267     } else if (ObjType->isAnyComplexType()) {
2268       // Next subobject is a complex number.
2269       uint64_t Index = Sub.Entries[I].ArrayIndex;
2270       if (Index > 1) {
2271         if (Info.getLangOpts().CPlusPlus11)
2272           Info.Diag(E, diag::note_constexpr_access_past_end)
2273             << handler.AccessKind;
2274         else
2275           Info.Diag(E);
2276         return handler.failed();
2277       }
2278 
2279       bool WasConstQualified = ObjType.isConstQualified();
2280       ObjType = ObjType->castAs<ComplexType>()->getElementType();
2281       if (WasConstQualified)
2282         ObjType.addConst();
2283 
2284       assert(I == N - 1 && "extracting subobject of scalar?");
2285       if (O->isComplexInt()) {
2286         return handler.found(Index ? O->getComplexIntImag()
2287                                    : O->getComplexIntReal(), ObjType);
2288       } else {
2289         assert(O->isComplexFloat());
2290         return handler.found(Index ? O->getComplexFloatImag()
2291                                    : O->getComplexFloatReal(), ObjType);
2292       }
2293     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2294       if (Field->isMutable() && handler.AccessKind == AK_Read) {
2295         Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
2296           << Field;
2297         Info.Note(Field->getLocation(), diag::note_declared_at);
2298         return handler.failed();
2299       }
2300 
2301       // Next subobject is a class, struct or union field.
2302       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2303       if (RD->isUnion()) {
2304         const FieldDecl *UnionField = O->getUnionField();
2305         if (!UnionField ||
2306             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2307           Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2308             << handler.AccessKind << Field << !UnionField << UnionField;
2309           return handler.failed();
2310         }
2311         O = &O->getUnionValue();
2312       } else
2313         O = &O->getStructField(Field->getFieldIndex());
2314 
2315       bool WasConstQualified = ObjType.isConstQualified();
2316       ObjType = Field->getType();
2317       if (WasConstQualified && !Field->isMutable())
2318         ObjType.addConst();
2319 
2320       if (ObjType.isVolatileQualified()) {
2321         if (Info.getLangOpts().CPlusPlus) {
2322           // FIXME: Include a description of the path to the volatile subobject.
2323           Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2324             << handler.AccessKind << 2 << Field;
2325           Info.Note(Field->getLocation(), diag::note_declared_at);
2326         } else {
2327           Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2328         }
2329         return handler.failed();
2330       }
2331 
2332       LastField = Field;
2333     } else {
2334       // Next subobject is a base class.
2335       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2336       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2337       O = &O->getStructBase(getBaseIndex(Derived, Base));
2338 
2339       bool WasConstQualified = ObjType.isConstQualified();
2340       ObjType = Info.Ctx.getRecordType(Base);
2341       if (WasConstQualified)
2342         ObjType.addConst();
2343     }
2344   }
2345 }
2346 
2347 namespace {
2348 struct ExtractSubobjectHandler {
2349   EvalInfo &Info;
2350   APValue &Result;
2351 
2352   static const AccessKinds AccessKind = AK_Read;
2353 
2354   typedef bool result_type;
failed__anona626307c0311::ExtractSubobjectHandler2355   bool failed() { return false; }
found__anona626307c0311::ExtractSubobjectHandler2356   bool found(APValue &Subobj, QualType SubobjType) {
2357     Result = Subobj;
2358     return true;
2359   }
found__anona626307c0311::ExtractSubobjectHandler2360   bool found(APSInt &Value, QualType SubobjType) {
2361     Result = APValue(Value);
2362     return true;
2363   }
found__anona626307c0311::ExtractSubobjectHandler2364   bool found(APFloat &Value, QualType SubobjType) {
2365     Result = APValue(Value);
2366     return true;
2367   }
foundString__anona626307c0311::ExtractSubobjectHandler2368   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2369     Result = APValue(extractStringLiteralCharacter(
2370         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2371     return true;
2372   }
2373 };
2374 } // end anonymous namespace
2375 
2376 const AccessKinds ExtractSubobjectHandler::AccessKind;
2377 
2378 /// Extract the designated sub-object of an rvalue.
extractSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & Result)2379 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2380                              const CompleteObject &Obj,
2381                              const SubobjectDesignator &Sub,
2382                              APValue &Result) {
2383   ExtractSubobjectHandler Handler = { Info, Result };
2384   return findSubobject(Info, E, Obj, Sub, Handler);
2385 }
2386 
2387 namespace {
2388 struct ModifySubobjectHandler {
2389   EvalInfo &Info;
2390   APValue &NewVal;
2391   const Expr *E;
2392 
2393   typedef bool result_type;
2394   static const AccessKinds AccessKind = AK_Assign;
2395 
checkConst__anona626307c0411::ModifySubobjectHandler2396   bool checkConst(QualType QT) {
2397     // Assigning to a const object has undefined behavior.
2398     if (QT.isConstQualified()) {
2399       Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2400       return false;
2401     }
2402     return true;
2403   }
2404 
failed__anona626307c0411::ModifySubobjectHandler2405   bool failed() { return false; }
found__anona626307c0411::ModifySubobjectHandler2406   bool found(APValue &Subobj, QualType SubobjType) {
2407     if (!checkConst(SubobjType))
2408       return false;
2409     // We've been given ownership of NewVal, so just swap it in.
2410     Subobj.swap(NewVal);
2411     return true;
2412   }
found__anona626307c0411::ModifySubobjectHandler2413   bool found(APSInt &Value, QualType SubobjType) {
2414     if (!checkConst(SubobjType))
2415       return false;
2416     if (!NewVal.isInt()) {
2417       // Maybe trying to write a cast pointer value into a complex?
2418       Info.Diag(E);
2419       return false;
2420     }
2421     Value = NewVal.getInt();
2422     return true;
2423   }
found__anona626307c0411::ModifySubobjectHandler2424   bool found(APFloat &Value, QualType SubobjType) {
2425     if (!checkConst(SubobjType))
2426       return false;
2427     Value = NewVal.getFloat();
2428     return true;
2429   }
foundString__anona626307c0411::ModifySubobjectHandler2430   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2431     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2432   }
2433 };
2434 } // end anonymous namespace
2435 
2436 const AccessKinds ModifySubobjectHandler::AccessKind;
2437 
2438 /// Update the designated sub-object of an rvalue to the given value.
modifySubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & NewVal)2439 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2440                             const CompleteObject &Obj,
2441                             const SubobjectDesignator &Sub,
2442                             APValue &NewVal) {
2443   ModifySubobjectHandler Handler = { Info, NewVal, E };
2444   return findSubobject(Info, E, Obj, Sub, Handler);
2445 }
2446 
2447 /// Find the position where two subobject designators diverge, or equivalently
2448 /// the length of the common initial subsequence.
FindDesignatorMismatch(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B,bool & WasArrayIndex)2449 static unsigned FindDesignatorMismatch(QualType ObjType,
2450                                        const SubobjectDesignator &A,
2451                                        const SubobjectDesignator &B,
2452                                        bool &WasArrayIndex) {
2453   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2454   for (/**/; I != N; ++I) {
2455     if (!ObjType.isNull() &&
2456         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2457       // Next subobject is an array element.
2458       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2459         WasArrayIndex = true;
2460         return I;
2461       }
2462       if (ObjType->isAnyComplexType())
2463         ObjType = ObjType->castAs<ComplexType>()->getElementType();
2464       else
2465         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2466     } else {
2467       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2468         WasArrayIndex = false;
2469         return I;
2470       }
2471       if (const FieldDecl *FD = getAsField(A.Entries[I]))
2472         // Next subobject is a field.
2473         ObjType = FD->getType();
2474       else
2475         // Next subobject is a base class.
2476         ObjType = QualType();
2477     }
2478   }
2479   WasArrayIndex = false;
2480   return I;
2481 }
2482 
2483 /// Determine whether the given subobject designators refer to elements of the
2484 /// same array object.
AreElementsOfSameArray(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B)2485 static bool AreElementsOfSameArray(QualType ObjType,
2486                                    const SubobjectDesignator &A,
2487                                    const SubobjectDesignator &B) {
2488   if (A.Entries.size() != B.Entries.size())
2489     return false;
2490 
2491   bool IsArray = A.MostDerivedArraySize != 0;
2492   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2493     // A is a subobject of the array element.
2494     return false;
2495 
2496   // If A (and B) designates an array element, the last entry will be the array
2497   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2498   // of length 1' case, and the entire path must match.
2499   bool WasArrayIndex;
2500   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2501   return CommonLength >= A.Entries.size() - IsArray;
2502 }
2503 
2504 /// Find the complete object to which an LValue refers.
findCompleteObject(EvalInfo & Info,const Expr * E,AccessKinds AK,const LValue & LVal,QualType LValType)2505 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2506                                          AccessKinds AK, const LValue &LVal,
2507                                          QualType LValType) {
2508   if (!LVal.Base) {
2509     Info.Diag(E, diag::note_constexpr_access_null) << AK;
2510     return CompleteObject();
2511   }
2512 
2513   CallStackFrame *Frame = nullptr;
2514   if (LVal.CallIndex) {
2515     Frame = Info.getCallFrame(LVal.CallIndex);
2516     if (!Frame) {
2517       Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2518         << AK << LVal.Base.is<const ValueDecl*>();
2519       NoteLValueLocation(Info, LVal.Base);
2520       return CompleteObject();
2521     }
2522   }
2523 
2524   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2525   // is not a constant expression (even if the object is non-volatile). We also
2526   // apply this rule to C++98, in order to conform to the expected 'volatile'
2527   // semantics.
2528   if (LValType.isVolatileQualified()) {
2529     if (Info.getLangOpts().CPlusPlus)
2530       Info.Diag(E, diag::note_constexpr_access_volatile_type)
2531         << AK << LValType;
2532     else
2533       Info.Diag(E);
2534     return CompleteObject();
2535   }
2536 
2537   // Compute value storage location and type of base object.
2538   APValue *BaseVal = nullptr;
2539   QualType BaseType = getType(LVal.Base);
2540 
2541   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2542     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2543     // In C++11, constexpr, non-volatile variables initialized with constant
2544     // expressions are constant expressions too. Inside constexpr functions,
2545     // parameters are constant expressions even if they're non-const.
2546     // In C++1y, objects local to a constant expression (those with a Frame) are
2547     // both readable and writable inside constant expressions.
2548     // In C, such things can also be folded, although they are not ICEs.
2549     const VarDecl *VD = dyn_cast<VarDecl>(D);
2550     if (VD) {
2551       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2552         VD = VDef;
2553     }
2554     if (!VD || VD->isInvalidDecl()) {
2555       Info.Diag(E);
2556       return CompleteObject();
2557     }
2558 
2559     // Accesses of volatile-qualified objects are not allowed.
2560     if (BaseType.isVolatileQualified()) {
2561       if (Info.getLangOpts().CPlusPlus) {
2562         Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2563           << AK << 1 << VD;
2564         Info.Note(VD->getLocation(), diag::note_declared_at);
2565       } else {
2566         Info.Diag(E);
2567       }
2568       return CompleteObject();
2569     }
2570 
2571     // Unless we're looking at a local variable or argument in a constexpr call,
2572     // the variable we're reading must be const.
2573     if (!Frame) {
2574       if (Info.getLangOpts().CPlusPlus14 &&
2575           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2576         // OK, we can read and modify an object if we're in the process of
2577         // evaluating its initializer, because its lifetime began in this
2578         // evaluation.
2579       } else if (AK != AK_Read) {
2580         // All the remaining cases only permit reading.
2581         Info.Diag(E, diag::note_constexpr_modify_global);
2582         return CompleteObject();
2583       } else if (VD->isConstexpr()) {
2584         // OK, we can read this variable.
2585       } else if (BaseType->isIntegralOrEnumerationType()) {
2586         if (!BaseType.isConstQualified()) {
2587           if (Info.getLangOpts().CPlusPlus) {
2588             Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2589             Info.Note(VD->getLocation(), diag::note_declared_at);
2590           } else {
2591             Info.Diag(E);
2592           }
2593           return CompleteObject();
2594         }
2595       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2596         // We support folding of const floating-point types, in order to make
2597         // static const data members of such types (supported as an extension)
2598         // more useful.
2599         if (Info.getLangOpts().CPlusPlus11) {
2600           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2601           Info.Note(VD->getLocation(), diag::note_declared_at);
2602         } else {
2603           Info.CCEDiag(E);
2604         }
2605       } else {
2606         // FIXME: Allow folding of values of any literal type in all languages.
2607         if (Info.getLangOpts().CPlusPlus11) {
2608           Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2609           Info.Note(VD->getLocation(), diag::note_declared_at);
2610         } else {
2611           Info.Diag(E);
2612         }
2613         return CompleteObject();
2614       }
2615     }
2616 
2617     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2618       return CompleteObject();
2619   } else {
2620     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2621 
2622     if (!Frame) {
2623       if (const MaterializeTemporaryExpr *MTE =
2624               dyn_cast<MaterializeTemporaryExpr>(Base)) {
2625         assert(MTE->getStorageDuration() == SD_Static &&
2626                "should have a frame for a non-global materialized temporary");
2627 
2628         // Per C++1y [expr.const]p2:
2629         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2630         //   - a [...] glvalue of integral or enumeration type that refers to
2631         //     a non-volatile const object [...]
2632         //   [...]
2633         //   - a [...] glvalue of literal type that refers to a non-volatile
2634         //     object whose lifetime began within the evaluation of e.
2635         //
2636         // C++11 misses the 'began within the evaluation of e' check and
2637         // instead allows all temporaries, including things like:
2638         //   int &&r = 1;
2639         //   int x = ++r;
2640         //   constexpr int k = r;
2641         // Therefore we use the C++1y rules in C++11 too.
2642         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2643         const ValueDecl *ED = MTE->getExtendingDecl();
2644         if (!(BaseType.isConstQualified() &&
2645               BaseType->isIntegralOrEnumerationType()) &&
2646             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2647           Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2648           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2649           return CompleteObject();
2650         }
2651 
2652         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2653         assert(BaseVal && "got reference to unevaluated temporary");
2654       } else {
2655         Info.Diag(E);
2656         return CompleteObject();
2657       }
2658     } else {
2659       BaseVal = Frame->getTemporary(Base);
2660       assert(BaseVal && "missing value for temporary");
2661     }
2662 
2663     // Volatile temporary objects cannot be accessed in constant expressions.
2664     if (BaseType.isVolatileQualified()) {
2665       if (Info.getLangOpts().CPlusPlus) {
2666         Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2667           << AK << 0;
2668         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2669       } else {
2670         Info.Diag(E);
2671       }
2672       return CompleteObject();
2673     }
2674   }
2675 
2676   // During the construction of an object, it is not yet 'const'.
2677   // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2678   // and this doesn't do quite the right thing for const subobjects of the
2679   // object under construction.
2680   if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2681     BaseType = Info.Ctx.getCanonicalType(BaseType);
2682     BaseType.removeLocalConst();
2683   }
2684 
2685   // In C++1y, we can't safely access any mutable state when we might be
2686   // evaluating after an unmodeled side effect or an evaluation failure.
2687   //
2688   // FIXME: Not all local state is mutable. Allow local constant subobjects
2689   // to be read here (but take care with 'mutable' fields).
2690   if (Frame && Info.getLangOpts().CPlusPlus14 &&
2691       (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
2692     return CompleteObject();
2693 
2694   return CompleteObject(BaseVal, BaseType);
2695 }
2696 
2697 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2698 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2699 /// glvalue referred to by an entity of reference type.
2700 ///
2701 /// \param Info - Information about the ongoing evaluation.
2702 /// \param Conv - The expression for which we are performing the conversion.
2703 ///               Used for diagnostics.
2704 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2705 ///               case of a non-class type).
2706 /// \param LVal - The glvalue on which we are attempting to perform this action.
2707 /// \param RVal - The produced value will be placed here.
handleLValueToRValueConversion(EvalInfo & Info,const Expr * Conv,QualType Type,const LValue & LVal,APValue & RVal)2708 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2709                                            QualType Type,
2710                                            const LValue &LVal, APValue &RVal) {
2711   if (LVal.Designator.Invalid)
2712     return false;
2713 
2714   // Check for special cases where there is no existing APValue to look at.
2715   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2716   if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2717       !Type.isVolatileQualified()) {
2718     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2719       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2720       // initializer until now for such expressions. Such an expression can't be
2721       // an ICE in C, so this only matters for fold.
2722       assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2723       if (Type.isVolatileQualified()) {
2724         Info.Diag(Conv);
2725         return false;
2726       }
2727       APValue Lit;
2728       if (!Evaluate(Lit, Info, CLE->getInitializer()))
2729         return false;
2730       CompleteObject LitObj(&Lit, Base->getType());
2731       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2732     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
2733       // We represent a string literal array as an lvalue pointing at the
2734       // corresponding expression, rather than building an array of chars.
2735       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2736       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2737       CompleteObject StrObj(&Str, Base->getType());
2738       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2739     }
2740   }
2741 
2742   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2743   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2744 }
2745 
2746 /// Perform an assignment of Val to LVal. Takes ownership of Val.
handleAssignment(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,APValue & Val)2747 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2748                              QualType LValType, APValue &Val) {
2749   if (LVal.Designator.Invalid)
2750     return false;
2751 
2752   if (!Info.getLangOpts().CPlusPlus14) {
2753     Info.Diag(E);
2754     return false;
2755   }
2756 
2757   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2758   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2759 }
2760 
isOverflowingIntegerType(ASTContext & Ctx,QualType T)2761 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2762   return T->isSignedIntegerType() &&
2763          Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2764 }
2765 
2766 namespace {
2767 struct CompoundAssignSubobjectHandler {
2768   EvalInfo &Info;
2769   const Expr *E;
2770   QualType PromotedLHSType;
2771   BinaryOperatorKind Opcode;
2772   const APValue &RHS;
2773 
2774   static const AccessKinds AccessKind = AK_Assign;
2775 
2776   typedef bool result_type;
2777 
checkConst__anona626307c0511::CompoundAssignSubobjectHandler2778   bool checkConst(QualType QT) {
2779     // Assigning to a const object has undefined behavior.
2780     if (QT.isConstQualified()) {
2781       Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2782       return false;
2783     }
2784     return true;
2785   }
2786 
failed__anona626307c0511::CompoundAssignSubobjectHandler2787   bool failed() { return false; }
found__anona626307c0511::CompoundAssignSubobjectHandler2788   bool found(APValue &Subobj, QualType SubobjType) {
2789     switch (Subobj.getKind()) {
2790     case APValue::Int:
2791       return found(Subobj.getInt(), SubobjType);
2792     case APValue::Float:
2793       return found(Subobj.getFloat(), SubobjType);
2794     case APValue::ComplexInt:
2795     case APValue::ComplexFloat:
2796       // FIXME: Implement complex compound assignment.
2797       Info.Diag(E);
2798       return false;
2799     case APValue::LValue:
2800       return foundPointer(Subobj, SubobjType);
2801     default:
2802       // FIXME: can this happen?
2803       Info.Diag(E);
2804       return false;
2805     }
2806   }
found__anona626307c0511::CompoundAssignSubobjectHandler2807   bool found(APSInt &Value, QualType SubobjType) {
2808     if (!checkConst(SubobjType))
2809       return false;
2810 
2811     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2812       // We don't support compound assignment on integer-cast-to-pointer
2813       // values.
2814       Info.Diag(E);
2815       return false;
2816     }
2817 
2818     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2819                                     SubobjType, Value);
2820     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2821       return false;
2822     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2823     return true;
2824   }
found__anona626307c0511::CompoundAssignSubobjectHandler2825   bool found(APFloat &Value, QualType SubobjType) {
2826     return checkConst(SubobjType) &&
2827            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2828                                   Value) &&
2829            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2830            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
2831   }
foundPointer__anona626307c0511::CompoundAssignSubobjectHandler2832   bool foundPointer(APValue &Subobj, QualType SubobjType) {
2833     if (!checkConst(SubobjType))
2834       return false;
2835 
2836     QualType PointeeType;
2837     if (const PointerType *PT = SubobjType->getAs<PointerType>())
2838       PointeeType = PT->getPointeeType();
2839 
2840     if (PointeeType.isNull() || !RHS.isInt() ||
2841         (Opcode != BO_Add && Opcode != BO_Sub)) {
2842       Info.Diag(E);
2843       return false;
2844     }
2845 
2846     int64_t Offset = getExtValue(RHS.getInt());
2847     if (Opcode == BO_Sub)
2848       Offset = -Offset;
2849 
2850     LValue LVal;
2851     LVal.setFrom(Info.Ctx, Subobj);
2852     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2853       return false;
2854     LVal.moveInto(Subobj);
2855     return true;
2856   }
foundString__anona626307c0511::CompoundAssignSubobjectHandler2857   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2858     llvm_unreachable("shouldn't encounter string elements here");
2859   }
2860 };
2861 } // end anonymous namespace
2862 
2863 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2864 
2865 /// Perform a compound assignment of LVal <op>= RVal.
handleCompoundAssignment(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,QualType PromotedLValType,BinaryOperatorKind Opcode,const APValue & RVal)2866 static bool handleCompoundAssignment(
2867     EvalInfo &Info, const Expr *E,
2868     const LValue &LVal, QualType LValType, QualType PromotedLValType,
2869     BinaryOperatorKind Opcode, const APValue &RVal) {
2870   if (LVal.Designator.Invalid)
2871     return false;
2872 
2873   if (!Info.getLangOpts().CPlusPlus14) {
2874     Info.Diag(E);
2875     return false;
2876   }
2877 
2878   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2879   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2880                                              RVal };
2881   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2882 }
2883 
2884 namespace {
2885 struct IncDecSubobjectHandler {
2886   EvalInfo &Info;
2887   const Expr *E;
2888   AccessKinds AccessKind;
2889   APValue *Old;
2890 
2891   typedef bool result_type;
2892 
checkConst__anona626307c0611::IncDecSubobjectHandler2893   bool checkConst(QualType QT) {
2894     // Assigning to a const object has undefined behavior.
2895     if (QT.isConstQualified()) {
2896       Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2897       return false;
2898     }
2899     return true;
2900   }
2901 
failed__anona626307c0611::IncDecSubobjectHandler2902   bool failed() { return false; }
found__anona626307c0611::IncDecSubobjectHandler2903   bool found(APValue &Subobj, QualType SubobjType) {
2904     // Stash the old value. Also clear Old, so we don't clobber it later
2905     // if we're post-incrementing a complex.
2906     if (Old) {
2907       *Old = Subobj;
2908       Old = nullptr;
2909     }
2910 
2911     switch (Subobj.getKind()) {
2912     case APValue::Int:
2913       return found(Subobj.getInt(), SubobjType);
2914     case APValue::Float:
2915       return found(Subobj.getFloat(), SubobjType);
2916     case APValue::ComplexInt:
2917       return found(Subobj.getComplexIntReal(),
2918                    SubobjType->castAs<ComplexType>()->getElementType()
2919                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2920     case APValue::ComplexFloat:
2921       return found(Subobj.getComplexFloatReal(),
2922                    SubobjType->castAs<ComplexType>()->getElementType()
2923                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2924     case APValue::LValue:
2925       return foundPointer(Subobj, SubobjType);
2926     default:
2927       // FIXME: can this happen?
2928       Info.Diag(E);
2929       return false;
2930     }
2931   }
found__anona626307c0611::IncDecSubobjectHandler2932   bool found(APSInt &Value, QualType SubobjType) {
2933     if (!checkConst(SubobjType))
2934       return false;
2935 
2936     if (!SubobjType->isIntegerType()) {
2937       // We don't support increment / decrement on integer-cast-to-pointer
2938       // values.
2939       Info.Diag(E);
2940       return false;
2941     }
2942 
2943     if (Old) *Old = APValue(Value);
2944 
2945     // bool arithmetic promotes to int, and the conversion back to bool
2946     // doesn't reduce mod 2^n, so special-case it.
2947     if (SubobjType->isBooleanType()) {
2948       if (AccessKind == AK_Increment)
2949         Value = 1;
2950       else
2951         Value = !Value;
2952       return true;
2953     }
2954 
2955     bool WasNegative = Value.isNegative();
2956     if (AccessKind == AK_Increment) {
2957       ++Value;
2958 
2959       if (!WasNegative && Value.isNegative() &&
2960           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2961         APSInt ActualValue(Value, /*IsUnsigned*/true);
2962         HandleOverflow(Info, E, ActualValue, SubobjType);
2963       }
2964     } else {
2965       --Value;
2966 
2967       if (WasNegative && !Value.isNegative() &&
2968           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2969         unsigned BitWidth = Value.getBitWidth();
2970         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2971         ActualValue.setBit(BitWidth);
2972         HandleOverflow(Info, E, ActualValue, SubobjType);
2973       }
2974     }
2975     return true;
2976   }
found__anona626307c0611::IncDecSubobjectHandler2977   bool found(APFloat &Value, QualType SubobjType) {
2978     if (!checkConst(SubobjType))
2979       return false;
2980 
2981     if (Old) *Old = APValue(Value);
2982 
2983     APFloat One(Value.getSemantics(), 1);
2984     if (AccessKind == AK_Increment)
2985       Value.add(One, APFloat::rmNearestTiesToEven);
2986     else
2987       Value.subtract(One, APFloat::rmNearestTiesToEven);
2988     return true;
2989   }
foundPointer__anona626307c0611::IncDecSubobjectHandler2990   bool foundPointer(APValue &Subobj, QualType SubobjType) {
2991     if (!checkConst(SubobjType))
2992       return false;
2993 
2994     QualType PointeeType;
2995     if (const PointerType *PT = SubobjType->getAs<PointerType>())
2996       PointeeType = PT->getPointeeType();
2997     else {
2998       Info.Diag(E);
2999       return false;
3000     }
3001 
3002     LValue LVal;
3003     LVal.setFrom(Info.Ctx, Subobj);
3004     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3005                                      AccessKind == AK_Increment ? 1 : -1))
3006       return false;
3007     LVal.moveInto(Subobj);
3008     return true;
3009   }
foundString__anona626307c0611::IncDecSubobjectHandler3010   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3011     llvm_unreachable("shouldn't encounter string elements here");
3012   }
3013 };
3014 } // end anonymous namespace
3015 
3016 /// Perform an increment or decrement on LVal.
handleIncDec(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,bool IsIncrement,APValue * Old)3017 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3018                          QualType LValType, bool IsIncrement, APValue *Old) {
3019   if (LVal.Designator.Invalid)
3020     return false;
3021 
3022   if (!Info.getLangOpts().CPlusPlus14) {
3023     Info.Diag(E);
3024     return false;
3025   }
3026 
3027   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3028   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3029   IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3030   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3031 }
3032 
3033 /// Build an lvalue for the object argument of a member function call.
EvaluateObjectArgument(EvalInfo & Info,const Expr * Object,LValue & This)3034 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3035                                    LValue &This) {
3036   if (Object->getType()->isPointerType())
3037     return EvaluatePointer(Object, This, Info);
3038 
3039   if (Object->isGLValue())
3040     return EvaluateLValue(Object, This, Info);
3041 
3042   if (Object->getType()->isLiteralType(Info.Ctx))
3043     return EvaluateTemporary(Object, This, Info);
3044 
3045   Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3046   return false;
3047 }
3048 
3049 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3050 /// lvalue referring to the result.
3051 ///
3052 /// \param Info - Information about the ongoing evaluation.
3053 /// \param LV - An lvalue referring to the base of the member pointer.
3054 /// \param RHS - The member pointer expression.
3055 /// \param IncludeMember - Specifies whether the member itself is included in
3056 ///        the resulting LValue subobject designator. This is not possible when
3057 ///        creating a bound member function.
3058 /// \return The field or method declaration to which the member pointer refers,
3059 ///         or 0 if evaluation fails.
HandleMemberPointerAccess(EvalInfo & Info,QualType LVType,LValue & LV,const Expr * RHS,bool IncludeMember=true)3060 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3061                                                   QualType LVType,
3062                                                   LValue &LV,
3063                                                   const Expr *RHS,
3064                                                   bool IncludeMember = true) {
3065   MemberPtr MemPtr;
3066   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3067     return nullptr;
3068 
3069   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3070   // member value, the behavior is undefined.
3071   if (!MemPtr.getDecl()) {
3072     // FIXME: Specific diagnostic.
3073     Info.Diag(RHS);
3074     return nullptr;
3075   }
3076 
3077   if (MemPtr.isDerivedMember()) {
3078     // This is a member of some derived class. Truncate LV appropriately.
3079     // The end of the derived-to-base path for the base object must match the
3080     // derived-to-base path for the member pointer.
3081     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3082         LV.Designator.Entries.size()) {
3083       Info.Diag(RHS);
3084       return nullptr;
3085     }
3086     unsigned PathLengthToMember =
3087         LV.Designator.Entries.size() - MemPtr.Path.size();
3088     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3089       const CXXRecordDecl *LVDecl = getAsBaseClass(
3090           LV.Designator.Entries[PathLengthToMember + I]);
3091       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3092       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3093         Info.Diag(RHS);
3094         return nullptr;
3095       }
3096     }
3097 
3098     // Truncate the lvalue to the appropriate derived class.
3099     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3100                             PathLengthToMember))
3101       return nullptr;
3102   } else if (!MemPtr.Path.empty()) {
3103     // Extend the LValue path with the member pointer's path.
3104     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3105                                   MemPtr.Path.size() + IncludeMember);
3106 
3107     // Walk down to the appropriate base class.
3108     if (const PointerType *PT = LVType->getAs<PointerType>())
3109       LVType = PT->getPointeeType();
3110     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3111     assert(RD && "member pointer access on non-class-type expression");
3112     // The first class in the path is that of the lvalue.
3113     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3114       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3115       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3116         return nullptr;
3117       RD = Base;
3118     }
3119     // Finally cast to the class containing the member.
3120     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3121                                 MemPtr.getContainingRecord()))
3122       return nullptr;
3123   }
3124 
3125   // Add the member. Note that we cannot build bound member functions here.
3126   if (IncludeMember) {
3127     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3128       if (!HandleLValueMember(Info, RHS, LV, FD))
3129         return nullptr;
3130     } else if (const IndirectFieldDecl *IFD =
3131                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3132       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3133         return nullptr;
3134     } else {
3135       llvm_unreachable("can't construct reference to bound member function");
3136     }
3137   }
3138 
3139   return MemPtr.getDecl();
3140 }
3141 
HandleMemberPointerAccess(EvalInfo & Info,const BinaryOperator * BO,LValue & LV,bool IncludeMember=true)3142 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3143                                                   const BinaryOperator *BO,
3144                                                   LValue &LV,
3145                                                   bool IncludeMember = true) {
3146   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3147 
3148   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3149     if (Info.keepEvaluatingAfterFailure()) {
3150       MemberPtr MemPtr;
3151       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3152     }
3153     return nullptr;
3154   }
3155 
3156   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3157                                    BO->getRHS(), IncludeMember);
3158 }
3159 
3160 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3161 /// the provided lvalue, which currently refers to the base object.
HandleBaseToDerivedCast(EvalInfo & Info,const CastExpr * E,LValue & Result)3162 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3163                                     LValue &Result) {
3164   SubobjectDesignator &D = Result.Designator;
3165   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3166     return false;
3167 
3168   QualType TargetQT = E->getType();
3169   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3170     TargetQT = PT->getPointeeType();
3171 
3172   // Check this cast lands within the final derived-to-base subobject path.
3173   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3174     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3175       << D.MostDerivedType << TargetQT;
3176     return false;
3177   }
3178 
3179   // Check the type of the final cast. We don't need to check the path,
3180   // since a cast can only be formed if the path is unique.
3181   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3182   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3183   const CXXRecordDecl *FinalType;
3184   if (NewEntriesSize == D.MostDerivedPathLength)
3185     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3186   else
3187     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3188   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3189     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3190       << D.MostDerivedType << TargetQT;
3191     return false;
3192   }
3193 
3194   // Truncate the lvalue to the appropriate derived class.
3195   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3196 }
3197 
3198 namespace {
3199 enum EvalStmtResult {
3200   /// Evaluation failed.
3201   ESR_Failed,
3202   /// Hit a 'return' statement.
3203   ESR_Returned,
3204   /// Evaluation succeeded.
3205   ESR_Succeeded,
3206   /// Hit a 'continue' statement.
3207   ESR_Continue,
3208   /// Hit a 'break' statement.
3209   ESR_Break,
3210   /// Still scanning for 'case' or 'default' statement.
3211   ESR_CaseNotFound
3212 };
3213 }
3214 
EvaluateDecl(EvalInfo & Info,const Decl * D)3215 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3216   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3217     // We don't need to evaluate the initializer for a static local.
3218     if (!VD->hasLocalStorage())
3219       return true;
3220 
3221     LValue Result;
3222     Result.set(VD, Info.CurrentCall->Index);
3223     APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3224 
3225     const Expr *InitE = VD->getInit();
3226     if (!InitE) {
3227       Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3228         << false << VD->getType();
3229       Val = APValue();
3230       return false;
3231     }
3232 
3233     if (InitE->isValueDependent())
3234       return false;
3235 
3236     if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3237       // Wipe out any partially-computed value, to allow tracking that this
3238       // evaluation failed.
3239       Val = APValue();
3240       return false;
3241     }
3242   }
3243 
3244   return true;
3245 }
3246 
3247 /// Evaluate a condition (either a variable declaration or an expression).
EvaluateCond(EvalInfo & Info,const VarDecl * CondDecl,const Expr * Cond,bool & Result)3248 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3249                          const Expr *Cond, bool &Result) {
3250   FullExpressionRAII Scope(Info);
3251   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3252     return false;
3253   return EvaluateAsBooleanCondition(Cond, Result, Info);
3254 }
3255 
3256 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3257                                    const Stmt *S,
3258                                    const SwitchCase *SC = nullptr);
3259 
3260 /// Evaluate the body of a loop, and translate the result as appropriate.
EvaluateLoopBody(APValue & Result,EvalInfo & Info,const Stmt * Body,const SwitchCase * Case=nullptr)3261 static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
3262                                        const Stmt *Body,
3263                                        const SwitchCase *Case = nullptr) {
3264   BlockScopeRAII Scope(Info);
3265   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3266   case ESR_Break:
3267     return ESR_Succeeded;
3268   case ESR_Succeeded:
3269   case ESR_Continue:
3270     return ESR_Continue;
3271   case ESR_Failed:
3272   case ESR_Returned:
3273   case ESR_CaseNotFound:
3274     return ESR;
3275   }
3276   llvm_unreachable("Invalid EvalStmtResult!");
3277 }
3278 
3279 /// Evaluate a switch statement.
EvaluateSwitch(APValue & Result,EvalInfo & Info,const SwitchStmt * SS)3280 static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3281                                      const SwitchStmt *SS) {
3282   BlockScopeRAII Scope(Info);
3283 
3284   // Evaluate the switch condition.
3285   APSInt Value;
3286   {
3287     FullExpressionRAII Scope(Info);
3288     if (SS->getConditionVariable() &&
3289         !EvaluateDecl(Info, SS->getConditionVariable()))
3290       return ESR_Failed;
3291     if (!EvaluateInteger(SS->getCond(), Value, Info))
3292       return ESR_Failed;
3293   }
3294 
3295   // Find the switch case corresponding to the value of the condition.
3296   // FIXME: Cache this lookup.
3297   const SwitchCase *Found = nullptr;
3298   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3299        SC = SC->getNextSwitchCase()) {
3300     if (isa<DefaultStmt>(SC)) {
3301       Found = SC;
3302       continue;
3303     }
3304 
3305     const CaseStmt *CS = cast<CaseStmt>(SC);
3306     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3307     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3308                               : LHS;
3309     if (LHS <= Value && Value <= RHS) {
3310       Found = SC;
3311       break;
3312     }
3313   }
3314 
3315   if (!Found)
3316     return ESR_Succeeded;
3317 
3318   // Search the switch body for the switch case and evaluate it from there.
3319   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3320   case ESR_Break:
3321     return ESR_Succeeded;
3322   case ESR_Succeeded:
3323   case ESR_Continue:
3324   case ESR_Failed:
3325   case ESR_Returned:
3326     return ESR;
3327   case ESR_CaseNotFound:
3328     // This can only happen if the switch case is nested within a statement
3329     // expression. We have no intention of supporting that.
3330     Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3331     return ESR_Failed;
3332   }
3333   llvm_unreachable("Invalid EvalStmtResult!");
3334 }
3335 
3336 // Evaluate a statement.
EvaluateStmt(APValue & Result,EvalInfo & Info,const Stmt * S,const SwitchCase * Case)3337 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3338                                    const Stmt *S, const SwitchCase *Case) {
3339   if (!Info.nextStep(S))
3340     return ESR_Failed;
3341 
3342   // If we're hunting down a 'case' or 'default' label, recurse through
3343   // substatements until we hit the label.
3344   if (Case) {
3345     // FIXME: We don't start the lifetime of objects whose initialization we
3346     // jump over. However, such objects must be of class type with a trivial
3347     // default constructor that initialize all subobjects, so must be empty,
3348     // so this almost never matters.
3349     switch (S->getStmtClass()) {
3350     case Stmt::CompoundStmtClass:
3351       // FIXME: Precompute which substatement of a compound statement we
3352       // would jump to, and go straight there rather than performing a
3353       // linear scan each time.
3354     case Stmt::LabelStmtClass:
3355     case Stmt::AttributedStmtClass:
3356     case Stmt::DoStmtClass:
3357       break;
3358 
3359     case Stmt::CaseStmtClass:
3360     case Stmt::DefaultStmtClass:
3361       if (Case == S)
3362         Case = nullptr;
3363       break;
3364 
3365     case Stmt::IfStmtClass: {
3366       // FIXME: Precompute which side of an 'if' we would jump to, and go
3367       // straight there rather than scanning both sides.
3368       const IfStmt *IS = cast<IfStmt>(S);
3369 
3370       // Wrap the evaluation in a block scope, in case it's a DeclStmt
3371       // preceded by our switch label.
3372       BlockScopeRAII Scope(Info);
3373 
3374       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3375       if (ESR != ESR_CaseNotFound || !IS->getElse())
3376         return ESR;
3377       return EvaluateStmt(Result, Info, IS->getElse(), Case);
3378     }
3379 
3380     case Stmt::WhileStmtClass: {
3381       EvalStmtResult ESR =
3382           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3383       if (ESR != ESR_Continue)
3384         return ESR;
3385       break;
3386     }
3387 
3388     case Stmt::ForStmtClass: {
3389       const ForStmt *FS = cast<ForStmt>(S);
3390       EvalStmtResult ESR =
3391           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3392       if (ESR != ESR_Continue)
3393         return ESR;
3394       if (FS->getInc()) {
3395         FullExpressionRAII IncScope(Info);
3396         if (!EvaluateIgnoredValue(Info, FS->getInc()))
3397           return ESR_Failed;
3398       }
3399       break;
3400     }
3401 
3402     case Stmt::DeclStmtClass:
3403       // FIXME: If the variable has initialization that can't be jumped over,
3404       // bail out of any immediately-surrounding compound-statement too.
3405     default:
3406       return ESR_CaseNotFound;
3407     }
3408   }
3409 
3410   switch (S->getStmtClass()) {
3411   default:
3412     if (const Expr *E = dyn_cast<Expr>(S)) {
3413       // Don't bother evaluating beyond an expression-statement which couldn't
3414       // be evaluated.
3415       FullExpressionRAII Scope(Info);
3416       if (!EvaluateIgnoredValue(Info, E))
3417         return ESR_Failed;
3418       return ESR_Succeeded;
3419     }
3420 
3421     Info.Diag(S->getLocStart());
3422     return ESR_Failed;
3423 
3424   case Stmt::NullStmtClass:
3425     return ESR_Succeeded;
3426 
3427   case Stmt::DeclStmtClass: {
3428     const DeclStmt *DS = cast<DeclStmt>(S);
3429     for (const auto *DclIt : DS->decls()) {
3430       // Each declaration initialization is its own full-expression.
3431       // FIXME: This isn't quite right; if we're performing aggregate
3432       // initialization, each braced subexpression is its own full-expression.
3433       FullExpressionRAII Scope(Info);
3434       if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
3435         return ESR_Failed;
3436     }
3437     return ESR_Succeeded;
3438   }
3439 
3440   case Stmt::ReturnStmtClass: {
3441     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3442     FullExpressionRAII Scope(Info);
3443     if (RetExpr && !Evaluate(Result, Info, RetExpr))
3444       return ESR_Failed;
3445     return ESR_Returned;
3446   }
3447 
3448   case Stmt::CompoundStmtClass: {
3449     BlockScopeRAII Scope(Info);
3450 
3451     const CompoundStmt *CS = cast<CompoundStmt>(S);
3452     for (const auto *BI : CS->body()) {
3453       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3454       if (ESR == ESR_Succeeded)
3455         Case = nullptr;
3456       else if (ESR != ESR_CaseNotFound)
3457         return ESR;
3458     }
3459     return Case ? ESR_CaseNotFound : ESR_Succeeded;
3460   }
3461 
3462   case Stmt::IfStmtClass: {
3463     const IfStmt *IS = cast<IfStmt>(S);
3464 
3465     // Evaluate the condition, as either a var decl or as an expression.
3466     BlockScopeRAII Scope(Info);
3467     bool Cond;
3468     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3469       return ESR_Failed;
3470 
3471     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3472       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3473       if (ESR != ESR_Succeeded)
3474         return ESR;
3475     }
3476     return ESR_Succeeded;
3477   }
3478 
3479   case Stmt::WhileStmtClass: {
3480     const WhileStmt *WS = cast<WhileStmt>(S);
3481     while (true) {
3482       BlockScopeRAII Scope(Info);
3483       bool Continue;
3484       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3485                         Continue))
3486         return ESR_Failed;
3487       if (!Continue)
3488         break;
3489 
3490       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3491       if (ESR != ESR_Continue)
3492         return ESR;
3493     }
3494     return ESR_Succeeded;
3495   }
3496 
3497   case Stmt::DoStmtClass: {
3498     const DoStmt *DS = cast<DoStmt>(S);
3499     bool Continue;
3500     do {
3501       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3502       if (ESR != ESR_Continue)
3503         return ESR;
3504       Case = nullptr;
3505 
3506       FullExpressionRAII CondScope(Info);
3507       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3508         return ESR_Failed;
3509     } while (Continue);
3510     return ESR_Succeeded;
3511   }
3512 
3513   case Stmt::ForStmtClass: {
3514     const ForStmt *FS = cast<ForStmt>(S);
3515     BlockScopeRAII Scope(Info);
3516     if (FS->getInit()) {
3517       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3518       if (ESR != ESR_Succeeded)
3519         return ESR;
3520     }
3521     while (true) {
3522       BlockScopeRAII Scope(Info);
3523       bool Continue = true;
3524       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3525                                          FS->getCond(), Continue))
3526         return ESR_Failed;
3527       if (!Continue)
3528         break;
3529 
3530       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3531       if (ESR != ESR_Continue)
3532         return ESR;
3533 
3534       if (FS->getInc()) {
3535         FullExpressionRAII IncScope(Info);
3536         if (!EvaluateIgnoredValue(Info, FS->getInc()))
3537           return ESR_Failed;
3538       }
3539     }
3540     return ESR_Succeeded;
3541   }
3542 
3543   case Stmt::CXXForRangeStmtClass: {
3544     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3545     BlockScopeRAII Scope(Info);
3546 
3547     // Initialize the __range variable.
3548     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3549     if (ESR != ESR_Succeeded)
3550       return ESR;
3551 
3552     // Create the __begin and __end iterators.
3553     ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3554     if (ESR != ESR_Succeeded)
3555       return ESR;
3556 
3557     while (true) {
3558       // Condition: __begin != __end.
3559       {
3560         bool Continue = true;
3561         FullExpressionRAII CondExpr(Info);
3562         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3563           return ESR_Failed;
3564         if (!Continue)
3565           break;
3566       }
3567 
3568       // User's variable declaration, initialized by *__begin.
3569       BlockScopeRAII InnerScope(Info);
3570       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3571       if (ESR != ESR_Succeeded)
3572         return ESR;
3573 
3574       // Loop body.
3575       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3576       if (ESR != ESR_Continue)
3577         return ESR;
3578 
3579       // Increment: ++__begin
3580       if (!EvaluateIgnoredValue(Info, FS->getInc()))
3581         return ESR_Failed;
3582     }
3583 
3584     return ESR_Succeeded;
3585   }
3586 
3587   case Stmt::SwitchStmtClass:
3588     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3589 
3590   case Stmt::ContinueStmtClass:
3591     return ESR_Continue;
3592 
3593   case Stmt::BreakStmtClass:
3594     return ESR_Break;
3595 
3596   case Stmt::LabelStmtClass:
3597     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3598 
3599   case Stmt::AttributedStmtClass:
3600     // As a general principle, C++11 attributes can be ignored without
3601     // any semantic impact.
3602     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3603                         Case);
3604 
3605   case Stmt::CaseStmtClass:
3606   case Stmt::DefaultStmtClass:
3607     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3608   }
3609 }
3610 
3611 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3612 /// default constructor. If so, we'll fold it whether or not it's marked as
3613 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3614 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)3615 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3616                                            const CXXConstructorDecl *CD,
3617                                            bool IsValueInitialization) {
3618   if (!CD->isTrivial() || !CD->isDefaultConstructor())
3619     return false;
3620 
3621   // Value-initialization does not call a trivial default constructor, so such a
3622   // call is a core constant expression whether or not the constructor is
3623   // constexpr.
3624   if (!CD->isConstexpr() && !IsValueInitialization) {
3625     if (Info.getLangOpts().CPlusPlus11) {
3626       // FIXME: If DiagDecl is an implicitly-declared special member function,
3627       // we should be much more explicit about why it's not constexpr.
3628       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3629         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3630       Info.Note(CD->getLocation(), diag::note_declared_at);
3631     } else {
3632       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3633     }
3634   }
3635   return true;
3636 }
3637 
3638 /// CheckConstexprFunction - Check that a function can be called in a constant
3639 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition)3640 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3641                                    const FunctionDecl *Declaration,
3642                                    const FunctionDecl *Definition) {
3643   // Potential constant expressions can contain calls to declared, but not yet
3644   // defined, constexpr functions.
3645   if (Info.checkingPotentialConstantExpression() && !Definition &&
3646       Declaration->isConstexpr())
3647     return false;
3648 
3649   // Bail out with no diagnostic if the function declaration itself is invalid.
3650   // We will have produced a relevant diagnostic while parsing it.
3651   if (Declaration->isInvalidDecl())
3652     return false;
3653 
3654   // Can we evaluate this function call?
3655   if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3656     return true;
3657 
3658   if (Info.getLangOpts().CPlusPlus11) {
3659     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3660     // FIXME: If DiagDecl is an implicitly-declared special member function, we
3661     // should be much more explicit about why it's not constexpr.
3662     Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3663       << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3664       << DiagDecl;
3665     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3666   } else {
3667     Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3668   }
3669   return false;
3670 }
3671 
3672 /// Determine if a class has any fields that might need to be copied by a
3673 /// trivial copy or move operation.
hasFields(const CXXRecordDecl * RD)3674 static bool hasFields(const CXXRecordDecl *RD) {
3675   if (!RD || RD->isEmpty())
3676     return false;
3677   for (auto *FD : RD->fields()) {
3678     if (FD->isUnnamedBitfield())
3679       continue;
3680     return true;
3681   }
3682   for (auto &Base : RD->bases())
3683     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3684       return true;
3685   return false;
3686 }
3687 
3688 namespace {
3689 typedef SmallVector<APValue, 8> ArgVector;
3690 }
3691 
3692 /// EvaluateArgs - Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,ArgVector & ArgValues,EvalInfo & Info)3693 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3694                          EvalInfo &Info) {
3695   bool Success = true;
3696   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3697        I != E; ++I) {
3698     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3699       // If we're checking for a potential constant expression, evaluate all
3700       // initializers even if some of them fail.
3701       if (!Info.keepEvaluatingAfterFailure())
3702         return false;
3703       Success = false;
3704     }
3705   }
3706   return Success;
3707 }
3708 
3709 /// Evaluate a function call.
HandleFunctionCall(SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,ArrayRef<const Expr * > Args,const Stmt * Body,EvalInfo & Info,APValue & Result)3710 static bool HandleFunctionCall(SourceLocation CallLoc,
3711                                const FunctionDecl *Callee, const LValue *This,
3712                                ArrayRef<const Expr*> Args, const Stmt *Body,
3713                                EvalInfo &Info, APValue &Result) {
3714   ArgVector ArgValues(Args.size());
3715   if (!EvaluateArgs(Args, ArgValues, Info))
3716     return false;
3717 
3718   if (!Info.CheckCallLimit(CallLoc))
3719     return false;
3720 
3721   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3722 
3723   // For a trivial copy or move assignment, perform an APValue copy. This is
3724   // essential for unions, where the operations performed by the assignment
3725   // operator cannot be represented as statements.
3726   //
3727   // Skip this for non-union classes with no fields; in that case, the defaulted
3728   // copy/move does not actually read the object.
3729   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3730   if (MD && MD->isDefaulted() && MD->isTrivial() &&
3731       (MD->getParent()->isUnion() || hasFields(MD->getParent()))) {
3732     assert(This &&
3733            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3734     LValue RHS;
3735     RHS.setFrom(Info.Ctx, ArgValues[0]);
3736     APValue RHSValue;
3737     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3738                                         RHS, RHSValue))
3739       return false;
3740     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3741                           RHSValue))
3742       return false;
3743     This->moveInto(Result);
3744     return true;
3745   }
3746 
3747   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
3748   if (ESR == ESR_Succeeded) {
3749     if (Callee->getReturnType()->isVoidType())
3750       return true;
3751     Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3752   }
3753   return ESR == ESR_Returned;
3754 }
3755 
3756 /// Evaluate a constructor call.
HandleConstructorCall(SourceLocation CallLoc,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)3757 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
3758                                   ArrayRef<const Expr*> Args,
3759                                   const CXXConstructorDecl *Definition,
3760                                   EvalInfo &Info, APValue &Result) {
3761   ArgVector ArgValues(Args.size());
3762   if (!EvaluateArgs(Args, ArgValues, Info))
3763     return false;
3764 
3765   if (!Info.CheckCallLimit(CallLoc))
3766     return false;
3767 
3768   const CXXRecordDecl *RD = Definition->getParent();
3769   if (RD->getNumVBases()) {
3770     Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3771     return false;
3772   }
3773 
3774   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
3775 
3776   // If it's a delegating constructor, just delegate.
3777   if (Definition->isDelegatingConstructor()) {
3778     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
3779     {
3780       FullExpressionRAII InitScope(Info);
3781       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3782         return false;
3783     }
3784     return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3785   }
3786 
3787   // For a trivial copy or move constructor, perform an APValue copy. This is
3788   // essential for unions (or classes with anonymous union members), where the
3789   // operations performed by the constructor cannot be represented by
3790   // ctor-initializers.
3791   //
3792   // Skip this for empty non-union classes; we should not perform an
3793   // lvalue-to-rvalue conversion on them because their copy constructor does not
3794   // actually read them.
3795   if (Definition->isDefaulted() &&
3796       ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3797        (Definition->isMoveConstructor() && Definition->isTrivial())) &&
3798       (Definition->getParent()->isUnion() ||
3799        hasFields(Definition->getParent()))) {
3800     LValue RHS;
3801     RHS.setFrom(Info.Ctx, ArgValues[0]);
3802     return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3803                                           RHS, Result);
3804   }
3805 
3806   // Reserve space for the struct members.
3807   if (!RD->isUnion() && Result.isUninit())
3808     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3809                      std::distance(RD->field_begin(), RD->field_end()));
3810 
3811   if (RD->isInvalidDecl()) return false;
3812   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3813 
3814   // A scope for temporaries lifetime-extended by reference members.
3815   BlockScopeRAII LifetimeExtendedScope(Info);
3816 
3817   bool Success = true;
3818   unsigned BasesSeen = 0;
3819 #ifndef NDEBUG
3820   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3821 #endif
3822   for (const auto *I : Definition->inits()) {
3823     LValue Subobject = This;
3824     APValue *Value = &Result;
3825 
3826     // Determine the subobject to initialize.
3827     FieldDecl *FD = nullptr;
3828     if (I->isBaseInitializer()) {
3829       QualType BaseType(I->getBaseClass(), 0);
3830 #ifndef NDEBUG
3831       // Non-virtual base classes are initialized in the order in the class
3832       // definition. We have already checked for virtual base classes.
3833       assert(!BaseIt->isVirtual() && "virtual base for literal type");
3834       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3835              "base class initializers not in expected order");
3836       ++BaseIt;
3837 #endif
3838       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
3839                                   BaseType->getAsCXXRecordDecl(), &Layout))
3840         return false;
3841       Value = &Result.getStructBase(BasesSeen++);
3842     } else if ((FD = I->getMember())) {
3843       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
3844         return false;
3845       if (RD->isUnion()) {
3846         Result = APValue(FD);
3847         Value = &Result.getUnionValue();
3848       } else {
3849         Value = &Result.getStructField(FD->getFieldIndex());
3850       }
3851     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
3852       // Walk the indirect field decl's chain to find the object to initialize,
3853       // and make sure we've initialized every step along it.
3854       for (auto *C : IFD->chain()) {
3855         FD = cast<FieldDecl>(C);
3856         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3857         // Switch the union field if it differs. This happens if we had
3858         // preceding zero-initialization, and we're now initializing a union
3859         // subobject other than the first.
3860         // FIXME: In this case, the values of the other subobjects are
3861         // specified, since zero-initialization sets all padding bits to zero.
3862         if (Value->isUninit() ||
3863             (Value->isUnion() && Value->getUnionField() != FD)) {
3864           if (CD->isUnion())
3865             *Value = APValue(FD);
3866           else
3867             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3868                              std::distance(CD->field_begin(), CD->field_end()));
3869         }
3870         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
3871           return false;
3872         if (CD->isUnion())
3873           Value = &Value->getUnionValue();
3874         else
3875           Value = &Value->getStructField(FD->getFieldIndex());
3876       }
3877     } else {
3878       llvm_unreachable("unknown base initializer kind");
3879     }
3880 
3881     FullExpressionRAII InitScope(Info);
3882     if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3883         (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
3884                                                           *Value, FD))) {
3885       // If we're checking for a potential constant expression, evaluate all
3886       // initializers even if some of them fail.
3887       if (!Info.keepEvaluatingAfterFailure())
3888         return false;
3889       Success = false;
3890     }
3891   }
3892 
3893   return Success &&
3894          EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3895 }
3896 
3897 //===----------------------------------------------------------------------===//
3898 // Generic Evaluation
3899 //===----------------------------------------------------------------------===//
3900 namespace {
3901 
3902 template <class Derived>
3903 class ExprEvaluatorBase
3904   : public ConstStmtVisitor<Derived, bool> {
3905 private:
DerivedSuccess(const APValue & V,const Expr * E)3906   bool DerivedSuccess(const APValue &V, const Expr *E) {
3907     return static_cast<Derived*>(this)->Success(V, E);
3908   }
DerivedZeroInitialization(const Expr * E)3909   bool DerivedZeroInitialization(const Expr *E) {
3910     return static_cast<Derived*>(this)->ZeroInitialization(E);
3911   }
3912 
3913   // Check whether a conditional operator with a non-constant condition is a
3914   // potential constant expression. If neither arm is a potential constant
3915   // expression, then the conditional operator is not either.
3916   template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)3917   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3918     assert(Info.checkingPotentialConstantExpression());
3919 
3920     // Speculatively evaluate both arms.
3921     {
3922       SmallVector<PartialDiagnosticAt, 8> Diag;
3923       SpeculativeEvaluationRAII Speculate(Info, &Diag);
3924 
3925       StmtVisitorTy::Visit(E->getFalseExpr());
3926       if (Diag.empty())
3927         return;
3928 
3929       Diag.clear();
3930       StmtVisitorTy::Visit(E->getTrueExpr());
3931       if (Diag.empty())
3932         return;
3933     }
3934 
3935     Error(E, diag::note_constexpr_conditional_never_const);
3936   }
3937 
3938 
3939   template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)3940   bool HandleConditionalOperator(const ConditionalOperator *E) {
3941     bool BoolResult;
3942     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3943       if (Info.checkingPotentialConstantExpression())
3944         CheckPotentialConstantConditional(E);
3945       return false;
3946     }
3947 
3948     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3949     return StmtVisitorTy::Visit(EvalExpr);
3950   }
3951 
3952 protected:
3953   EvalInfo &Info;
3954   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
3955   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3956 
CCEDiag(const Expr * E,diag::kind D)3957   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
3958     return Info.CCEDiag(E, D);
3959   }
3960 
ZeroInitialization(const Expr * E)3961   bool ZeroInitialization(const Expr *E) { return Error(E); }
3962 
3963 public:
ExprEvaluatorBase(EvalInfo & Info)3964   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3965 
getEvalInfo()3966   EvalInfo &getEvalInfo() { return Info; }
3967 
3968   /// Report an evaluation error. This should only be called when an error is
3969   /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)3970   bool Error(const Expr *E, diag::kind D) {
3971     Info.Diag(E, D);
3972     return false;
3973   }
Error(const Expr * E)3974   bool Error(const Expr *E) {
3975     return Error(E, diag::note_invalid_subexpr_in_const_expr);
3976   }
3977 
VisitStmt(const Stmt *)3978   bool VisitStmt(const Stmt *) {
3979     llvm_unreachable("Expression evaluator should not be called on stmts");
3980   }
VisitExpr(const Expr * E)3981   bool VisitExpr(const Expr *E) {
3982     return Error(E);
3983   }
3984 
VisitParenExpr(const ParenExpr * E)3985   bool VisitParenExpr(const ParenExpr *E)
3986     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)3987   bool VisitUnaryExtension(const UnaryOperator *E)
3988     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)3989   bool VisitUnaryPlus(const UnaryOperator *E)
3990     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)3991   bool VisitChooseExpr(const ChooseExpr *E)
3992     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)3993   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3994     { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)3995   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3996     { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)3997   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3998     { return StmtVisitorTy::Visit(E->getExpr()); }
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * E)3999   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4000     // The initializer may not have been parsed yet, or might be erroneous.
4001     if (!E->getExpr())
4002       return Error(E);
4003     return StmtVisitorTy::Visit(E->getExpr());
4004   }
4005   // We cannot create any objects for which cleanups are required, so there is
4006   // nothing to do here; all cleanups must come from unevaluated subexpressions.
VisitExprWithCleanups(const ExprWithCleanups * E)4007   bool VisitExprWithCleanups(const ExprWithCleanups *E)
4008     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4009 
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)4010   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4011     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4012     return static_cast<Derived*>(this)->VisitCastExpr(E);
4013   }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)4014   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4015     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4016     return static_cast<Derived*>(this)->VisitCastExpr(E);
4017   }
4018 
VisitBinaryOperator(const BinaryOperator * E)4019   bool VisitBinaryOperator(const BinaryOperator *E) {
4020     switch (E->getOpcode()) {
4021     default:
4022       return Error(E);
4023 
4024     case BO_Comma:
4025       VisitIgnoredValue(E->getLHS());
4026       return StmtVisitorTy::Visit(E->getRHS());
4027 
4028     case BO_PtrMemD:
4029     case BO_PtrMemI: {
4030       LValue Obj;
4031       if (!HandleMemberPointerAccess(Info, E, Obj))
4032         return false;
4033       APValue Result;
4034       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4035         return false;
4036       return DerivedSuccess(Result, E);
4037     }
4038     }
4039   }
4040 
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)4041   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4042     // Evaluate and cache the common expression. We treat it as a temporary,
4043     // even though it's not quite the same thing.
4044     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4045                   Info, E->getCommon()))
4046       return false;
4047 
4048     return HandleConditionalOperator(E);
4049   }
4050 
VisitConditionalOperator(const ConditionalOperator * E)4051   bool VisitConditionalOperator(const ConditionalOperator *E) {
4052     bool IsBcpCall = false;
4053     // If the condition (ignoring parens) is a __builtin_constant_p call,
4054     // the result is a constant expression if it can be folded without
4055     // side-effects. This is an important GNU extension. See GCC PR38377
4056     // for discussion.
4057     if (const CallExpr *CallCE =
4058           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4059       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4060         IsBcpCall = true;
4061 
4062     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4063     // constant expression; we can't check whether it's potentially foldable.
4064     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4065       return false;
4066 
4067     FoldConstant Fold(Info, IsBcpCall);
4068     if (!HandleConditionalOperator(E)) {
4069       Fold.keepDiagnostics();
4070       return false;
4071     }
4072 
4073     return true;
4074   }
4075 
VisitOpaqueValueExpr(const OpaqueValueExpr * E)4076   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4077     if (APValue *Value = Info.CurrentCall->getTemporary(E))
4078       return DerivedSuccess(*Value, E);
4079 
4080     const Expr *Source = E->getSourceExpr();
4081     if (!Source)
4082       return Error(E);
4083     if (Source == E) { // sanity checking.
4084       assert(0 && "OpaqueValueExpr recursively refers to itself");
4085       return Error(E);
4086     }
4087     return StmtVisitorTy::Visit(Source);
4088   }
4089 
VisitCallExpr(const CallExpr * E)4090   bool VisitCallExpr(const CallExpr *E) {
4091     const Expr *Callee = E->getCallee()->IgnoreParens();
4092     QualType CalleeType = Callee->getType();
4093 
4094     const FunctionDecl *FD = nullptr;
4095     LValue *This = nullptr, ThisVal;
4096     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4097     bool HasQualifier = false;
4098 
4099     // Extract function decl and 'this' pointer from the callee.
4100     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4101       const ValueDecl *Member = nullptr;
4102       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4103         // Explicit bound member calls, such as x.f() or p->g();
4104         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4105           return false;
4106         Member = ME->getMemberDecl();
4107         This = &ThisVal;
4108         HasQualifier = ME->hasQualifier();
4109       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4110         // Indirect bound member calls ('.*' or '->*').
4111         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4112         if (!Member) return false;
4113         This = &ThisVal;
4114       } else
4115         return Error(Callee);
4116 
4117       FD = dyn_cast<FunctionDecl>(Member);
4118       if (!FD)
4119         return Error(Callee);
4120     } else if (CalleeType->isFunctionPointerType()) {
4121       LValue Call;
4122       if (!EvaluatePointer(Callee, Call, Info))
4123         return false;
4124 
4125       if (!Call.getLValueOffset().isZero())
4126         return Error(Callee);
4127       FD = dyn_cast_or_null<FunctionDecl>(
4128                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
4129       if (!FD)
4130         return Error(Callee);
4131 
4132       // Overloaded operator calls to member functions are represented as normal
4133       // calls with '*this' as the first argument.
4134       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4135       if (MD && !MD->isStatic()) {
4136         // FIXME: When selecting an implicit conversion for an overloaded
4137         // operator delete, we sometimes try to evaluate calls to conversion
4138         // operators without a 'this' parameter!
4139         if (Args.empty())
4140           return Error(E);
4141 
4142         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4143           return false;
4144         This = &ThisVal;
4145         Args = Args.slice(1);
4146       }
4147 
4148       // Don't call function pointers which have been cast to some other type.
4149       if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
4150         return Error(E);
4151     } else
4152       return Error(E);
4153 
4154     if (This && !This->checkSubobject(Info, E, CSK_This))
4155       return false;
4156 
4157     // DR1358 allows virtual constexpr functions in some cases. Don't allow
4158     // calls to such functions in constant expressions.
4159     if (This && !HasQualifier &&
4160         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4161       return Error(E, diag::note_constexpr_virtual_call);
4162 
4163     const FunctionDecl *Definition = nullptr;
4164     Stmt *Body = FD->getBody(Definition);
4165     APValue Result;
4166 
4167     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
4168         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4169                             Info, Result))
4170       return false;
4171 
4172     return DerivedSuccess(Result, E);
4173   }
4174 
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)4175   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4176     return StmtVisitorTy::Visit(E->getInitializer());
4177   }
VisitInitListExpr(const InitListExpr * E)4178   bool VisitInitListExpr(const InitListExpr *E) {
4179     if (E->getNumInits() == 0)
4180       return DerivedZeroInitialization(E);
4181     if (E->getNumInits() == 1)
4182       return StmtVisitorTy::Visit(E->getInit(0));
4183     return Error(E);
4184   }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)4185   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4186     return DerivedZeroInitialization(E);
4187   }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)4188   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4189     return DerivedZeroInitialization(E);
4190   }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)4191   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4192     return DerivedZeroInitialization(E);
4193   }
4194 
4195   /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)4196   bool VisitMemberExpr(const MemberExpr *E) {
4197     assert(!E->isArrow() && "missing call to bound member function?");
4198 
4199     APValue Val;
4200     if (!Evaluate(Val, Info, E->getBase()))
4201       return false;
4202 
4203     QualType BaseTy = E->getBase()->getType();
4204 
4205     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4206     if (!FD) return Error(E);
4207     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4208     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4209            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4210 
4211     CompleteObject Obj(&Val, BaseTy);
4212     SubobjectDesignator Designator(BaseTy);
4213     Designator.addDeclUnchecked(FD);
4214 
4215     APValue Result;
4216     return extractSubobject(Info, E, Obj, Designator, Result) &&
4217            DerivedSuccess(Result, E);
4218   }
4219 
VisitCastExpr(const CastExpr * E)4220   bool VisitCastExpr(const CastExpr *E) {
4221     switch (E->getCastKind()) {
4222     default:
4223       break;
4224 
4225     case CK_AtomicToNonAtomic: {
4226       APValue AtomicVal;
4227       if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4228         return false;
4229       return DerivedSuccess(AtomicVal, E);
4230     }
4231 
4232     case CK_NoOp:
4233     case CK_UserDefinedConversion:
4234       return StmtVisitorTy::Visit(E->getSubExpr());
4235 
4236     case CK_LValueToRValue: {
4237       LValue LVal;
4238       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4239         return false;
4240       APValue RVal;
4241       // Note, we use the subexpression's type in order to retain cv-qualifiers.
4242       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4243                                           LVal, RVal))
4244         return false;
4245       return DerivedSuccess(RVal, E);
4246     }
4247     }
4248 
4249     return Error(E);
4250   }
4251 
VisitUnaryPostInc(const UnaryOperator * UO)4252   bool VisitUnaryPostInc(const UnaryOperator *UO) {
4253     return VisitUnaryPostIncDec(UO);
4254   }
VisitUnaryPostDec(const UnaryOperator * UO)4255   bool VisitUnaryPostDec(const UnaryOperator *UO) {
4256     return VisitUnaryPostIncDec(UO);
4257   }
VisitUnaryPostIncDec(const UnaryOperator * UO)4258   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4259     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4260       return Error(UO);
4261 
4262     LValue LVal;
4263     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4264       return false;
4265     APValue RVal;
4266     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4267                       UO->isIncrementOp(), &RVal))
4268       return false;
4269     return DerivedSuccess(RVal, UO);
4270   }
4271 
VisitStmtExpr(const StmtExpr * E)4272   bool VisitStmtExpr(const StmtExpr *E) {
4273     // We will have checked the full-expressions inside the statement expression
4274     // when they were completed, and don't need to check them again now.
4275     if (Info.checkingForOverflow())
4276       return Error(E);
4277 
4278     BlockScopeRAII Scope(Info);
4279     const CompoundStmt *CS = E->getSubStmt();
4280     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4281                                            BE = CS->body_end();
4282          /**/; ++BI) {
4283       if (BI + 1 == BE) {
4284         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4285         if (!FinalExpr) {
4286           Info.Diag((*BI)->getLocStart(),
4287                     diag::note_constexpr_stmt_expr_unsupported);
4288           return false;
4289         }
4290         return this->Visit(FinalExpr);
4291       }
4292 
4293       APValue ReturnValue;
4294       EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4295       if (ESR != ESR_Succeeded) {
4296         // FIXME: If the statement-expression terminated due to 'return',
4297         // 'break', or 'continue', it would be nice to propagate that to
4298         // the outer statement evaluation rather than bailing out.
4299         if (ESR != ESR_Failed)
4300           Info.Diag((*BI)->getLocStart(),
4301                     diag::note_constexpr_stmt_expr_unsupported);
4302         return false;
4303       }
4304     }
4305   }
4306 
4307   /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)4308   void VisitIgnoredValue(const Expr *E) {
4309     EvaluateIgnoredValue(Info, E);
4310   }
4311 };
4312 
4313 }
4314 
4315 //===----------------------------------------------------------------------===//
4316 // Common base class for lvalue and temporary evaluation.
4317 //===----------------------------------------------------------------------===//
4318 namespace {
4319 template<class Derived>
4320 class LValueExprEvaluatorBase
4321   : public ExprEvaluatorBase<Derived> {
4322 protected:
4323   LValue &Result;
4324   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4325   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4326 
Success(APValue::LValueBase B)4327   bool Success(APValue::LValueBase B) {
4328     Result.set(B);
4329     return true;
4330   }
4331 
4332 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result)4333   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4334     ExprEvaluatorBaseTy(Info), Result(Result) {}
4335 
Success(const APValue & V,const Expr * E)4336   bool Success(const APValue &V, const Expr *E) {
4337     Result.setFrom(this->Info.Ctx, V);
4338     return true;
4339   }
4340 
VisitMemberExpr(const MemberExpr * E)4341   bool VisitMemberExpr(const MemberExpr *E) {
4342     // Handle non-static data members.
4343     QualType BaseTy;
4344     if (E->isArrow()) {
4345       if (!EvaluatePointer(E->getBase(), Result, this->Info))
4346         return false;
4347       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4348     } else if (E->getBase()->isRValue()) {
4349       assert(E->getBase()->getType()->isRecordType());
4350       if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4351         return false;
4352       BaseTy = E->getBase()->getType();
4353     } else {
4354       if (!this->Visit(E->getBase()))
4355         return false;
4356       BaseTy = E->getBase()->getType();
4357     }
4358 
4359     const ValueDecl *MD = E->getMemberDecl();
4360     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4361       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4362              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4363       (void)BaseTy;
4364       if (!HandleLValueMember(this->Info, E, Result, FD))
4365         return false;
4366     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4367       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4368         return false;
4369     } else
4370       return this->Error(E);
4371 
4372     if (MD->getType()->isReferenceType()) {
4373       APValue RefValue;
4374       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4375                                           RefValue))
4376         return false;
4377       return Success(RefValue, E);
4378     }
4379     return true;
4380   }
4381 
VisitBinaryOperator(const BinaryOperator * E)4382   bool VisitBinaryOperator(const BinaryOperator *E) {
4383     switch (E->getOpcode()) {
4384     default:
4385       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4386 
4387     case BO_PtrMemD:
4388     case BO_PtrMemI:
4389       return HandleMemberPointerAccess(this->Info, E, Result);
4390     }
4391   }
4392 
VisitCastExpr(const CastExpr * E)4393   bool VisitCastExpr(const CastExpr *E) {
4394     switch (E->getCastKind()) {
4395     default:
4396       return ExprEvaluatorBaseTy::VisitCastExpr(E);
4397 
4398     case CK_DerivedToBase:
4399     case CK_UncheckedDerivedToBase:
4400       if (!this->Visit(E->getSubExpr()))
4401         return false;
4402 
4403       // Now figure out the necessary offset to add to the base LV to get from
4404       // the derived class to the base class.
4405       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4406                                   Result);
4407     }
4408   }
4409 };
4410 }
4411 
4412 //===----------------------------------------------------------------------===//
4413 // LValue Evaluation
4414 //
4415 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4416 // function designators (in C), decl references to void objects (in C), and
4417 // temporaries (if building with -Wno-address-of-temporary).
4418 //
4419 // LValue evaluation produces values comprising a base expression of one of the
4420 // following types:
4421 // - Declarations
4422 //  * VarDecl
4423 //  * FunctionDecl
4424 // - Literals
4425 //  * CompoundLiteralExpr in C
4426 //  * StringLiteral
4427 //  * CXXTypeidExpr
4428 //  * PredefinedExpr
4429 //  * ObjCStringLiteralExpr
4430 //  * ObjCEncodeExpr
4431 //  * AddrLabelExpr
4432 //  * BlockExpr
4433 //  * CallExpr for a MakeStringConstant builtin
4434 // - Locals and temporaries
4435 //  * MaterializeTemporaryExpr
4436 //  * Any Expr, with a CallIndex indicating the function in which the temporary
4437 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
4438 //    from the AST (FIXME).
4439 //  * A MaterializeTemporaryExpr that has static storage duration, with no
4440 //    CallIndex, for a lifetime-extended temporary.
4441 // plus an offset in bytes.
4442 //===----------------------------------------------------------------------===//
4443 namespace {
4444 class LValueExprEvaluator
4445   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4446 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result)4447   LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4448     LValueExprEvaluatorBaseTy(Info, Result) {}
4449 
4450   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4451   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4452 
4453   bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)4454   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4455   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4456   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4457   bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)4458   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)4459   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4460   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4461   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4462   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4463   bool VisitUnaryDeref(const UnaryOperator *E);
4464   bool VisitUnaryReal(const UnaryOperator *E);
4465   bool VisitUnaryImag(const UnaryOperator *E);
VisitUnaryPreInc(const UnaryOperator * UO)4466   bool VisitUnaryPreInc(const UnaryOperator *UO) {
4467     return VisitUnaryPreIncDec(UO);
4468   }
VisitUnaryPreDec(const UnaryOperator * UO)4469   bool VisitUnaryPreDec(const UnaryOperator *UO) {
4470     return VisitUnaryPreIncDec(UO);
4471   }
4472   bool VisitBinAssign(const BinaryOperator *BO);
4473   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4474 
VisitCastExpr(const CastExpr * E)4475   bool VisitCastExpr(const CastExpr *E) {
4476     switch (E->getCastKind()) {
4477     default:
4478       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4479 
4480     case CK_LValueBitCast:
4481       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4482       if (!Visit(E->getSubExpr()))
4483         return false;
4484       Result.Designator.setInvalid();
4485       return true;
4486 
4487     case CK_BaseToDerived:
4488       if (!Visit(E->getSubExpr()))
4489         return false;
4490       return HandleBaseToDerivedCast(Info, E, Result);
4491     }
4492   }
4493 };
4494 } // end anonymous namespace
4495 
4496 /// Evaluate an expression as an lvalue. This can be legitimately called on
4497 /// expressions which are not glvalues, in two cases:
4498 ///  * function designators in C, and
4499 ///  * "extern void" objects
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info)4500 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4501   assert(E->isGLValue() || E->getType()->isFunctionType() ||
4502          E->getType()->isVoidType());
4503   return LValueExprEvaluator(Info, Result).Visit(E);
4504 }
4505 
VisitDeclRefExpr(const DeclRefExpr * E)4506 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4507   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4508     return Success(FD);
4509   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4510     return VisitVarDecl(E, VD);
4511   return Error(E);
4512 }
4513 
VisitVarDecl(const Expr * E,const VarDecl * VD)4514 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4515   CallStackFrame *Frame = nullptr;
4516   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4517     Frame = Info.CurrentCall;
4518 
4519   if (!VD->getType()->isReferenceType()) {
4520     if (Frame) {
4521       Result.set(VD, Frame->Index);
4522       return true;
4523     }
4524     return Success(VD);
4525   }
4526 
4527   APValue *V;
4528   if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4529     return false;
4530   if (V->isUninit()) {
4531     if (!Info.checkingPotentialConstantExpression())
4532       Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4533     return false;
4534   }
4535   return Success(*V, E);
4536 }
4537 
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)4538 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4539     const MaterializeTemporaryExpr *E) {
4540   // Walk through the expression to find the materialized temporary itself.
4541   SmallVector<const Expr *, 2> CommaLHSs;
4542   SmallVector<SubobjectAdjustment, 2> Adjustments;
4543   const Expr *Inner = E->GetTemporaryExpr()->
4544       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4545 
4546   // If we passed any comma operators, evaluate their LHSs.
4547   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4548     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4549       return false;
4550 
4551   // A materialized temporary with static storage duration can appear within the
4552   // result of a constant expression evaluation, so we need to preserve its
4553   // value for use outside this evaluation.
4554   APValue *Value;
4555   if (E->getStorageDuration() == SD_Static) {
4556     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4557     *Value = APValue();
4558     Result.set(E);
4559   } else {
4560     Value = &Info.CurrentCall->
4561         createTemporary(E, E->getStorageDuration() == SD_Automatic);
4562     Result.set(E, Info.CurrentCall->Index);
4563   }
4564 
4565   QualType Type = Inner->getType();
4566 
4567   // Materialize the temporary itself.
4568   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4569       (E->getStorageDuration() == SD_Static &&
4570        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4571     *Value = APValue();
4572     return false;
4573   }
4574 
4575   // Adjust our lvalue to refer to the desired subobject.
4576   for (unsigned I = Adjustments.size(); I != 0; /**/) {
4577     --I;
4578     switch (Adjustments[I].Kind) {
4579     case SubobjectAdjustment::DerivedToBaseAdjustment:
4580       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4581                                 Type, Result))
4582         return false;
4583       Type = Adjustments[I].DerivedToBase.BasePath->getType();
4584       break;
4585 
4586     case SubobjectAdjustment::FieldAdjustment:
4587       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4588         return false;
4589       Type = Adjustments[I].Field->getType();
4590       break;
4591 
4592     case SubobjectAdjustment::MemberPointerAdjustment:
4593       if (!HandleMemberPointerAccess(this->Info, Type, Result,
4594                                      Adjustments[I].Ptr.RHS))
4595         return false;
4596       Type = Adjustments[I].Ptr.MPT->getPointeeType();
4597       break;
4598     }
4599   }
4600 
4601   return true;
4602 }
4603 
4604 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)4605 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4606   assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4607   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4608   // only see this when folding in C, so there's no standard to follow here.
4609   return Success(E);
4610 }
4611 
VisitCXXTypeidExpr(const CXXTypeidExpr * E)4612 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4613   if (!E->isPotentiallyEvaluated())
4614     return Success(E);
4615 
4616   Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4617     << E->getExprOperand()->getType()
4618     << E->getExprOperand()->getSourceRange();
4619   return false;
4620 }
4621 
VisitCXXUuidofExpr(const CXXUuidofExpr * E)4622 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4623   return Success(E);
4624 }
4625 
VisitMemberExpr(const MemberExpr * E)4626 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4627   // Handle static data members.
4628   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4629     VisitIgnoredValue(E->getBase());
4630     return VisitVarDecl(E, VD);
4631   }
4632 
4633   // Handle static member functions.
4634   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4635     if (MD->isStatic()) {
4636       VisitIgnoredValue(E->getBase());
4637       return Success(MD);
4638     }
4639   }
4640 
4641   // Handle non-static data members.
4642   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4643 }
4644 
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)4645 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4646   // FIXME: Deal with vectors as array subscript bases.
4647   if (E->getBase()->getType()->isVectorType())
4648     return Error(E);
4649 
4650   if (!EvaluatePointer(E->getBase(), Result, Info))
4651     return false;
4652 
4653   APSInt Index;
4654   if (!EvaluateInteger(E->getIdx(), Index, Info))
4655     return false;
4656 
4657   return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4658                                      getExtValue(Index));
4659 }
4660 
VisitUnaryDeref(const UnaryOperator * E)4661 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4662   return EvaluatePointer(E->getSubExpr(), Result, Info);
4663 }
4664 
VisitUnaryReal(const UnaryOperator * E)4665 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4666   if (!Visit(E->getSubExpr()))
4667     return false;
4668   // __real is a no-op on scalar lvalues.
4669   if (E->getSubExpr()->getType()->isAnyComplexType())
4670     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4671   return true;
4672 }
4673 
VisitUnaryImag(const UnaryOperator * E)4674 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4675   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4676          "lvalue __imag__ on scalar?");
4677   if (!Visit(E->getSubExpr()))
4678     return false;
4679   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4680   return true;
4681 }
4682 
VisitUnaryPreIncDec(const UnaryOperator * UO)4683 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4684   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4685     return Error(UO);
4686 
4687   if (!this->Visit(UO->getSubExpr()))
4688     return false;
4689 
4690   return handleIncDec(
4691       this->Info, UO, Result, UO->getSubExpr()->getType(),
4692       UO->isIncrementOp(), nullptr);
4693 }
4694 
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)4695 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4696     const CompoundAssignOperator *CAO) {
4697   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4698     return Error(CAO);
4699 
4700   APValue RHS;
4701 
4702   // The overall lvalue result is the result of evaluating the LHS.
4703   if (!this->Visit(CAO->getLHS())) {
4704     if (Info.keepEvaluatingAfterFailure())
4705       Evaluate(RHS, this->Info, CAO->getRHS());
4706     return false;
4707   }
4708 
4709   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4710     return false;
4711 
4712   return handleCompoundAssignment(
4713       this->Info, CAO,
4714       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4715       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4716 }
4717 
VisitBinAssign(const BinaryOperator * E)4718 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4719   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4720     return Error(E);
4721 
4722   APValue NewVal;
4723 
4724   if (!this->Visit(E->getLHS())) {
4725     if (Info.keepEvaluatingAfterFailure())
4726       Evaluate(NewVal, this->Info, E->getRHS());
4727     return false;
4728   }
4729 
4730   if (!Evaluate(NewVal, this->Info, E->getRHS()))
4731     return false;
4732 
4733   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4734                           NewVal);
4735 }
4736 
4737 //===----------------------------------------------------------------------===//
4738 // Pointer Evaluation
4739 //===----------------------------------------------------------------------===//
4740 
4741 namespace {
4742 class PointerExprEvaluator
4743   : public ExprEvaluatorBase<PointerExprEvaluator> {
4744   LValue &Result;
4745 
Success(const Expr * E)4746   bool Success(const Expr *E) {
4747     Result.set(E);
4748     return true;
4749   }
4750 public:
4751 
PointerExprEvaluator(EvalInfo & info,LValue & Result)4752   PointerExprEvaluator(EvalInfo &info, LValue &Result)
4753     : ExprEvaluatorBaseTy(info), Result(Result) {}
4754 
Success(const APValue & V,const Expr * E)4755   bool Success(const APValue &V, const Expr *E) {
4756     Result.setFrom(Info.Ctx, V);
4757     return true;
4758   }
ZeroInitialization(const Expr * E)4759   bool ZeroInitialization(const Expr *E) {
4760     return Success((Expr*)nullptr);
4761   }
4762 
4763   bool VisitBinaryOperator(const BinaryOperator *E);
4764   bool VisitCastExpr(const CastExpr* E);
4765   bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)4766   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
4767       { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)4768   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
4769       { return Success(E); }
VisitAddrLabelExpr(const AddrLabelExpr * E)4770   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
4771       { return Success(E); }
4772   bool VisitCallExpr(const CallExpr *E);
VisitBlockExpr(const BlockExpr * E)4773   bool VisitBlockExpr(const BlockExpr *E) {
4774     if (!E->getBlockDecl()->hasCaptures())
4775       return Success(E);
4776     return Error(E);
4777   }
VisitCXXThisExpr(const CXXThisExpr * E)4778   bool VisitCXXThisExpr(const CXXThisExpr *E) {
4779     // Can't look at 'this' when checking a potential constant expression.
4780     if (Info.checkingPotentialConstantExpression())
4781       return false;
4782     if (!Info.CurrentCall->This) {
4783       if (Info.getLangOpts().CPlusPlus11)
4784         Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4785       else
4786         Info.Diag(E);
4787       return false;
4788     }
4789     Result = *Info.CurrentCall->This;
4790     return true;
4791   }
4792 
4793   // FIXME: Missing: @protocol, @selector
4794 };
4795 } // end anonymous namespace
4796 
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info)4797 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
4798   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
4799   return PointerExprEvaluator(Info, Result).Visit(E);
4800 }
4801 
VisitBinaryOperator(const BinaryOperator * E)4802 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4803   if (E->getOpcode() != BO_Add &&
4804       E->getOpcode() != BO_Sub)
4805     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4806 
4807   const Expr *PExp = E->getLHS();
4808   const Expr *IExp = E->getRHS();
4809   if (IExp->getType()->isPointerType())
4810     std::swap(PExp, IExp);
4811 
4812   bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4813   if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
4814     return false;
4815 
4816   llvm::APSInt Offset;
4817   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
4818     return false;
4819 
4820   int64_t AdditionalOffset = getExtValue(Offset);
4821   if (E->getOpcode() == BO_Sub)
4822     AdditionalOffset = -AdditionalOffset;
4823 
4824   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
4825   return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4826                                      AdditionalOffset);
4827 }
4828 
VisitUnaryAddrOf(const UnaryOperator * E)4829 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4830   return EvaluateLValue(E->getSubExpr(), Result, Info);
4831 }
4832 
VisitCastExpr(const CastExpr * E)4833 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4834   const Expr* SubExpr = E->getSubExpr();
4835 
4836   switch (E->getCastKind()) {
4837   default:
4838     break;
4839 
4840   case CK_BitCast:
4841   case CK_CPointerToObjCPointerCast:
4842   case CK_BlockPointerToObjCPointerCast:
4843   case CK_AnyPointerToBlockPointerCast:
4844   case CK_AddressSpaceConversion:
4845     if (!Visit(SubExpr))
4846       return false;
4847     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4848     // permitted in constant expressions in C++11. Bitcasts from cv void* are
4849     // also static_casts, but we disallow them as a resolution to DR1312.
4850     if (!E->getType()->isVoidPointerType()) {
4851       Result.Designator.setInvalid();
4852       if (SubExpr->getType()->isVoidPointerType())
4853         CCEDiag(E, diag::note_constexpr_invalid_cast)
4854           << 3 << SubExpr->getType();
4855       else
4856         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4857     }
4858     return true;
4859 
4860   case CK_DerivedToBase:
4861   case CK_UncheckedDerivedToBase:
4862     if (!EvaluatePointer(E->getSubExpr(), Result, Info))
4863       return false;
4864     if (!Result.Base && Result.Offset.isZero())
4865       return true;
4866 
4867     // Now figure out the necessary offset to add to the base LV to get from
4868     // the derived class to the base class.
4869     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4870                                   castAs<PointerType>()->getPointeeType(),
4871                                 Result);
4872 
4873   case CK_BaseToDerived:
4874     if (!Visit(E->getSubExpr()))
4875       return false;
4876     if (!Result.Base && Result.Offset.isZero())
4877       return true;
4878     return HandleBaseToDerivedCast(Info, E, Result);
4879 
4880   case CK_NullToPointer:
4881     VisitIgnoredValue(E->getSubExpr());
4882     return ZeroInitialization(E);
4883 
4884   case CK_IntegralToPointer: {
4885     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4886 
4887     APValue Value;
4888     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
4889       break;
4890 
4891     if (Value.isInt()) {
4892       unsigned Size = Info.Ctx.getTypeSize(E->getType());
4893       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
4894       Result.Base = (Expr*)nullptr;
4895       Result.Offset = CharUnits::fromQuantity(N);
4896       Result.CallIndex = 0;
4897       Result.Designator.setInvalid();
4898       return true;
4899     } else {
4900       // Cast is of an lvalue, no need to change value.
4901       Result.setFrom(Info.Ctx, Value);
4902       return true;
4903     }
4904   }
4905   case CK_ArrayToPointerDecay:
4906     if (SubExpr->isGLValue()) {
4907       if (!EvaluateLValue(SubExpr, Result, Info))
4908         return false;
4909     } else {
4910       Result.set(SubExpr, Info.CurrentCall->Index);
4911       if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
4912                            Info, Result, SubExpr))
4913         return false;
4914     }
4915     // The result is a pointer to the first element of the array.
4916     if (const ConstantArrayType *CAT
4917           = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4918       Result.addArray(Info, E, CAT);
4919     else
4920       Result.Designator.setInvalid();
4921     return true;
4922 
4923   case CK_FunctionToPointerDecay:
4924     return EvaluateLValue(SubExpr, Result, Info);
4925   }
4926 
4927   return ExprEvaluatorBaseTy::VisitCastExpr(E);
4928 }
4929 
GetAlignOfType(EvalInfo & Info,QualType T)4930 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
4931   // C++ [expr.alignof]p3:
4932   //     When alignof is applied to a reference type, the result is the
4933   //     alignment of the referenced type.
4934   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4935     T = Ref->getPointeeType();
4936 
4937   // __alignof is defined to return the preferred alignment.
4938   return Info.Ctx.toCharUnitsFromBits(
4939     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4940 }
4941 
GetAlignOfExpr(EvalInfo & Info,const Expr * E)4942 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
4943   E = E->IgnoreParens();
4944 
4945   // The kinds of expressions that we have special-case logic here for
4946   // should be kept up to date with the special checks for those
4947   // expressions in Sema.
4948 
4949   // alignof decl is always accepted, even if it doesn't make sense: we default
4950   // to 1 in those cases.
4951   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4952     return Info.Ctx.getDeclAlign(DRE->getDecl(),
4953                                  /*RefAsPointee*/true);
4954 
4955   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4956     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4957                                  /*RefAsPointee*/true);
4958 
4959   return GetAlignOfType(Info, E->getType());
4960 }
4961 
VisitCallExpr(const CallExpr * E)4962 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
4963   if (IsStringLiteralCall(E))
4964     return Success(E);
4965 
4966   switch (E->getBuiltinCallee()) {
4967   case Builtin::BI__builtin_addressof:
4968     return EvaluateLValue(E->getArg(0), Result, Info);
4969   case Builtin::BI__builtin_assume_aligned: {
4970     // We need to be very careful here because: if the pointer does not have the
4971     // asserted alignment, then the behavior is undefined, and undefined
4972     // behavior is non-constant.
4973     if (!EvaluatePointer(E->getArg(0), Result, Info))
4974       return false;
4975 
4976     LValue OffsetResult(Result);
4977     APSInt Alignment;
4978     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
4979       return false;
4980     CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
4981 
4982     if (E->getNumArgs() > 2) {
4983       APSInt Offset;
4984       if (!EvaluateInteger(E->getArg(2), Offset, Info))
4985         return false;
4986 
4987       int64_t AdditionalOffset = -getExtValue(Offset);
4988       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
4989     }
4990 
4991     // If there is a base object, then it must have the correct alignment.
4992     if (OffsetResult.Base) {
4993       CharUnits BaseAlignment;
4994       if (const ValueDecl *VD =
4995           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
4996         BaseAlignment = Info.Ctx.getDeclAlign(VD);
4997       } else {
4998         BaseAlignment =
4999           GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5000       }
5001 
5002       if (BaseAlignment < Align) {
5003         Result.Designator.setInvalid();
5004 	// FIXME: Quantities here cast to integers because the plural modifier
5005 	// does not work on APSInts yet.
5006         CCEDiag(E->getArg(0),
5007                 diag::note_constexpr_baa_insufficient_alignment) << 0
5008           << (int) BaseAlignment.getQuantity()
5009           << (unsigned) getExtValue(Alignment);
5010         return false;
5011       }
5012     }
5013 
5014     // The offset must also have the correct alignment.
5015     if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5016       Result.Designator.setInvalid();
5017       APSInt Offset(64, false);
5018       Offset = OffsetResult.Offset.getQuantity();
5019 
5020       if (OffsetResult.Base)
5021         CCEDiag(E->getArg(0),
5022                 diag::note_constexpr_baa_insufficient_alignment) << 1
5023           << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5024       else
5025         CCEDiag(E->getArg(0),
5026                 diag::note_constexpr_baa_value_insufficient_alignment)
5027           << Offset << (unsigned) getExtValue(Alignment);
5028 
5029       return false;
5030     }
5031 
5032     return true;
5033   }
5034   default:
5035     return ExprEvaluatorBaseTy::VisitCallExpr(E);
5036   }
5037 }
5038 
5039 //===----------------------------------------------------------------------===//
5040 // Member Pointer Evaluation
5041 //===----------------------------------------------------------------------===//
5042 
5043 namespace {
5044 class MemberPointerExprEvaluator
5045   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5046   MemberPtr &Result;
5047 
Success(const ValueDecl * D)5048   bool Success(const ValueDecl *D) {
5049     Result = MemberPtr(D);
5050     return true;
5051   }
5052 public:
5053 
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)5054   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5055     : ExprEvaluatorBaseTy(Info), Result(Result) {}
5056 
Success(const APValue & V,const Expr * E)5057   bool Success(const APValue &V, const Expr *E) {
5058     Result.setFrom(V);
5059     return true;
5060   }
ZeroInitialization(const Expr * E)5061   bool ZeroInitialization(const Expr *E) {
5062     return Success((const ValueDecl*)nullptr);
5063   }
5064 
5065   bool VisitCastExpr(const CastExpr *E);
5066   bool VisitUnaryAddrOf(const UnaryOperator *E);
5067 };
5068 } // end anonymous namespace
5069 
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)5070 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5071                                   EvalInfo &Info) {
5072   assert(E->isRValue() && E->getType()->isMemberPointerType());
5073   return MemberPointerExprEvaluator(Info, Result).Visit(E);
5074 }
5075 
VisitCastExpr(const CastExpr * E)5076 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5077   switch (E->getCastKind()) {
5078   default:
5079     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5080 
5081   case CK_NullToMemberPointer:
5082     VisitIgnoredValue(E->getSubExpr());
5083     return ZeroInitialization(E);
5084 
5085   case CK_BaseToDerivedMemberPointer: {
5086     if (!Visit(E->getSubExpr()))
5087       return false;
5088     if (E->path_empty())
5089       return true;
5090     // Base-to-derived member pointer casts store the path in derived-to-base
5091     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5092     // the wrong end of the derived->base arc, so stagger the path by one class.
5093     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5094     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5095          PathI != PathE; ++PathI) {
5096       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5097       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5098       if (!Result.castToDerived(Derived))
5099         return Error(E);
5100     }
5101     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5102     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5103       return Error(E);
5104     return true;
5105   }
5106 
5107   case CK_DerivedToBaseMemberPointer:
5108     if (!Visit(E->getSubExpr()))
5109       return false;
5110     for (CastExpr::path_const_iterator PathI = E->path_begin(),
5111          PathE = E->path_end(); PathI != PathE; ++PathI) {
5112       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5113       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5114       if (!Result.castToBase(Base))
5115         return Error(E);
5116     }
5117     return true;
5118   }
5119 }
5120 
VisitUnaryAddrOf(const UnaryOperator * E)5121 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5122   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5123   // member can be formed.
5124   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5125 }
5126 
5127 //===----------------------------------------------------------------------===//
5128 // Record Evaluation
5129 //===----------------------------------------------------------------------===//
5130 
5131 namespace {
5132   class RecordExprEvaluator
5133   : public ExprEvaluatorBase<RecordExprEvaluator> {
5134     const LValue &This;
5135     APValue &Result;
5136   public:
5137 
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)5138     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5139       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5140 
Success(const APValue & V,const Expr * E)5141     bool Success(const APValue &V, const Expr *E) {
5142       Result = V;
5143       return true;
5144     }
5145     bool ZeroInitialization(const Expr *E);
5146 
5147     bool VisitCastExpr(const CastExpr *E);
5148     bool VisitInitListExpr(const InitListExpr *E);
5149     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5150     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5151   };
5152 }
5153 
5154 /// Perform zero-initialization on an object of non-union class type.
5155 /// C++11 [dcl.init]p5:
5156 ///  To zero-initialize an object or reference of type T means:
5157 ///    [...]
5158 ///    -- if T is a (possibly cv-qualified) non-union class type,
5159 ///       each non-static data member and each base-class subobject is
5160 ///       zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)5161 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5162                                           const RecordDecl *RD,
5163                                           const LValue &This, APValue &Result) {
5164   assert(!RD->isUnion() && "Expected non-union class type");
5165   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5166   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5167                    std::distance(RD->field_begin(), RD->field_end()));
5168 
5169   if (RD->isInvalidDecl()) return false;
5170   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5171 
5172   if (CD) {
5173     unsigned Index = 0;
5174     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5175            End = CD->bases_end(); I != End; ++I, ++Index) {
5176       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5177       LValue Subobject = This;
5178       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5179         return false;
5180       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5181                                          Result.getStructBase(Index)))
5182         return false;
5183     }
5184   }
5185 
5186   for (const auto *I : RD->fields()) {
5187     // -- if T is a reference type, no initialization is performed.
5188     if (I->getType()->isReferenceType())
5189       continue;
5190 
5191     LValue Subobject = This;
5192     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5193       return false;
5194 
5195     ImplicitValueInitExpr VIE(I->getType());
5196     if (!EvaluateInPlace(
5197           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5198       return false;
5199   }
5200 
5201   return true;
5202 }
5203 
ZeroInitialization(const Expr * E)5204 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5205   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5206   if (RD->isInvalidDecl()) return false;
5207   if (RD->isUnion()) {
5208     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5209     // object's first non-static named data member is zero-initialized
5210     RecordDecl::field_iterator I = RD->field_begin();
5211     if (I == RD->field_end()) {
5212       Result = APValue((const FieldDecl*)nullptr);
5213       return true;
5214     }
5215 
5216     LValue Subobject = This;
5217     if (!HandleLValueMember(Info, E, Subobject, *I))
5218       return false;
5219     Result = APValue(*I);
5220     ImplicitValueInitExpr VIE(I->getType());
5221     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5222   }
5223 
5224   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5225     Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
5226     return false;
5227   }
5228 
5229   return HandleClassZeroInitialization(Info, E, RD, This, Result);
5230 }
5231 
VisitCastExpr(const CastExpr * E)5232 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5233   switch (E->getCastKind()) {
5234   default:
5235     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5236 
5237   case CK_ConstructorConversion:
5238     return Visit(E->getSubExpr());
5239 
5240   case CK_DerivedToBase:
5241   case CK_UncheckedDerivedToBase: {
5242     APValue DerivedObject;
5243     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5244       return false;
5245     if (!DerivedObject.isStruct())
5246       return Error(E->getSubExpr());
5247 
5248     // Derived-to-base rvalue conversion: just slice off the derived part.
5249     APValue *Value = &DerivedObject;
5250     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5251     for (CastExpr::path_const_iterator PathI = E->path_begin(),
5252          PathE = E->path_end(); PathI != PathE; ++PathI) {
5253       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5254       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5255       Value = &Value->getStructBase(getBaseIndex(RD, Base));
5256       RD = Base;
5257     }
5258     Result = *Value;
5259     return true;
5260   }
5261   }
5262 }
5263 
VisitInitListExpr(const InitListExpr * E)5264 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5265   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5266   if (RD->isInvalidDecl()) return false;
5267   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5268 
5269   if (RD->isUnion()) {
5270     const FieldDecl *Field = E->getInitializedFieldInUnion();
5271     Result = APValue(Field);
5272     if (!Field)
5273       return true;
5274 
5275     // If the initializer list for a union does not contain any elements, the
5276     // first element of the union is value-initialized.
5277     // FIXME: The element should be initialized from an initializer list.
5278     //        Is this difference ever observable for initializer lists which
5279     //        we don't build?
5280     ImplicitValueInitExpr VIE(Field->getType());
5281     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5282 
5283     LValue Subobject = This;
5284     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5285       return false;
5286 
5287     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5288     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5289                                   isa<CXXDefaultInitExpr>(InitExpr));
5290 
5291     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5292   }
5293 
5294   assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5295          "initializer list for class with base classes");
5296   Result = APValue(APValue::UninitStruct(), 0,
5297                    std::distance(RD->field_begin(), RD->field_end()));
5298   unsigned ElementNo = 0;
5299   bool Success = true;
5300   for (const auto *Field : RD->fields()) {
5301     // Anonymous bit-fields are not considered members of the class for
5302     // purposes of aggregate initialization.
5303     if (Field->isUnnamedBitfield())
5304       continue;
5305 
5306     LValue Subobject = This;
5307 
5308     bool HaveInit = ElementNo < E->getNumInits();
5309 
5310     // FIXME: Diagnostics here should point to the end of the initializer
5311     // list, not the start.
5312     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5313                             Subobject, Field, &Layout))
5314       return false;
5315 
5316     // Perform an implicit value-initialization for members beyond the end of
5317     // the initializer list.
5318     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5319     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5320 
5321     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5322     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5323                                   isa<CXXDefaultInitExpr>(Init));
5324 
5325     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5326     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5327         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5328                                                        FieldVal, Field))) {
5329       if (!Info.keepEvaluatingAfterFailure())
5330         return false;
5331       Success = false;
5332     }
5333   }
5334 
5335   return Success;
5336 }
5337 
VisitCXXConstructExpr(const CXXConstructExpr * E)5338 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5339   const CXXConstructorDecl *FD = E->getConstructor();
5340   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5341 
5342   bool ZeroInit = E->requiresZeroInitialization();
5343   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5344     // If we've already performed zero-initialization, we're already done.
5345     if (!Result.isUninit())
5346       return true;
5347 
5348     // We can get here in two different ways:
5349     //  1) We're performing value-initialization, and should zero-initialize
5350     //     the object, or
5351     //  2) We're performing default-initialization of an object with a trivial
5352     //     constexpr default constructor, in which case we should start the
5353     //     lifetimes of all the base subobjects (there can be no data member
5354     //     subobjects in this case) per [basic.life]p1.
5355     // Either way, ZeroInitialization is appropriate.
5356     return ZeroInitialization(E);
5357   }
5358 
5359   const FunctionDecl *Definition = nullptr;
5360   FD->getBody(Definition);
5361 
5362   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5363     return false;
5364 
5365   // Avoid materializing a temporary for an elidable copy/move constructor.
5366   if (E->isElidable() && !ZeroInit)
5367     if (const MaterializeTemporaryExpr *ME
5368           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5369       return Visit(ME->GetTemporaryExpr());
5370 
5371   if (ZeroInit && !ZeroInitialization(E))
5372     return false;
5373 
5374   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5375   return HandleConstructorCall(E->getExprLoc(), This, Args,
5376                                cast<CXXConstructorDecl>(Definition), Info,
5377                                Result);
5378 }
5379 
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)5380 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5381     const CXXStdInitializerListExpr *E) {
5382   const ConstantArrayType *ArrayType =
5383       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5384 
5385   LValue Array;
5386   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5387     return false;
5388 
5389   // Get a pointer to the first element of the array.
5390   Array.addArray(Info, E, ArrayType);
5391 
5392   // FIXME: Perform the checks on the field types in SemaInit.
5393   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5394   RecordDecl::field_iterator Field = Record->field_begin();
5395   if (Field == Record->field_end())
5396     return Error(E);
5397 
5398   // Start pointer.
5399   if (!Field->getType()->isPointerType() ||
5400       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5401                             ArrayType->getElementType()))
5402     return Error(E);
5403 
5404   // FIXME: What if the initializer_list type has base classes, etc?
5405   Result = APValue(APValue::UninitStruct(), 0, 2);
5406   Array.moveInto(Result.getStructField(0));
5407 
5408   if (++Field == Record->field_end())
5409     return Error(E);
5410 
5411   if (Field->getType()->isPointerType() &&
5412       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5413                            ArrayType->getElementType())) {
5414     // End pointer.
5415     if (!HandleLValueArrayAdjustment(Info, E, Array,
5416                                      ArrayType->getElementType(),
5417                                      ArrayType->getSize().getZExtValue()))
5418       return false;
5419     Array.moveInto(Result.getStructField(1));
5420   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5421     // Length.
5422     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5423   else
5424     return Error(E);
5425 
5426   if (++Field != Record->field_end())
5427     return Error(E);
5428 
5429   return true;
5430 }
5431 
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)5432 static bool EvaluateRecord(const Expr *E, const LValue &This,
5433                            APValue &Result, EvalInfo &Info) {
5434   assert(E->isRValue() && E->getType()->isRecordType() &&
5435          "can't evaluate expression as a record rvalue");
5436   return RecordExprEvaluator(Info, This, Result).Visit(E);
5437 }
5438 
5439 //===----------------------------------------------------------------------===//
5440 // Temporary Evaluation
5441 //
5442 // Temporaries are represented in the AST as rvalues, but generally behave like
5443 // lvalues. The full-object of which the temporary is a subobject is implicitly
5444 // materialized so that a reference can bind to it.
5445 //===----------------------------------------------------------------------===//
5446 namespace {
5447 class TemporaryExprEvaluator
5448   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5449 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)5450   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5451     LValueExprEvaluatorBaseTy(Info, Result) {}
5452 
5453   /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)5454   bool VisitConstructExpr(const Expr *E) {
5455     Result.set(E, Info.CurrentCall->Index);
5456     return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5457                            Info, Result, E);
5458   }
5459 
VisitCastExpr(const CastExpr * E)5460   bool VisitCastExpr(const CastExpr *E) {
5461     switch (E->getCastKind()) {
5462     default:
5463       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5464 
5465     case CK_ConstructorConversion:
5466       return VisitConstructExpr(E->getSubExpr());
5467     }
5468   }
VisitInitListExpr(const InitListExpr * E)5469   bool VisitInitListExpr(const InitListExpr *E) {
5470     return VisitConstructExpr(E);
5471   }
VisitCXXConstructExpr(const CXXConstructExpr * E)5472   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5473     return VisitConstructExpr(E);
5474   }
VisitCallExpr(const CallExpr * E)5475   bool VisitCallExpr(const CallExpr *E) {
5476     return VisitConstructExpr(E);
5477   }
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)5478   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5479     return VisitConstructExpr(E);
5480   }
5481 };
5482 } // end anonymous namespace
5483 
5484 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)5485 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5486   assert(E->isRValue() && E->getType()->isRecordType());
5487   return TemporaryExprEvaluator(Info, Result).Visit(E);
5488 }
5489 
5490 //===----------------------------------------------------------------------===//
5491 // Vector Evaluation
5492 //===----------------------------------------------------------------------===//
5493 
5494 namespace {
5495   class VectorExprEvaluator
5496   : public ExprEvaluatorBase<VectorExprEvaluator> {
5497     APValue &Result;
5498   public:
5499 
VectorExprEvaluator(EvalInfo & info,APValue & Result)5500     VectorExprEvaluator(EvalInfo &info, APValue &Result)
5501       : ExprEvaluatorBaseTy(info), Result(Result) {}
5502 
Success(const ArrayRef<APValue> & V,const Expr * E)5503     bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5504       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5505       // FIXME: remove this APValue copy.
5506       Result = APValue(V.data(), V.size());
5507       return true;
5508     }
Success(const APValue & V,const Expr * E)5509     bool Success(const APValue &V, const Expr *E) {
5510       assert(V.isVector());
5511       Result = V;
5512       return true;
5513     }
5514     bool ZeroInitialization(const Expr *E);
5515 
VisitUnaryReal(const UnaryOperator * E)5516     bool VisitUnaryReal(const UnaryOperator *E)
5517       { return Visit(E->getSubExpr()); }
5518     bool VisitCastExpr(const CastExpr* E);
5519     bool VisitInitListExpr(const InitListExpr *E);
5520     bool VisitUnaryImag(const UnaryOperator *E);
5521     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5522     //                 binary comparisons, binary and/or/xor,
5523     //                 shufflevector, ExtVectorElementExpr
5524   };
5525 } // end anonymous namespace
5526 
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)5527 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5528   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5529   return VectorExprEvaluator(Info, Result).Visit(E);
5530 }
5531 
VisitCastExpr(const CastExpr * E)5532 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5533   const VectorType *VTy = E->getType()->castAs<VectorType>();
5534   unsigned NElts = VTy->getNumElements();
5535 
5536   const Expr *SE = E->getSubExpr();
5537   QualType SETy = SE->getType();
5538 
5539   switch (E->getCastKind()) {
5540   case CK_VectorSplat: {
5541     APValue Val = APValue();
5542     if (SETy->isIntegerType()) {
5543       APSInt IntResult;
5544       if (!EvaluateInteger(SE, IntResult, Info))
5545          return false;
5546       Val = APValue(IntResult);
5547     } else if (SETy->isRealFloatingType()) {
5548        APFloat F(0.0);
5549        if (!EvaluateFloat(SE, F, Info))
5550          return false;
5551        Val = APValue(F);
5552     } else {
5553       return Error(E);
5554     }
5555 
5556     // Splat and create vector APValue.
5557     SmallVector<APValue, 4> Elts(NElts, Val);
5558     return Success(Elts, E);
5559   }
5560   case CK_BitCast: {
5561     // Evaluate the operand into an APInt we can extract from.
5562     llvm::APInt SValInt;
5563     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5564       return false;
5565     // Extract the elements
5566     QualType EltTy = VTy->getElementType();
5567     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5568     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5569     SmallVector<APValue, 4> Elts;
5570     if (EltTy->isRealFloatingType()) {
5571       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5572       unsigned FloatEltSize = EltSize;
5573       if (&Sem == &APFloat::x87DoubleExtended)
5574         FloatEltSize = 80;
5575       for (unsigned i = 0; i < NElts; i++) {
5576         llvm::APInt Elt;
5577         if (BigEndian)
5578           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5579         else
5580           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5581         Elts.push_back(APValue(APFloat(Sem, Elt)));
5582       }
5583     } else if (EltTy->isIntegerType()) {
5584       for (unsigned i = 0; i < NElts; i++) {
5585         llvm::APInt Elt;
5586         if (BigEndian)
5587           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5588         else
5589           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5590         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5591       }
5592     } else {
5593       return Error(E);
5594     }
5595     return Success(Elts, E);
5596   }
5597   default:
5598     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5599   }
5600 }
5601 
5602 bool
VisitInitListExpr(const InitListExpr * E)5603 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5604   const VectorType *VT = E->getType()->castAs<VectorType>();
5605   unsigned NumInits = E->getNumInits();
5606   unsigned NumElements = VT->getNumElements();
5607 
5608   QualType EltTy = VT->getElementType();
5609   SmallVector<APValue, 4> Elements;
5610 
5611   // The number of initializers can be less than the number of
5612   // vector elements. For OpenCL, this can be due to nested vector
5613   // initialization. For GCC compatibility, missing trailing elements
5614   // should be initialized with zeroes.
5615   unsigned CountInits = 0, CountElts = 0;
5616   while (CountElts < NumElements) {
5617     // Handle nested vector initialization.
5618     if (CountInits < NumInits
5619         && E->getInit(CountInits)->getType()->isVectorType()) {
5620       APValue v;
5621       if (!EvaluateVector(E->getInit(CountInits), v, Info))
5622         return Error(E);
5623       unsigned vlen = v.getVectorLength();
5624       for (unsigned j = 0; j < vlen; j++)
5625         Elements.push_back(v.getVectorElt(j));
5626       CountElts += vlen;
5627     } else if (EltTy->isIntegerType()) {
5628       llvm::APSInt sInt(32);
5629       if (CountInits < NumInits) {
5630         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5631           return false;
5632       } else // trailing integer zero.
5633         sInt = Info.Ctx.MakeIntValue(0, EltTy);
5634       Elements.push_back(APValue(sInt));
5635       CountElts++;
5636     } else {
5637       llvm::APFloat f(0.0);
5638       if (CountInits < NumInits) {
5639         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5640           return false;
5641       } else // trailing float zero.
5642         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5643       Elements.push_back(APValue(f));
5644       CountElts++;
5645     }
5646     CountInits++;
5647   }
5648   return Success(Elements, E);
5649 }
5650 
5651 bool
ZeroInitialization(const Expr * E)5652 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5653   const VectorType *VT = E->getType()->getAs<VectorType>();
5654   QualType EltTy = VT->getElementType();
5655   APValue ZeroElement;
5656   if (EltTy->isIntegerType())
5657     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5658   else
5659     ZeroElement =
5660         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5661 
5662   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5663   return Success(Elements, E);
5664 }
5665 
VisitUnaryImag(const UnaryOperator * E)5666 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5667   VisitIgnoredValue(E->getSubExpr());
5668   return ZeroInitialization(E);
5669 }
5670 
5671 //===----------------------------------------------------------------------===//
5672 // Array Evaluation
5673 //===----------------------------------------------------------------------===//
5674 
5675 namespace {
5676   class ArrayExprEvaluator
5677   : public ExprEvaluatorBase<ArrayExprEvaluator> {
5678     const LValue &This;
5679     APValue &Result;
5680   public:
5681 
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)5682     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5683       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
5684 
Success(const APValue & V,const Expr * E)5685     bool Success(const APValue &V, const Expr *E) {
5686       assert((V.isArray() || V.isLValue()) &&
5687              "expected array or string literal");
5688       Result = V;
5689       return true;
5690     }
5691 
ZeroInitialization(const Expr * E)5692     bool ZeroInitialization(const Expr *E) {
5693       const ConstantArrayType *CAT =
5694           Info.Ctx.getAsConstantArrayType(E->getType());
5695       if (!CAT)
5696         return Error(E);
5697 
5698       Result = APValue(APValue::UninitArray(), 0,
5699                        CAT->getSize().getZExtValue());
5700       if (!Result.hasArrayFiller()) return true;
5701 
5702       // Zero-initialize all elements.
5703       LValue Subobject = This;
5704       Subobject.addArray(Info, E, CAT);
5705       ImplicitValueInitExpr VIE(CAT->getElementType());
5706       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
5707     }
5708 
5709     bool VisitInitListExpr(const InitListExpr *E);
5710     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5711     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5712                                const LValue &Subobject,
5713                                APValue *Value, QualType Type);
5714   };
5715 } // end anonymous namespace
5716 
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)5717 static bool EvaluateArray(const Expr *E, const LValue &This,
5718                           APValue &Result, EvalInfo &Info) {
5719   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
5720   return ArrayExprEvaluator(Info, This, Result).Visit(E);
5721 }
5722 
VisitInitListExpr(const InitListExpr * E)5723 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5724   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5725   if (!CAT)
5726     return Error(E);
5727 
5728   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5729   // an appropriately-typed string literal enclosed in braces.
5730   if (E->isStringLiteralInit()) {
5731     LValue LV;
5732     if (!EvaluateLValue(E->getInit(0), LV, Info))
5733       return false;
5734     APValue Val;
5735     LV.moveInto(Val);
5736     return Success(Val, E);
5737   }
5738 
5739   bool Success = true;
5740 
5741   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5742          "zero-initialized array shouldn't have any initialized elts");
5743   APValue Filler;
5744   if (Result.isArray() && Result.hasArrayFiller())
5745     Filler = Result.getArrayFiller();
5746 
5747   unsigned NumEltsToInit = E->getNumInits();
5748   unsigned NumElts = CAT->getSize().getZExtValue();
5749   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
5750 
5751   // If the initializer might depend on the array index, run it for each
5752   // array element. For now, just whitelist non-class value-initialization.
5753   if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5754     NumEltsToInit = NumElts;
5755 
5756   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
5757 
5758   // If the array was previously zero-initialized, preserve the
5759   // zero-initialized values.
5760   if (!Filler.isUninit()) {
5761     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5762       Result.getArrayInitializedElt(I) = Filler;
5763     if (Result.hasArrayFiller())
5764       Result.getArrayFiller() = Filler;
5765   }
5766 
5767   LValue Subobject = This;
5768   Subobject.addArray(Info, E, CAT);
5769   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5770     const Expr *Init =
5771         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
5772     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
5773                          Info, Subobject, Init) ||
5774         !HandleLValueArrayAdjustment(Info, Init, Subobject,
5775                                      CAT->getElementType(), 1)) {
5776       if (!Info.keepEvaluatingAfterFailure())
5777         return false;
5778       Success = false;
5779     }
5780   }
5781 
5782   if (!Result.hasArrayFiller())
5783     return Success;
5784 
5785   // If we get here, we have a trivial filler, which we can just evaluate
5786   // once and splat over the rest of the array elements.
5787   assert(FillerExpr && "no array filler for incomplete init list");
5788   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5789                          FillerExpr) && Success;
5790 }
5791 
VisitCXXConstructExpr(const CXXConstructExpr * E)5792 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5793   return VisitCXXConstructExpr(E, This, &Result, E->getType());
5794 }
5795 
VisitCXXConstructExpr(const CXXConstructExpr * E,const LValue & Subobject,APValue * Value,QualType Type)5796 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5797                                                const LValue &Subobject,
5798                                                APValue *Value,
5799                                                QualType Type) {
5800   bool HadZeroInit = !Value->isUninit();
5801 
5802   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5803     unsigned N = CAT->getSize().getZExtValue();
5804 
5805     // Preserve the array filler if we had prior zero-initialization.
5806     APValue Filler =
5807       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5808                                              : APValue();
5809 
5810     *Value = APValue(APValue::UninitArray(), N, N);
5811 
5812     if (HadZeroInit)
5813       for (unsigned I = 0; I != N; ++I)
5814         Value->getArrayInitializedElt(I) = Filler;
5815 
5816     // Initialize the elements.
5817     LValue ArrayElt = Subobject;
5818     ArrayElt.addArray(Info, E, CAT);
5819     for (unsigned I = 0; I != N; ++I)
5820       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5821                                  CAT->getElementType()) ||
5822           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5823                                        CAT->getElementType(), 1))
5824         return false;
5825 
5826     return true;
5827   }
5828 
5829   if (!Type->isRecordType())
5830     return Error(E);
5831 
5832   const CXXConstructorDecl *FD = E->getConstructor();
5833 
5834   bool ZeroInit = E->requiresZeroInitialization();
5835   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5836     if (HadZeroInit)
5837       return true;
5838 
5839     // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5840     ImplicitValueInitExpr VIE(Type);
5841     return EvaluateInPlace(*Value, Info, Subobject, &VIE);
5842   }
5843 
5844   const FunctionDecl *Definition = nullptr;
5845   FD->getBody(Definition);
5846 
5847   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5848     return false;
5849 
5850   if (ZeroInit && !HadZeroInit) {
5851     ImplicitValueInitExpr VIE(Type);
5852     if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
5853       return false;
5854   }
5855 
5856   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5857   return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
5858                                cast<CXXConstructorDecl>(Definition),
5859                                Info, *Value);
5860 }
5861 
5862 //===----------------------------------------------------------------------===//
5863 // Integer Evaluation
5864 //
5865 // As a GNU extension, we support casting pointers to sufficiently-wide integer
5866 // types and back in constant folding. Integer values are thus represented
5867 // either as an integer-valued APValue, or as an lvalue-valued APValue.
5868 //===----------------------------------------------------------------------===//
5869 
5870 namespace {
5871 class IntExprEvaluator
5872   : public ExprEvaluatorBase<IntExprEvaluator> {
5873   APValue &Result;
5874 public:
IntExprEvaluator(EvalInfo & info,APValue & result)5875   IntExprEvaluator(EvalInfo &info, APValue &result)
5876     : ExprEvaluatorBaseTy(info), Result(result) {}
5877 
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)5878   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
5879     assert(E->getType()->isIntegralOrEnumerationType() &&
5880            "Invalid evaluation result.");
5881     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
5882            "Invalid evaluation result.");
5883     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5884            "Invalid evaluation result.");
5885     Result = APValue(SI);
5886     return true;
5887   }
Success(const llvm::APSInt & SI,const Expr * E)5888   bool Success(const llvm::APSInt &SI, const Expr *E) {
5889     return Success(SI, E, Result);
5890   }
5891 
Success(const llvm::APInt & I,const Expr * E,APValue & Result)5892   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
5893     assert(E->getType()->isIntegralOrEnumerationType() &&
5894            "Invalid evaluation result.");
5895     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5896            "Invalid evaluation result.");
5897     Result = APValue(APSInt(I));
5898     Result.getInt().setIsUnsigned(
5899                             E->getType()->isUnsignedIntegerOrEnumerationType());
5900     return true;
5901   }
Success(const llvm::APInt & I,const Expr * E)5902   bool Success(const llvm::APInt &I, const Expr *E) {
5903     return Success(I, E, Result);
5904   }
5905 
Success(uint64_t Value,const Expr * E,APValue & Result)5906   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5907     assert(E->getType()->isIntegralOrEnumerationType() &&
5908            "Invalid evaluation result.");
5909     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
5910     return true;
5911   }
Success(uint64_t Value,const Expr * E)5912   bool Success(uint64_t Value, const Expr *E) {
5913     return Success(Value, E, Result);
5914   }
5915 
Success(CharUnits Size,const Expr * E)5916   bool Success(CharUnits Size, const Expr *E) {
5917     return Success(Size.getQuantity(), E);
5918   }
5919 
Success(const APValue & V,const Expr * E)5920   bool Success(const APValue &V, const Expr *E) {
5921     if (V.isLValue() || V.isAddrLabelDiff()) {
5922       Result = V;
5923       return true;
5924     }
5925     return Success(V.getInt(), E);
5926   }
5927 
ZeroInitialization(const Expr * E)5928   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
5929 
5930   //===--------------------------------------------------------------------===//
5931   //                            Visitor Methods
5932   //===--------------------------------------------------------------------===//
5933 
VisitIntegerLiteral(const IntegerLiteral * E)5934   bool VisitIntegerLiteral(const IntegerLiteral *E) {
5935     return Success(E->getValue(), E);
5936   }
VisitCharacterLiteral(const CharacterLiteral * E)5937   bool VisitCharacterLiteral(const CharacterLiteral *E) {
5938     return Success(E->getValue(), E);
5939   }
5940 
5941   bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)5942   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5943     if (CheckReferencedDecl(E, E->getDecl()))
5944       return true;
5945 
5946     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
5947   }
VisitMemberExpr(const MemberExpr * E)5948   bool VisitMemberExpr(const MemberExpr *E) {
5949     if (CheckReferencedDecl(E, E->getMemberDecl())) {
5950       VisitIgnoredValue(E->getBase());
5951       return true;
5952     }
5953 
5954     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
5955   }
5956 
5957   bool VisitCallExpr(const CallExpr *E);
5958   bool VisitBinaryOperator(const BinaryOperator *E);
5959   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
5960   bool VisitUnaryOperator(const UnaryOperator *E);
5961 
5962   bool VisitCastExpr(const CastExpr* E);
5963   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
5964 
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)5965   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
5966     return Success(E->getValue(), E);
5967   }
5968 
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)5969   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5970     return Success(E->getValue(), E);
5971   }
5972 
5973   // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)5974   bool VisitGNUNullExpr(const GNUNullExpr *E) {
5975     return ZeroInitialization(E);
5976   }
5977 
VisitTypeTraitExpr(const TypeTraitExpr * E)5978   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5979     return Success(E->getValue(), E);
5980   }
5981 
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)5982   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5983     return Success(E->getValue(), E);
5984   }
5985 
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)5986   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5987     return Success(E->getValue(), E);
5988   }
5989 
5990   bool VisitUnaryReal(const UnaryOperator *E);
5991   bool VisitUnaryImag(const UnaryOperator *E);
5992 
5993   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
5994   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
5995 
5996 private:
5997   static QualType GetObjectType(APValue::LValueBase B);
5998   bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
5999   // FIXME: Missing: array subscript of vector, member of vector
6000 };
6001 } // end anonymous namespace
6002 
6003 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6004 /// produce either the integer value or a pointer.
6005 ///
6006 /// GCC has a heinous extension which folds casts between pointer types and
6007 /// pointer-sized integral types. We support this by allowing the evaluation of
6008 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6009 /// Some simple arithmetic on such values is supported (they are treated much
6010 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)6011 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6012                                     EvalInfo &Info) {
6013   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6014   return IntExprEvaluator(Info, Result).Visit(E);
6015 }
6016 
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)6017 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6018   APValue Val;
6019   if (!EvaluateIntegerOrLValue(E, Val, Info))
6020     return false;
6021   if (!Val.isInt()) {
6022     // FIXME: It would be better to produce the diagnostic for casting
6023     //        a pointer to an integer.
6024     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6025     return false;
6026   }
6027   Result = Val.getInt();
6028   return true;
6029 }
6030 
6031 /// Check whether the given declaration can be directly converted to an integral
6032 /// rvalue. If not, no diagnostic is produced; there are other things we can
6033 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)6034 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6035   // Enums are integer constant exprs.
6036   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6037     // Check for signedness/width mismatches between E type and ECD value.
6038     bool SameSign = (ECD->getInitVal().isSigned()
6039                      == E->getType()->isSignedIntegerOrEnumerationType());
6040     bool SameWidth = (ECD->getInitVal().getBitWidth()
6041                       == Info.Ctx.getIntWidth(E->getType()));
6042     if (SameSign && SameWidth)
6043       return Success(ECD->getInitVal(), E);
6044     else {
6045       // Get rid of mismatch (otherwise Success assertions will fail)
6046       // by computing a new value matching the type of E.
6047       llvm::APSInt Val = ECD->getInitVal();
6048       if (!SameSign)
6049         Val.setIsSigned(!ECD->getInitVal().isSigned());
6050       if (!SameWidth)
6051         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6052       return Success(Val, E);
6053     }
6054   }
6055   return false;
6056 }
6057 
6058 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6059 /// as GCC.
EvaluateBuiltinClassifyType(const CallExpr * E)6060 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6061   // The following enum mimics the values returned by GCC.
6062   // FIXME: Does GCC differ between lvalue and rvalue references here?
6063   enum gcc_type_class {
6064     no_type_class = -1,
6065     void_type_class, integer_type_class, char_type_class,
6066     enumeral_type_class, boolean_type_class,
6067     pointer_type_class, reference_type_class, offset_type_class,
6068     real_type_class, complex_type_class,
6069     function_type_class, method_type_class,
6070     record_type_class, union_type_class,
6071     array_type_class, string_type_class,
6072     lang_type_class
6073   };
6074 
6075   // If no argument was supplied, default to "no_type_class". This isn't
6076   // ideal, however it is what gcc does.
6077   if (E->getNumArgs() == 0)
6078     return no_type_class;
6079 
6080   QualType ArgTy = E->getArg(0)->getType();
6081   if (ArgTy->isVoidType())
6082     return void_type_class;
6083   else if (ArgTy->isEnumeralType())
6084     return enumeral_type_class;
6085   else if (ArgTy->isBooleanType())
6086     return boolean_type_class;
6087   else if (ArgTy->isCharType())
6088     return string_type_class; // gcc doesn't appear to use char_type_class
6089   else if (ArgTy->isIntegerType())
6090     return integer_type_class;
6091   else if (ArgTy->isPointerType())
6092     return pointer_type_class;
6093   else if (ArgTy->isReferenceType())
6094     return reference_type_class;
6095   else if (ArgTy->isRealType())
6096     return real_type_class;
6097   else if (ArgTy->isComplexType())
6098     return complex_type_class;
6099   else if (ArgTy->isFunctionType())
6100     return function_type_class;
6101   else if (ArgTy->isStructureOrClassType())
6102     return record_type_class;
6103   else if (ArgTy->isUnionType())
6104     return union_type_class;
6105   else if (ArgTy->isArrayType())
6106     return array_type_class;
6107   else if (ArgTy->isUnionType())
6108     return union_type_class;
6109   else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
6110     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6111 }
6112 
6113 /// EvaluateBuiltinConstantPForLValue - Determine the result of
6114 /// __builtin_constant_p when applied to the given lvalue.
6115 ///
6116 /// An lvalue is only "constant" if it is a pointer or reference to the first
6117 /// character of a string literal.
6118 template<typename LValue>
EvaluateBuiltinConstantPForLValue(const LValue & LV)6119 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
6120   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
6121   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6122 }
6123 
6124 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6125 /// GCC as we can manage.
EvaluateBuiltinConstantP(ASTContext & Ctx,const Expr * Arg)6126 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6127   QualType ArgType = Arg->getType();
6128 
6129   // __builtin_constant_p always has one operand. The rules which gcc follows
6130   // are not precisely documented, but are as follows:
6131   //
6132   //  - If the operand is of integral, floating, complex or enumeration type,
6133   //    and can be folded to a known value of that type, it returns 1.
6134   //  - If the operand and can be folded to a pointer to the first character
6135   //    of a string literal (or such a pointer cast to an integral type), it
6136   //    returns 1.
6137   //
6138   // Otherwise, it returns 0.
6139   //
6140   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6141   // its support for this does not currently work.
6142   if (ArgType->isIntegralOrEnumerationType()) {
6143     Expr::EvalResult Result;
6144     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6145       return false;
6146 
6147     APValue &V = Result.Val;
6148     if (V.getKind() == APValue::Int)
6149       return true;
6150 
6151     return EvaluateBuiltinConstantPForLValue(V);
6152   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6153     return Arg->isEvaluatable(Ctx);
6154   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6155     LValue LV;
6156     Expr::EvalStatus Status;
6157     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
6158     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6159                           : EvaluatePointer(Arg, LV, Info)) &&
6160         !Status.HasSideEffects)
6161       return EvaluateBuiltinConstantPForLValue(LV);
6162   }
6163 
6164   // Anything else isn't considered to be sufficiently constant.
6165   return false;
6166 }
6167 
6168 /// Retrieves the "underlying object type" of the given expression,
6169 /// as used by __builtin_object_size.
GetObjectType(APValue::LValueBase B)6170 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
6171   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6172     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
6173       return VD->getType();
6174   } else if (const Expr *E = B.get<const Expr*>()) {
6175     if (isa<CompoundLiteralExpr>(E))
6176       return E->getType();
6177   }
6178 
6179   return QualType();
6180 }
6181 
TryEvaluateBuiltinObjectSize(const CallExpr * E)6182 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
6183   LValue Base;
6184 
6185   {
6186     // The operand of __builtin_object_size is never evaluated for side-effects.
6187     // If there are any, but we can determine the pointed-to object anyway, then
6188     // ignore the side-effects.
6189     SpeculativeEvaluationRAII SpeculativeEval(Info);
6190     if (!EvaluatePointer(E->getArg(0), Base, Info))
6191       return false;
6192   }
6193 
6194   if (!Base.getLValueBase()) {
6195     // It is not possible to determine which objects ptr points to at compile time,
6196     // __builtin_object_size should return (size_t) -1 for type 0 or 1
6197     // and (size_t) 0 for type 2 or 3.
6198     llvm::APSInt TypeIntVaue;
6199     const Expr *ExprType = E->getArg(1);
6200     if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
6201       return false;
6202     if (TypeIntVaue == 0 || TypeIntVaue == 1)
6203       return Success(-1, E);
6204     if (TypeIntVaue == 2 || TypeIntVaue == 3)
6205       return Success(0, E);
6206     return Error(E);
6207   }
6208 
6209   QualType T = GetObjectType(Base.getLValueBase());
6210   if (T.isNull() ||
6211       T->isIncompleteType() ||
6212       T->isFunctionType() ||
6213       T->isVariablyModifiedType() ||
6214       T->isDependentType())
6215     return Error(E);
6216 
6217   CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
6218   CharUnits Offset = Base.getLValueOffset();
6219 
6220   if (!Offset.isNegative() && Offset <= Size)
6221     Size -= Offset;
6222   else
6223     Size = CharUnits::Zero();
6224   return Success(Size, E);
6225 }
6226 
VisitCallExpr(const CallExpr * E)6227 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
6228   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
6229   default:
6230     return ExprEvaluatorBaseTy::VisitCallExpr(E);
6231 
6232   case Builtin::BI__builtin_object_size: {
6233     if (TryEvaluateBuiltinObjectSize(E))
6234       return true;
6235 
6236     // If evaluating the argument has side-effects, we can't determine the size
6237     // of the object, and so we lower it to unknown now. CodeGen relies on us to
6238     // handle all cases where the expression has side-effects.
6239     if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
6240       if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
6241         return Success(-1ULL, E);
6242       return Success(0, E);
6243     }
6244 
6245     // Expression had no side effects, but we couldn't statically determine the
6246     // size of the referenced object.
6247     switch (Info.EvalMode) {
6248     case EvalInfo::EM_ConstantExpression:
6249     case EvalInfo::EM_PotentialConstantExpression:
6250     case EvalInfo::EM_ConstantFold:
6251     case EvalInfo::EM_EvaluateForOverflow:
6252     case EvalInfo::EM_IgnoreSideEffects:
6253       return Error(E);
6254     case EvalInfo::EM_ConstantExpressionUnevaluated:
6255     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6256       return Success(-1ULL, E);
6257     }
6258   }
6259 
6260   case Builtin::BI__builtin_bswap16:
6261   case Builtin::BI__builtin_bswap32:
6262   case Builtin::BI__builtin_bswap64: {
6263     APSInt Val;
6264     if (!EvaluateInteger(E->getArg(0), Val, Info))
6265       return false;
6266 
6267     return Success(Val.byteSwap(), E);
6268   }
6269 
6270   case Builtin::BI__builtin_classify_type:
6271     return Success(EvaluateBuiltinClassifyType(E), E);
6272 
6273   // FIXME: BI__builtin_clrsb
6274   // FIXME: BI__builtin_clrsbl
6275   // FIXME: BI__builtin_clrsbll
6276 
6277   case Builtin::BI__builtin_clz:
6278   case Builtin::BI__builtin_clzl:
6279   case Builtin::BI__builtin_clzll:
6280   case Builtin::BI__builtin_clzs: {
6281     APSInt Val;
6282     if (!EvaluateInteger(E->getArg(0), Val, Info))
6283       return false;
6284     if (!Val)
6285       return Error(E);
6286 
6287     return Success(Val.countLeadingZeros(), E);
6288   }
6289 
6290   case Builtin::BI__builtin_constant_p:
6291     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6292 
6293   case Builtin::BI__builtin_ctz:
6294   case Builtin::BI__builtin_ctzl:
6295   case Builtin::BI__builtin_ctzll:
6296   case Builtin::BI__builtin_ctzs: {
6297     APSInt Val;
6298     if (!EvaluateInteger(E->getArg(0), Val, Info))
6299       return false;
6300     if (!Val)
6301       return Error(E);
6302 
6303     return Success(Val.countTrailingZeros(), E);
6304   }
6305 
6306   case Builtin::BI__builtin_eh_return_data_regno: {
6307     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6308     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6309     return Success(Operand, E);
6310   }
6311 
6312   case Builtin::BI__builtin_expect:
6313     return Visit(E->getArg(0));
6314 
6315   case Builtin::BI__builtin_ffs:
6316   case Builtin::BI__builtin_ffsl:
6317   case Builtin::BI__builtin_ffsll: {
6318     APSInt Val;
6319     if (!EvaluateInteger(E->getArg(0), Val, Info))
6320       return false;
6321 
6322     unsigned N = Val.countTrailingZeros();
6323     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6324   }
6325 
6326   case Builtin::BI__builtin_fpclassify: {
6327     APFloat Val(0.0);
6328     if (!EvaluateFloat(E->getArg(5), Val, Info))
6329       return false;
6330     unsigned Arg;
6331     switch (Val.getCategory()) {
6332     case APFloat::fcNaN: Arg = 0; break;
6333     case APFloat::fcInfinity: Arg = 1; break;
6334     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6335     case APFloat::fcZero: Arg = 4; break;
6336     }
6337     return Visit(E->getArg(Arg));
6338   }
6339 
6340   case Builtin::BI__builtin_isinf_sign: {
6341     APFloat Val(0.0);
6342     return EvaluateFloat(E->getArg(0), Val, Info) &&
6343            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6344   }
6345 
6346   case Builtin::BI__builtin_isinf: {
6347     APFloat Val(0.0);
6348     return EvaluateFloat(E->getArg(0), Val, Info) &&
6349            Success(Val.isInfinity() ? 1 : 0, E);
6350   }
6351 
6352   case Builtin::BI__builtin_isfinite: {
6353     APFloat Val(0.0);
6354     return EvaluateFloat(E->getArg(0), Val, Info) &&
6355            Success(Val.isFinite() ? 1 : 0, E);
6356   }
6357 
6358   case Builtin::BI__builtin_isnan: {
6359     APFloat Val(0.0);
6360     return EvaluateFloat(E->getArg(0), Val, Info) &&
6361            Success(Val.isNaN() ? 1 : 0, E);
6362   }
6363 
6364   case Builtin::BI__builtin_isnormal: {
6365     APFloat Val(0.0);
6366     return EvaluateFloat(E->getArg(0), Val, Info) &&
6367            Success(Val.isNormal() ? 1 : 0, E);
6368   }
6369 
6370   case Builtin::BI__builtin_parity:
6371   case Builtin::BI__builtin_parityl:
6372   case Builtin::BI__builtin_parityll: {
6373     APSInt Val;
6374     if (!EvaluateInteger(E->getArg(0), Val, Info))
6375       return false;
6376 
6377     return Success(Val.countPopulation() % 2, E);
6378   }
6379 
6380   case Builtin::BI__builtin_popcount:
6381   case Builtin::BI__builtin_popcountl:
6382   case Builtin::BI__builtin_popcountll: {
6383     APSInt Val;
6384     if (!EvaluateInteger(E->getArg(0), Val, Info))
6385       return false;
6386 
6387     return Success(Val.countPopulation(), E);
6388   }
6389 
6390   case Builtin::BIstrlen:
6391     // A call to strlen is not a constant expression.
6392     if (Info.getLangOpts().CPlusPlus11)
6393       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6394         << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6395     else
6396       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6397     // Fall through.
6398   case Builtin::BI__builtin_strlen: {
6399     // As an extension, we support __builtin_strlen() as a constant expression,
6400     // and support folding strlen() to a constant.
6401     LValue String;
6402     if (!EvaluatePointer(E->getArg(0), String, Info))
6403       return false;
6404 
6405     // Fast path: if it's a string literal, search the string value.
6406     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6407             String.getLValueBase().dyn_cast<const Expr *>())) {
6408       // The string literal may have embedded null characters. Find the first
6409       // one and truncate there.
6410       StringRef Str = S->getBytes();
6411       int64_t Off = String.Offset.getQuantity();
6412       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6413           S->getCharByteWidth() == 1) {
6414         Str = Str.substr(Off);
6415 
6416         StringRef::size_type Pos = Str.find(0);
6417         if (Pos != StringRef::npos)
6418           Str = Str.substr(0, Pos);
6419 
6420         return Success(Str.size(), E);
6421       }
6422 
6423       // Fall through to slow path to issue appropriate diagnostic.
6424     }
6425 
6426     // Slow path: scan the bytes of the string looking for the terminating 0.
6427     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6428     for (uint64_t Strlen = 0; /**/; ++Strlen) {
6429       APValue Char;
6430       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6431           !Char.isInt())
6432         return false;
6433       if (!Char.getInt())
6434         return Success(Strlen, E);
6435       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6436         return false;
6437     }
6438   }
6439 
6440   case Builtin::BI__atomic_always_lock_free:
6441   case Builtin::BI__atomic_is_lock_free:
6442   case Builtin::BI__c11_atomic_is_lock_free: {
6443     APSInt SizeVal;
6444     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6445       return false;
6446 
6447     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6448     // of two less than the maximum inline atomic width, we know it is
6449     // lock-free.  If the size isn't a power of two, or greater than the
6450     // maximum alignment where we promote atomics, we know it is not lock-free
6451     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
6452     // the answer can only be determined at runtime; for example, 16-byte
6453     // atomics have lock-free implementations on some, but not all,
6454     // x86-64 processors.
6455 
6456     // Check power-of-two.
6457     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
6458     if (Size.isPowerOfTwo()) {
6459       // Check against inlining width.
6460       unsigned InlineWidthBits =
6461           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6462       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6463         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6464             Size == CharUnits::One() ||
6465             E->getArg(1)->isNullPointerConstant(Info.Ctx,
6466                                                 Expr::NPC_NeverValueDependent))
6467           // OK, we will inline appropriately-aligned operations of this size,
6468           // and _Atomic(T) is appropriately-aligned.
6469           return Success(1, E);
6470 
6471         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6472           castAs<PointerType>()->getPointeeType();
6473         if (!PointeeType->isIncompleteType() &&
6474             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6475           // OK, we will inline operations on this object.
6476           return Success(1, E);
6477         }
6478       }
6479     }
6480 
6481     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6482         Success(0, E) : Error(E);
6483   }
6484   }
6485 }
6486 
HasSameBase(const LValue & A,const LValue & B)6487 static bool HasSameBase(const LValue &A, const LValue &B) {
6488   if (!A.getLValueBase())
6489     return !B.getLValueBase();
6490   if (!B.getLValueBase())
6491     return false;
6492 
6493   if (A.getLValueBase().getOpaqueValue() !=
6494       B.getLValueBase().getOpaqueValue()) {
6495     const Decl *ADecl = GetLValueBaseDecl(A);
6496     if (!ADecl)
6497       return false;
6498     const Decl *BDecl = GetLValueBaseDecl(B);
6499     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
6500       return false;
6501   }
6502 
6503   return IsGlobalLValue(A.getLValueBase()) ||
6504          A.getLValueCallIndex() == B.getLValueCallIndex();
6505 }
6506 
6507 /// \brief Determine whether this is a pointer past the end of the complete
6508 /// object referred to by the lvalue.
isOnePastTheEndOfCompleteObject(const ASTContext & Ctx,const LValue & LV)6509 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6510                                             const LValue &LV) {
6511   // A null pointer can be viewed as being "past the end" but we don't
6512   // choose to look at it that way here.
6513   if (!LV.getLValueBase())
6514     return false;
6515 
6516   // If the designator is valid and refers to a subobject, we're not pointing
6517   // past the end.
6518   if (!LV.getLValueDesignator().Invalid &&
6519       !LV.getLValueDesignator().isOnePastTheEnd())
6520     return false;
6521 
6522   // We're a past-the-end pointer if we point to the byte after the object,
6523   // no matter what our type or path is.
6524   auto Size = Ctx.getTypeSizeInChars(getType(LV.getLValueBase()));
6525   return LV.getLValueOffset() == Size;
6526 }
6527 
6528 namespace {
6529 
6530 /// \brief Data recursive integer evaluator of certain binary operators.
6531 ///
6532 /// We use a data recursive algorithm for binary operators so that we are able
6533 /// to handle extreme cases of chained binary operators without causing stack
6534 /// overflow.
6535 class DataRecursiveIntBinOpEvaluator {
6536   struct EvalResult {
6537     APValue Val;
6538     bool Failed;
6539 
EvalResult__anona626307c1311::DataRecursiveIntBinOpEvaluator::EvalResult6540     EvalResult() : Failed(false) { }
6541 
swap__anona626307c1311::DataRecursiveIntBinOpEvaluator::EvalResult6542     void swap(EvalResult &RHS) {
6543       Val.swap(RHS.Val);
6544       Failed = RHS.Failed;
6545       RHS.Failed = false;
6546     }
6547   };
6548 
6549   struct Job {
6550     const Expr *E;
6551     EvalResult LHSResult; // meaningful only for binary operator expression.
6552     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6553 
Job__anona626307c1311::DataRecursiveIntBinOpEvaluator::Job6554     Job() : StoredInfo(nullptr) {}
startSpeculativeEval__anona626307c1311::DataRecursiveIntBinOpEvaluator::Job6555     void startSpeculativeEval(EvalInfo &Info) {
6556       OldEvalStatus = Info.EvalStatus;
6557       Info.EvalStatus.Diag = nullptr;
6558       StoredInfo = &Info;
6559     }
~Job__anona626307c1311::DataRecursiveIntBinOpEvaluator::Job6560     ~Job() {
6561       if (StoredInfo) {
6562         StoredInfo->EvalStatus = OldEvalStatus;
6563       }
6564     }
6565   private:
6566     EvalInfo *StoredInfo; // non-null if status changed.
6567     Expr::EvalStatus OldEvalStatus;
6568   };
6569 
6570   SmallVector<Job, 16> Queue;
6571 
6572   IntExprEvaluator &IntEval;
6573   EvalInfo &Info;
6574   APValue &FinalResult;
6575 
6576 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)6577   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6578     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6579 
6580   /// \brief True if \param E is a binary operator that we are going to handle
6581   /// data recursively.
6582   /// We handle binary operators that are comma, logical, or that have operands
6583   /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)6584   static bool shouldEnqueue(const BinaryOperator *E) {
6585     return E->getOpcode() == BO_Comma ||
6586            E->isLogicalOp() ||
6587            (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6588             E->getRHS()->getType()->isIntegralOrEnumerationType());
6589   }
6590 
Traverse(const BinaryOperator * E)6591   bool Traverse(const BinaryOperator *E) {
6592     enqueue(E);
6593     EvalResult PrevResult;
6594     while (!Queue.empty())
6595       process(PrevResult);
6596 
6597     if (PrevResult.Failed) return false;
6598 
6599     FinalResult.swap(PrevResult.Val);
6600     return true;
6601   }
6602 
6603 private:
Success(uint64_t Value,const Expr * E,APValue & Result)6604   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6605     return IntEval.Success(Value, E, Result);
6606   }
Success(const APSInt & Value,const Expr * E,APValue & Result)6607   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6608     return IntEval.Success(Value, E, Result);
6609   }
Error(const Expr * E)6610   bool Error(const Expr *E) {
6611     return IntEval.Error(E);
6612   }
Error(const Expr * E,diag::kind D)6613   bool Error(const Expr *E, diag::kind D) {
6614     return IntEval.Error(E, D);
6615   }
6616 
CCEDiag(const Expr * E,diag::kind D)6617   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6618     return Info.CCEDiag(E, D);
6619   }
6620 
6621   // \brief Returns true if visiting the RHS is necessary, false otherwise.
6622   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6623                          bool &SuppressRHSDiags);
6624 
6625   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6626                   const BinaryOperator *E, APValue &Result);
6627 
EvaluateExpr(const Expr * E,EvalResult & Result)6628   void EvaluateExpr(const Expr *E, EvalResult &Result) {
6629     Result.Failed = !Evaluate(Result.Val, Info, E);
6630     if (Result.Failed)
6631       Result.Val = APValue();
6632   }
6633 
6634   void process(EvalResult &Result);
6635 
enqueue(const Expr * E)6636   void enqueue(const Expr *E) {
6637     E = E->IgnoreParens();
6638     Queue.resize(Queue.size()+1);
6639     Queue.back().E = E;
6640     Queue.back().Kind = Job::AnyExprKind;
6641   }
6642 };
6643 
6644 }
6645 
6646 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)6647        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6648                          bool &SuppressRHSDiags) {
6649   if (E->getOpcode() == BO_Comma) {
6650     // Ignore LHS but note if we could not evaluate it.
6651     if (LHSResult.Failed)
6652       return Info.noteSideEffect();
6653     return true;
6654   }
6655 
6656   if (E->isLogicalOp()) {
6657     bool LHSAsBool;
6658     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
6659       // We were able to evaluate the LHS, see if we can get away with not
6660       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
6661       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6662         Success(LHSAsBool, E, LHSResult.Val);
6663         return false; // Ignore RHS
6664       }
6665     } else {
6666       LHSResult.Failed = true;
6667 
6668       // Since we weren't able to evaluate the left hand side, it
6669       // must have had side effects.
6670       if (!Info.noteSideEffect())
6671         return false;
6672 
6673       // We can't evaluate the LHS; however, sometimes the result
6674       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6675       // Don't ignore RHS and suppress diagnostics from this arm.
6676       SuppressRHSDiags = true;
6677     }
6678 
6679     return true;
6680   }
6681 
6682   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6683          E->getRHS()->getType()->isIntegralOrEnumerationType());
6684 
6685   if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
6686     return false; // Ignore RHS;
6687 
6688   return true;
6689 }
6690 
6691 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)6692        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6693                   const BinaryOperator *E, APValue &Result) {
6694   if (E->getOpcode() == BO_Comma) {
6695     if (RHSResult.Failed)
6696       return false;
6697     Result = RHSResult.Val;
6698     return true;
6699   }
6700 
6701   if (E->isLogicalOp()) {
6702     bool lhsResult, rhsResult;
6703     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6704     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6705 
6706     if (LHSIsOK) {
6707       if (RHSIsOK) {
6708         if (E->getOpcode() == BO_LOr)
6709           return Success(lhsResult || rhsResult, E, Result);
6710         else
6711           return Success(lhsResult && rhsResult, E, Result);
6712       }
6713     } else {
6714       if (RHSIsOK) {
6715         // We can't evaluate the LHS; however, sometimes the result
6716         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6717         if (rhsResult == (E->getOpcode() == BO_LOr))
6718           return Success(rhsResult, E, Result);
6719       }
6720     }
6721 
6722     return false;
6723   }
6724 
6725   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6726          E->getRHS()->getType()->isIntegralOrEnumerationType());
6727 
6728   if (LHSResult.Failed || RHSResult.Failed)
6729     return false;
6730 
6731   const APValue &LHSVal = LHSResult.Val;
6732   const APValue &RHSVal = RHSResult.Val;
6733 
6734   // Handle cases like (unsigned long)&a + 4.
6735   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6736     Result = LHSVal;
6737     CharUnits AdditionalOffset =
6738         CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
6739     if (E->getOpcode() == BO_Add)
6740       Result.getLValueOffset() += AdditionalOffset;
6741     else
6742       Result.getLValueOffset() -= AdditionalOffset;
6743     return true;
6744   }
6745 
6746   // Handle cases like 4 + (unsigned long)&a
6747   if (E->getOpcode() == BO_Add &&
6748       RHSVal.isLValue() && LHSVal.isInt()) {
6749     Result = RHSVal;
6750     Result.getLValueOffset() +=
6751         CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
6752     return true;
6753   }
6754 
6755   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6756     // Handle (intptr_t)&&A - (intptr_t)&&B.
6757     if (!LHSVal.getLValueOffset().isZero() ||
6758         !RHSVal.getLValueOffset().isZero())
6759       return false;
6760     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6761     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6762     if (!LHSExpr || !RHSExpr)
6763       return false;
6764     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6765     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6766     if (!LHSAddrExpr || !RHSAddrExpr)
6767       return false;
6768     // Make sure both labels come from the same function.
6769     if (LHSAddrExpr->getLabel()->getDeclContext() !=
6770         RHSAddrExpr->getLabel()->getDeclContext())
6771       return false;
6772     Result = APValue(LHSAddrExpr, RHSAddrExpr);
6773     return true;
6774   }
6775 
6776   // All the remaining cases expect both operands to be an integer
6777   if (!LHSVal.isInt() || !RHSVal.isInt())
6778     return Error(E);
6779 
6780   // Set up the width and signedness manually, in case it can't be deduced
6781   // from the operation we're performing.
6782   // FIXME: Don't do this in the cases where we can deduce it.
6783   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6784                E->getType()->isUnsignedIntegerOrEnumerationType());
6785   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6786                          RHSVal.getInt(), Value))
6787     return false;
6788   return Success(Value, E, Result);
6789 }
6790 
process(EvalResult & Result)6791 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
6792   Job &job = Queue.back();
6793 
6794   switch (job.Kind) {
6795     case Job::AnyExprKind: {
6796       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6797         if (shouldEnqueue(Bop)) {
6798           job.Kind = Job::BinOpKind;
6799           enqueue(Bop->getLHS());
6800           return;
6801         }
6802       }
6803 
6804       EvaluateExpr(job.E, Result);
6805       Queue.pop_back();
6806       return;
6807     }
6808 
6809     case Job::BinOpKind: {
6810       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6811       bool SuppressRHSDiags = false;
6812       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
6813         Queue.pop_back();
6814         return;
6815       }
6816       if (SuppressRHSDiags)
6817         job.startSpeculativeEval(Info);
6818       job.LHSResult.swap(Result);
6819       job.Kind = Job::BinOpVisitedLHSKind;
6820       enqueue(Bop->getRHS());
6821       return;
6822     }
6823 
6824     case Job::BinOpVisitedLHSKind: {
6825       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6826       EvalResult RHS;
6827       RHS.swap(Result);
6828       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
6829       Queue.pop_back();
6830       return;
6831     }
6832   }
6833 
6834   llvm_unreachable("Invalid Job::Kind!");
6835 }
6836 
VisitBinaryOperator(const BinaryOperator * E)6837 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6838   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
6839     return Error(E);
6840 
6841   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6842     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
6843 
6844   QualType LHSTy = E->getLHS()->getType();
6845   QualType RHSTy = E->getRHS()->getType();
6846 
6847   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
6848     ComplexValue LHS, RHS;
6849     bool LHSOK;
6850     if (E->isAssignmentOp()) {
6851       LValue LV;
6852       EvaluateLValue(E->getLHS(), LV, Info);
6853       LHSOK = false;
6854     } else if (LHSTy->isRealFloatingType()) {
6855       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
6856       if (LHSOK) {
6857         LHS.makeComplexFloat();
6858         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
6859       }
6860     } else {
6861       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6862     }
6863     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6864       return false;
6865 
6866     if (E->getRHS()->getType()->isRealFloatingType()) {
6867       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
6868         return false;
6869       RHS.makeComplexFloat();
6870       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
6871     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
6872       return false;
6873 
6874     if (LHS.isComplexFloat()) {
6875       APFloat::cmpResult CR_r =
6876         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
6877       APFloat::cmpResult CR_i =
6878         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6879 
6880       if (E->getOpcode() == BO_EQ)
6881         return Success((CR_r == APFloat::cmpEqual &&
6882                         CR_i == APFloat::cmpEqual), E);
6883       else {
6884         assert(E->getOpcode() == BO_NE &&
6885                "Invalid complex comparison.");
6886         return Success(((CR_r == APFloat::cmpGreaterThan ||
6887                          CR_r == APFloat::cmpLessThan ||
6888                          CR_r == APFloat::cmpUnordered) ||
6889                         (CR_i == APFloat::cmpGreaterThan ||
6890                          CR_i == APFloat::cmpLessThan ||
6891                          CR_i == APFloat::cmpUnordered)), E);
6892       }
6893     } else {
6894       if (E->getOpcode() == BO_EQ)
6895         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6896                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6897       else {
6898         assert(E->getOpcode() == BO_NE &&
6899                "Invalid compex comparison.");
6900         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6901                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6902       }
6903     }
6904   }
6905 
6906   if (LHSTy->isRealFloatingType() &&
6907       RHSTy->isRealFloatingType()) {
6908     APFloat RHS(0.0), LHS(0.0);
6909 
6910     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6911     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6912       return false;
6913 
6914     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
6915       return false;
6916 
6917     APFloat::cmpResult CR = LHS.compare(RHS);
6918 
6919     switch (E->getOpcode()) {
6920     default:
6921       llvm_unreachable("Invalid binary operator!");
6922     case BO_LT:
6923       return Success(CR == APFloat::cmpLessThan, E);
6924     case BO_GT:
6925       return Success(CR == APFloat::cmpGreaterThan, E);
6926     case BO_LE:
6927       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
6928     case BO_GE:
6929       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
6930                      E);
6931     case BO_EQ:
6932       return Success(CR == APFloat::cmpEqual, E);
6933     case BO_NE:
6934       return Success(CR == APFloat::cmpGreaterThan
6935                      || CR == APFloat::cmpLessThan
6936                      || CR == APFloat::cmpUnordered, E);
6937     }
6938   }
6939 
6940   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6941     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
6942       LValue LHSValue, RHSValue;
6943 
6944       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6945       if (!LHSOK && Info.keepEvaluatingAfterFailure())
6946         return false;
6947 
6948       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6949         return false;
6950 
6951       // Reject differing bases from the normal codepath; we special-case
6952       // comparisons to null.
6953       if (!HasSameBase(LHSValue, RHSValue)) {
6954         if (E->getOpcode() == BO_Sub) {
6955           // Handle &&A - &&B.
6956           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6957             return false;
6958           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
6959           const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
6960           if (!LHSExpr || !RHSExpr)
6961             return false;
6962           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6963           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6964           if (!LHSAddrExpr || !RHSAddrExpr)
6965             return false;
6966           // Make sure both labels come from the same function.
6967           if (LHSAddrExpr->getLabel()->getDeclContext() !=
6968               RHSAddrExpr->getLabel()->getDeclContext())
6969             return false;
6970           Result = APValue(LHSAddrExpr, RHSAddrExpr);
6971           return true;
6972         }
6973         // Inequalities and subtractions between unrelated pointers have
6974         // unspecified or undefined behavior.
6975         if (!E->isEqualityOp())
6976           return Error(E);
6977         // A constant address may compare equal to the address of a symbol.
6978         // The one exception is that address of an object cannot compare equal
6979         // to a null pointer constant.
6980         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6981             (!RHSValue.Base && !RHSValue.Offset.isZero()))
6982           return Error(E);
6983         // It's implementation-defined whether distinct literals will have
6984         // distinct addresses. In clang, the result of such a comparison is
6985         // unspecified, so it is not a constant expression. However, we do know
6986         // that the address of a literal will be non-null.
6987         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6988             LHSValue.Base && RHSValue.Base)
6989           return Error(E);
6990         // We can't tell whether weak symbols will end up pointing to the same
6991         // object.
6992         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
6993           return Error(E);
6994         // We can't compare the address of the start of one object with the
6995         // past-the-end address of another object, per C++ DR1652.
6996         if ((LHSValue.Base && LHSValue.Offset.isZero() &&
6997              isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
6998             (RHSValue.Base && RHSValue.Offset.isZero() &&
6999              isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7000           return Error(E);
7001         // We can't tell whether an object is at the same address as another
7002         // zero sized object.
7003         if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7004             (LHSValue.Base && isZeroSized(RHSValue)))
7005           return Error(E);
7006         // Pointers with different bases cannot represent the same object.
7007         // (Note that clang defaults to -fmerge-all-constants, which can
7008         // lead to inconsistent results for comparisons involving the address
7009         // of a constant; this generally doesn't matter in practice.)
7010         return Success(E->getOpcode() == BO_NE, E);
7011       }
7012 
7013       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7014       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7015 
7016       SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7017       SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7018 
7019       if (E->getOpcode() == BO_Sub) {
7020         // C++11 [expr.add]p6:
7021         //   Unless both pointers point to elements of the same array object, or
7022         //   one past the last element of the array object, the behavior is
7023         //   undefined.
7024         if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7025             !AreElementsOfSameArray(getType(LHSValue.Base),
7026                                     LHSDesignator, RHSDesignator))
7027           CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7028 
7029         QualType Type = E->getLHS()->getType();
7030         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
7031 
7032         CharUnits ElementSize;
7033         if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
7034           return false;
7035 
7036         // As an extension, a type may have zero size (empty struct or union in
7037         // C, array of zero length). Pointer subtraction in such cases has
7038         // undefined behavior, so is not constant.
7039         if (ElementSize.isZero()) {
7040           Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7041             << ElementType;
7042           return false;
7043         }
7044 
7045         // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7046         // and produce incorrect results when it overflows. Such behavior
7047         // appears to be non-conforming, but is common, so perhaps we should
7048         // assume the standard intended for such cases to be undefined behavior
7049         // and check for them.
7050 
7051         // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7052         // overflow in the final conversion to ptrdiff_t.
7053         APSInt LHS(
7054           llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7055         APSInt RHS(
7056           llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7057         APSInt ElemSize(
7058           llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7059         APSInt TrueResult = (LHS - RHS) / ElemSize;
7060         APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7061 
7062         if (Result.extend(65) != TrueResult)
7063           HandleOverflow(Info, E, TrueResult, E->getType());
7064         return Success(Result, E);
7065       }
7066 
7067       // C++11 [expr.rel]p3:
7068       //   Pointers to void (after pointer conversions) can be compared, with a
7069       //   result defined as follows: If both pointers represent the same
7070       //   address or are both the null pointer value, the result is true if the
7071       //   operator is <= or >= and false otherwise; otherwise the result is
7072       //   unspecified.
7073       // We interpret this as applying to pointers to *cv* void.
7074       if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
7075           E->isRelationalOp())
7076         CCEDiag(E, diag::note_constexpr_void_comparison);
7077 
7078       // C++11 [expr.rel]p2:
7079       // - If two pointers point to non-static data members of the same object,
7080       //   or to subobjects or array elements fo such members, recursively, the
7081       //   pointer to the later declared member compares greater provided the
7082       //   two members have the same access control and provided their class is
7083       //   not a union.
7084       //   [...]
7085       // - Otherwise pointer comparisons are unspecified.
7086       if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7087           E->isRelationalOp()) {
7088         bool WasArrayIndex;
7089         unsigned Mismatch =
7090           FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7091                                  RHSDesignator, WasArrayIndex);
7092         // At the point where the designators diverge, the comparison has a
7093         // specified value if:
7094         //  - we are comparing array indices
7095         //  - we are comparing fields of a union, or fields with the same access
7096         // Otherwise, the result is unspecified and thus the comparison is not a
7097         // constant expression.
7098         if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7099             Mismatch < RHSDesignator.Entries.size()) {
7100           const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7101           const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7102           if (!LF && !RF)
7103             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7104           else if (!LF)
7105             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7106               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7107               << RF->getParent() << RF;
7108           else if (!RF)
7109             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7110               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7111               << LF->getParent() << LF;
7112           else if (!LF->getParent()->isUnion() &&
7113                    LF->getAccess() != RF->getAccess())
7114             CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7115               << LF << LF->getAccess() << RF << RF->getAccess()
7116               << LF->getParent();
7117         }
7118       }
7119 
7120       // The comparison here must be unsigned, and performed with the same
7121       // width as the pointer.
7122       unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7123       uint64_t CompareLHS = LHSOffset.getQuantity();
7124       uint64_t CompareRHS = RHSOffset.getQuantity();
7125       assert(PtrSize <= 64 && "Unexpected pointer width");
7126       uint64_t Mask = ~0ULL >> (64 - PtrSize);
7127       CompareLHS &= Mask;
7128       CompareRHS &= Mask;
7129 
7130       // If there is a base and this is a relational operator, we can only
7131       // compare pointers within the object in question; otherwise, the result
7132       // depends on where the object is located in memory.
7133       if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7134         QualType BaseTy = getType(LHSValue.Base);
7135         if (BaseTy->isIncompleteType())
7136           return Error(E);
7137         CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7138         uint64_t OffsetLimit = Size.getQuantity();
7139         if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7140           return Error(E);
7141       }
7142 
7143       switch (E->getOpcode()) {
7144       default: llvm_unreachable("missing comparison operator");
7145       case BO_LT: return Success(CompareLHS < CompareRHS, E);
7146       case BO_GT: return Success(CompareLHS > CompareRHS, E);
7147       case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7148       case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7149       case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7150       case BO_NE: return Success(CompareLHS != CompareRHS, E);
7151       }
7152     }
7153   }
7154 
7155   if (LHSTy->isMemberPointerType()) {
7156     assert(E->isEqualityOp() && "unexpected member pointer operation");
7157     assert(RHSTy->isMemberPointerType() && "invalid comparison");
7158 
7159     MemberPtr LHSValue, RHSValue;
7160 
7161     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7162     if (!LHSOK && Info.keepEvaluatingAfterFailure())
7163       return false;
7164 
7165     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7166       return false;
7167 
7168     // C++11 [expr.eq]p2:
7169     //   If both operands are null, they compare equal. Otherwise if only one is
7170     //   null, they compare unequal.
7171     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7172       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7173       return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7174     }
7175 
7176     //   Otherwise if either is a pointer to a virtual member function, the
7177     //   result is unspecified.
7178     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7179       if (MD->isVirtual())
7180         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7181     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7182       if (MD->isVirtual())
7183         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7184 
7185     //   Otherwise they compare equal if and only if they would refer to the
7186     //   same member of the same most derived object or the same subobject if
7187     //   they were dereferenced with a hypothetical object of the associated
7188     //   class type.
7189     bool Equal = LHSValue == RHSValue;
7190     return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7191   }
7192 
7193   if (LHSTy->isNullPtrType()) {
7194     assert(E->isComparisonOp() && "unexpected nullptr operation");
7195     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7196     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7197     // are compared, the result is true of the operator is <=, >= or ==, and
7198     // false otherwise.
7199     BinaryOperator::Opcode Opcode = E->getOpcode();
7200     return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7201   }
7202 
7203   assert((!LHSTy->isIntegralOrEnumerationType() ||
7204           !RHSTy->isIntegralOrEnumerationType()) &&
7205          "DataRecursiveIntBinOpEvaluator should have handled integral types");
7206   // We can't continue from here for non-integral types.
7207   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7208 }
7209 
7210 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7211 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)7212 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7213                                     const UnaryExprOrTypeTraitExpr *E) {
7214   switch(E->getKind()) {
7215   case UETT_AlignOf: {
7216     if (E->isArgumentType())
7217       return Success(GetAlignOfType(Info, E->getArgumentType()), E);
7218     else
7219       return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
7220   }
7221 
7222   case UETT_VecStep: {
7223     QualType Ty = E->getTypeOfArgument();
7224 
7225     if (Ty->isVectorType()) {
7226       unsigned n = Ty->castAs<VectorType>()->getNumElements();
7227 
7228       // The vec_step built-in functions that take a 3-component
7229       // vector return 4. (OpenCL 1.1 spec 6.11.12)
7230       if (n == 3)
7231         n = 4;
7232 
7233       return Success(n, E);
7234     } else
7235       return Success(1, E);
7236   }
7237 
7238   case UETT_SizeOf: {
7239     QualType SrcTy = E->getTypeOfArgument();
7240     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7241     //   the result is the size of the referenced type."
7242     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7243       SrcTy = Ref->getPointeeType();
7244 
7245     CharUnits Sizeof;
7246     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
7247       return false;
7248     return Success(Sizeof, E);
7249   }
7250   }
7251 
7252   llvm_unreachable("unknown expr/type trait");
7253 }
7254 
VisitOffsetOfExpr(const OffsetOfExpr * OOE)7255 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
7256   CharUnits Result;
7257   unsigned n = OOE->getNumComponents();
7258   if (n == 0)
7259     return Error(OOE);
7260   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
7261   for (unsigned i = 0; i != n; ++i) {
7262     OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7263     switch (ON.getKind()) {
7264     case OffsetOfExpr::OffsetOfNode::Array: {
7265       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
7266       APSInt IdxResult;
7267       if (!EvaluateInteger(Idx, IdxResult, Info))
7268         return false;
7269       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7270       if (!AT)
7271         return Error(OOE);
7272       CurrentType = AT->getElementType();
7273       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7274       Result += IdxResult.getSExtValue() * ElementSize;
7275       break;
7276     }
7277 
7278     case OffsetOfExpr::OffsetOfNode::Field: {
7279       FieldDecl *MemberDecl = ON.getField();
7280       const RecordType *RT = CurrentType->getAs<RecordType>();
7281       if (!RT)
7282         return Error(OOE);
7283       RecordDecl *RD = RT->getDecl();
7284       if (RD->isInvalidDecl()) return false;
7285       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7286       unsigned i = MemberDecl->getFieldIndex();
7287       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
7288       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
7289       CurrentType = MemberDecl->getType().getNonReferenceType();
7290       break;
7291     }
7292 
7293     case OffsetOfExpr::OffsetOfNode::Identifier:
7294       llvm_unreachable("dependent __builtin_offsetof");
7295 
7296     case OffsetOfExpr::OffsetOfNode::Base: {
7297       CXXBaseSpecifier *BaseSpec = ON.getBase();
7298       if (BaseSpec->isVirtual())
7299         return Error(OOE);
7300 
7301       // Find the layout of the class whose base we are looking into.
7302       const RecordType *RT = CurrentType->getAs<RecordType>();
7303       if (!RT)
7304         return Error(OOE);
7305       RecordDecl *RD = RT->getDecl();
7306       if (RD->isInvalidDecl()) return false;
7307       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7308 
7309       // Find the base class itself.
7310       CurrentType = BaseSpec->getType();
7311       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7312       if (!BaseRT)
7313         return Error(OOE);
7314 
7315       // Add the offset to the base.
7316       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7317       break;
7318     }
7319     }
7320   }
7321   return Success(Result, OOE);
7322 }
7323 
VisitUnaryOperator(const UnaryOperator * E)7324 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7325   switch (E->getOpcode()) {
7326   default:
7327     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7328     // See C99 6.6p3.
7329     return Error(E);
7330   case UO_Extension:
7331     // FIXME: Should extension allow i-c-e extension expressions in its scope?
7332     // If so, we could clear the diagnostic ID.
7333     return Visit(E->getSubExpr());
7334   case UO_Plus:
7335     // The result is just the value.
7336     return Visit(E->getSubExpr());
7337   case UO_Minus: {
7338     if (!Visit(E->getSubExpr()))
7339       return false;
7340     if (!Result.isInt()) return Error(E);
7341     const APSInt &Value = Result.getInt();
7342     if (Value.isSigned() && Value.isMinSignedValue())
7343       HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7344                      E->getType());
7345     return Success(-Value, E);
7346   }
7347   case UO_Not: {
7348     if (!Visit(E->getSubExpr()))
7349       return false;
7350     if (!Result.isInt()) return Error(E);
7351     return Success(~Result.getInt(), E);
7352   }
7353   case UO_LNot: {
7354     bool bres;
7355     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
7356       return false;
7357     return Success(!bres, E);
7358   }
7359   }
7360 }
7361 
7362 /// HandleCast - This is used to evaluate implicit or explicit casts where the
7363 /// result type is integer.
VisitCastExpr(const CastExpr * E)7364 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7365   const Expr *SubExpr = E->getSubExpr();
7366   QualType DestType = E->getType();
7367   QualType SrcType = SubExpr->getType();
7368 
7369   switch (E->getCastKind()) {
7370   case CK_BaseToDerived:
7371   case CK_DerivedToBase:
7372   case CK_UncheckedDerivedToBase:
7373   case CK_Dynamic:
7374   case CK_ToUnion:
7375   case CK_ArrayToPointerDecay:
7376   case CK_FunctionToPointerDecay:
7377   case CK_NullToPointer:
7378   case CK_NullToMemberPointer:
7379   case CK_BaseToDerivedMemberPointer:
7380   case CK_DerivedToBaseMemberPointer:
7381   case CK_ReinterpretMemberPointer:
7382   case CK_ConstructorConversion:
7383   case CK_IntegralToPointer:
7384   case CK_ToVoid:
7385   case CK_VectorSplat:
7386   case CK_IntegralToFloating:
7387   case CK_FloatingCast:
7388   case CK_CPointerToObjCPointerCast:
7389   case CK_BlockPointerToObjCPointerCast:
7390   case CK_AnyPointerToBlockPointerCast:
7391   case CK_ObjCObjectLValueCast:
7392   case CK_FloatingRealToComplex:
7393   case CK_FloatingComplexToReal:
7394   case CK_FloatingComplexCast:
7395   case CK_FloatingComplexToIntegralComplex:
7396   case CK_IntegralRealToComplex:
7397   case CK_IntegralComplexCast:
7398   case CK_IntegralComplexToFloatingComplex:
7399   case CK_BuiltinFnToFnPtr:
7400   case CK_ZeroToOCLEvent:
7401   case CK_NonAtomicToAtomic:
7402   case CK_AddressSpaceConversion:
7403     llvm_unreachable("invalid cast kind for integral value");
7404 
7405   case CK_BitCast:
7406   case CK_Dependent:
7407   case CK_LValueBitCast:
7408   case CK_ARCProduceObject:
7409   case CK_ARCConsumeObject:
7410   case CK_ARCReclaimReturnedObject:
7411   case CK_ARCExtendBlockObject:
7412   case CK_CopyAndAutoreleaseBlockObject:
7413     return Error(E);
7414 
7415   case CK_UserDefinedConversion:
7416   case CK_LValueToRValue:
7417   case CK_AtomicToNonAtomic:
7418   case CK_NoOp:
7419     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7420 
7421   case CK_MemberPointerToBoolean:
7422   case CK_PointerToBoolean:
7423   case CK_IntegralToBoolean:
7424   case CK_FloatingToBoolean:
7425   case CK_FloatingComplexToBoolean:
7426   case CK_IntegralComplexToBoolean: {
7427     bool BoolResult;
7428     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
7429       return false;
7430     return Success(BoolResult, E);
7431   }
7432 
7433   case CK_IntegralCast: {
7434     if (!Visit(SubExpr))
7435       return false;
7436 
7437     if (!Result.isInt()) {
7438       // Allow casts of address-of-label differences if they are no-ops
7439       // or narrowing.  (The narrowing case isn't actually guaranteed to
7440       // be constant-evaluatable except in some narrow cases which are hard
7441       // to detect here.  We let it through on the assumption the user knows
7442       // what they are doing.)
7443       if (Result.isAddrLabelDiff())
7444         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
7445       // Only allow casts of lvalues if they are lossless.
7446       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7447     }
7448 
7449     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7450                                       Result.getInt()), E);
7451   }
7452 
7453   case CK_PointerToIntegral: {
7454     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7455 
7456     LValue LV;
7457     if (!EvaluatePointer(SubExpr, LV, Info))
7458       return false;
7459 
7460     if (LV.getLValueBase()) {
7461       // Only allow based lvalue casts if they are lossless.
7462       // FIXME: Allow a larger integer size than the pointer size, and allow
7463       // narrowing back down to pointer width in subsequent integral casts.
7464       // FIXME: Check integer type's active bits, not its type size.
7465       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
7466         return Error(E);
7467 
7468       LV.Designator.setInvalid();
7469       LV.moveInto(Result);
7470       return true;
7471     }
7472 
7473     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7474                                          SrcType);
7475     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
7476   }
7477 
7478   case CK_IntegralComplexToReal: {
7479     ComplexValue C;
7480     if (!EvaluateComplex(SubExpr, C, Info))
7481       return false;
7482     return Success(C.getComplexIntReal(), E);
7483   }
7484 
7485   case CK_FloatingToIntegral: {
7486     APFloat F(0.0);
7487     if (!EvaluateFloat(SubExpr, F, Info))
7488       return false;
7489 
7490     APSInt Value;
7491     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7492       return false;
7493     return Success(Value, E);
7494   }
7495   }
7496 
7497   llvm_unreachable("unknown cast resulting in integral value");
7498 }
7499 
VisitUnaryReal(const UnaryOperator * E)7500 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7501   if (E->getSubExpr()->getType()->isAnyComplexType()) {
7502     ComplexValue LV;
7503     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7504       return false;
7505     if (!LV.isComplexInt())
7506       return Error(E);
7507     return Success(LV.getComplexIntReal(), E);
7508   }
7509 
7510   return Visit(E->getSubExpr());
7511 }
7512 
VisitUnaryImag(const UnaryOperator * E)7513 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7514   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
7515     ComplexValue LV;
7516     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7517       return false;
7518     if (!LV.isComplexInt())
7519       return Error(E);
7520     return Success(LV.getComplexIntImag(), E);
7521   }
7522 
7523   VisitIgnoredValue(E->getSubExpr());
7524   return Success(0, E);
7525 }
7526 
VisitSizeOfPackExpr(const SizeOfPackExpr * E)7527 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7528   return Success(E->getPackLength(), E);
7529 }
7530 
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)7531 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7532   return Success(E->getValue(), E);
7533 }
7534 
7535 //===----------------------------------------------------------------------===//
7536 // Float Evaluation
7537 //===----------------------------------------------------------------------===//
7538 
7539 namespace {
7540 class FloatExprEvaluator
7541   : public ExprEvaluatorBase<FloatExprEvaluator> {
7542   APFloat &Result;
7543 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)7544   FloatExprEvaluator(EvalInfo &info, APFloat &result)
7545     : ExprEvaluatorBaseTy(info), Result(result) {}
7546 
Success(const APValue & V,const Expr * e)7547   bool Success(const APValue &V, const Expr *e) {
7548     Result = V.getFloat();
7549     return true;
7550   }
7551 
ZeroInitialization(const Expr * E)7552   bool ZeroInitialization(const Expr *E) {
7553     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7554     return true;
7555   }
7556 
7557   bool VisitCallExpr(const CallExpr *E);
7558 
7559   bool VisitUnaryOperator(const UnaryOperator *E);
7560   bool VisitBinaryOperator(const BinaryOperator *E);
7561   bool VisitFloatingLiteral(const FloatingLiteral *E);
7562   bool VisitCastExpr(const CastExpr *E);
7563 
7564   bool VisitUnaryReal(const UnaryOperator *E);
7565   bool VisitUnaryImag(const UnaryOperator *E);
7566 
7567   // FIXME: Missing: array subscript of vector, member of vector
7568 };
7569 } // end anonymous namespace
7570 
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)7571 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
7572   assert(E->isRValue() && E->getType()->isRealFloatingType());
7573   return FloatExprEvaluator(Info, Result).Visit(E);
7574 }
7575 
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)7576 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
7577                                   QualType ResultTy,
7578                                   const Expr *Arg,
7579                                   bool SNaN,
7580                                   llvm::APFloat &Result) {
7581   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7582   if (!S) return false;
7583 
7584   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7585 
7586   llvm::APInt fill;
7587 
7588   // Treat empty strings as if they were zero.
7589   if (S->getString().empty())
7590     fill = llvm::APInt(32, 0);
7591   else if (S->getString().getAsInteger(0, fill))
7592     return false;
7593 
7594   if (Context.getTargetInfo().isNan2008()) {
7595     if (SNaN)
7596       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7597     else
7598       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7599   } else {
7600     // Prior to IEEE 754-2008, architectures were allowed to choose whether
7601     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7602     // a different encoding to what became a standard in 2008, and for pre-
7603     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7604     // sNaN. This is now known as "legacy NaN" encoding.
7605     if (SNaN)
7606       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7607     else
7608       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7609   }
7610 
7611   return true;
7612 }
7613 
VisitCallExpr(const CallExpr * E)7614 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
7615   switch (E->getBuiltinCallee()) {
7616   default:
7617     return ExprEvaluatorBaseTy::VisitCallExpr(E);
7618 
7619   case Builtin::BI__builtin_huge_val:
7620   case Builtin::BI__builtin_huge_valf:
7621   case Builtin::BI__builtin_huge_vall:
7622   case Builtin::BI__builtin_inf:
7623   case Builtin::BI__builtin_inff:
7624   case Builtin::BI__builtin_infl: {
7625     const llvm::fltSemantics &Sem =
7626       Info.Ctx.getFloatTypeSemantics(E->getType());
7627     Result = llvm::APFloat::getInf(Sem);
7628     return true;
7629   }
7630 
7631   case Builtin::BI__builtin_nans:
7632   case Builtin::BI__builtin_nansf:
7633   case Builtin::BI__builtin_nansl:
7634     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7635                                true, Result))
7636       return Error(E);
7637     return true;
7638 
7639   case Builtin::BI__builtin_nan:
7640   case Builtin::BI__builtin_nanf:
7641   case Builtin::BI__builtin_nanl:
7642     // If this is __builtin_nan() turn this into a nan, otherwise we
7643     // can't constant fold it.
7644     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7645                                false, Result))
7646       return Error(E);
7647     return true;
7648 
7649   case Builtin::BI__builtin_fabs:
7650   case Builtin::BI__builtin_fabsf:
7651   case Builtin::BI__builtin_fabsl:
7652     if (!EvaluateFloat(E->getArg(0), Result, Info))
7653       return false;
7654 
7655     if (Result.isNegative())
7656       Result.changeSign();
7657     return true;
7658 
7659   // FIXME: Builtin::BI__builtin_powi
7660   // FIXME: Builtin::BI__builtin_powif
7661   // FIXME: Builtin::BI__builtin_powil
7662 
7663   case Builtin::BI__builtin_copysign:
7664   case Builtin::BI__builtin_copysignf:
7665   case Builtin::BI__builtin_copysignl: {
7666     APFloat RHS(0.);
7667     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7668         !EvaluateFloat(E->getArg(1), RHS, Info))
7669       return false;
7670     Result.copySign(RHS);
7671     return true;
7672   }
7673   }
7674 }
7675 
VisitUnaryReal(const UnaryOperator * E)7676 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7677   if (E->getSubExpr()->getType()->isAnyComplexType()) {
7678     ComplexValue CV;
7679     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7680       return false;
7681     Result = CV.FloatReal;
7682     return true;
7683   }
7684 
7685   return Visit(E->getSubExpr());
7686 }
7687 
VisitUnaryImag(const UnaryOperator * E)7688 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7689   if (E->getSubExpr()->getType()->isAnyComplexType()) {
7690     ComplexValue CV;
7691     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7692       return false;
7693     Result = CV.FloatImag;
7694     return true;
7695   }
7696 
7697   VisitIgnoredValue(E->getSubExpr());
7698   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7699   Result = llvm::APFloat::getZero(Sem);
7700   return true;
7701 }
7702 
VisitUnaryOperator(const UnaryOperator * E)7703 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7704   switch (E->getOpcode()) {
7705   default: return Error(E);
7706   case UO_Plus:
7707     return EvaluateFloat(E->getSubExpr(), Result, Info);
7708   case UO_Minus:
7709     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7710       return false;
7711     Result.changeSign();
7712     return true;
7713   }
7714 }
7715 
VisitBinaryOperator(const BinaryOperator * E)7716 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7717   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7718     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7719 
7720   APFloat RHS(0.0);
7721   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7722   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7723     return false;
7724   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7725          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
7726 }
7727 
VisitFloatingLiteral(const FloatingLiteral * E)7728 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7729   Result = E->getValue();
7730   return true;
7731 }
7732 
VisitCastExpr(const CastExpr * E)7733 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7734   const Expr* SubExpr = E->getSubExpr();
7735 
7736   switch (E->getCastKind()) {
7737   default:
7738     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7739 
7740   case CK_IntegralToFloating: {
7741     APSInt IntResult;
7742     return EvaluateInteger(SubExpr, IntResult, Info) &&
7743            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7744                                 E->getType(), Result);
7745   }
7746 
7747   case CK_FloatingCast: {
7748     if (!Visit(SubExpr))
7749       return false;
7750     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7751                                   Result);
7752   }
7753 
7754   case CK_FloatingComplexToReal: {
7755     ComplexValue V;
7756     if (!EvaluateComplex(SubExpr, V, Info))
7757       return false;
7758     Result = V.getComplexFloatReal();
7759     return true;
7760   }
7761   }
7762 }
7763 
7764 //===----------------------------------------------------------------------===//
7765 // Complex Evaluation (for float and integer)
7766 //===----------------------------------------------------------------------===//
7767 
7768 namespace {
7769 class ComplexExprEvaluator
7770   : public ExprEvaluatorBase<ComplexExprEvaluator> {
7771   ComplexValue &Result;
7772 
7773 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)7774   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
7775     : ExprEvaluatorBaseTy(info), Result(Result) {}
7776 
Success(const APValue & V,const Expr * e)7777   bool Success(const APValue &V, const Expr *e) {
7778     Result.setFrom(V);
7779     return true;
7780   }
7781 
7782   bool ZeroInitialization(const Expr *E);
7783 
7784   //===--------------------------------------------------------------------===//
7785   //                            Visitor Methods
7786   //===--------------------------------------------------------------------===//
7787 
7788   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
7789   bool VisitCastExpr(const CastExpr *E);
7790   bool VisitBinaryOperator(const BinaryOperator *E);
7791   bool VisitUnaryOperator(const UnaryOperator *E);
7792   bool VisitInitListExpr(const InitListExpr *E);
7793 };
7794 } // end anonymous namespace
7795 
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)7796 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7797                             EvalInfo &Info) {
7798   assert(E->isRValue() && E->getType()->isAnyComplexType());
7799   return ComplexExprEvaluator(Info, Result).Visit(E);
7800 }
7801 
ZeroInitialization(const Expr * E)7802 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
7803   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
7804   if (ElemTy->isRealFloatingType()) {
7805     Result.makeComplexFloat();
7806     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7807     Result.FloatReal = Zero;
7808     Result.FloatImag = Zero;
7809   } else {
7810     Result.makeComplexInt();
7811     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7812     Result.IntReal = Zero;
7813     Result.IntImag = Zero;
7814   }
7815   return true;
7816 }
7817 
VisitImaginaryLiteral(const ImaginaryLiteral * E)7818 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7819   const Expr* SubExpr = E->getSubExpr();
7820 
7821   if (SubExpr->getType()->isRealFloatingType()) {
7822     Result.makeComplexFloat();
7823     APFloat &Imag = Result.FloatImag;
7824     if (!EvaluateFloat(SubExpr, Imag, Info))
7825       return false;
7826 
7827     Result.FloatReal = APFloat(Imag.getSemantics());
7828     return true;
7829   } else {
7830     assert(SubExpr->getType()->isIntegerType() &&
7831            "Unexpected imaginary literal.");
7832 
7833     Result.makeComplexInt();
7834     APSInt &Imag = Result.IntImag;
7835     if (!EvaluateInteger(SubExpr, Imag, Info))
7836       return false;
7837 
7838     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7839     return true;
7840   }
7841 }
7842 
VisitCastExpr(const CastExpr * E)7843 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
7844 
7845   switch (E->getCastKind()) {
7846   case CK_BitCast:
7847   case CK_BaseToDerived:
7848   case CK_DerivedToBase:
7849   case CK_UncheckedDerivedToBase:
7850   case CK_Dynamic:
7851   case CK_ToUnion:
7852   case CK_ArrayToPointerDecay:
7853   case CK_FunctionToPointerDecay:
7854   case CK_NullToPointer:
7855   case CK_NullToMemberPointer:
7856   case CK_BaseToDerivedMemberPointer:
7857   case CK_DerivedToBaseMemberPointer:
7858   case CK_MemberPointerToBoolean:
7859   case CK_ReinterpretMemberPointer:
7860   case CK_ConstructorConversion:
7861   case CK_IntegralToPointer:
7862   case CK_PointerToIntegral:
7863   case CK_PointerToBoolean:
7864   case CK_ToVoid:
7865   case CK_VectorSplat:
7866   case CK_IntegralCast:
7867   case CK_IntegralToBoolean:
7868   case CK_IntegralToFloating:
7869   case CK_FloatingToIntegral:
7870   case CK_FloatingToBoolean:
7871   case CK_FloatingCast:
7872   case CK_CPointerToObjCPointerCast:
7873   case CK_BlockPointerToObjCPointerCast:
7874   case CK_AnyPointerToBlockPointerCast:
7875   case CK_ObjCObjectLValueCast:
7876   case CK_FloatingComplexToReal:
7877   case CK_FloatingComplexToBoolean:
7878   case CK_IntegralComplexToReal:
7879   case CK_IntegralComplexToBoolean:
7880   case CK_ARCProduceObject:
7881   case CK_ARCConsumeObject:
7882   case CK_ARCReclaimReturnedObject:
7883   case CK_ARCExtendBlockObject:
7884   case CK_CopyAndAutoreleaseBlockObject:
7885   case CK_BuiltinFnToFnPtr:
7886   case CK_ZeroToOCLEvent:
7887   case CK_NonAtomicToAtomic:
7888   case CK_AddressSpaceConversion:
7889     llvm_unreachable("invalid cast kind for complex value");
7890 
7891   case CK_LValueToRValue:
7892   case CK_AtomicToNonAtomic:
7893   case CK_NoOp:
7894     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7895 
7896   case CK_Dependent:
7897   case CK_LValueBitCast:
7898   case CK_UserDefinedConversion:
7899     return Error(E);
7900 
7901   case CK_FloatingRealToComplex: {
7902     APFloat &Real = Result.FloatReal;
7903     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
7904       return false;
7905 
7906     Result.makeComplexFloat();
7907     Result.FloatImag = APFloat(Real.getSemantics());
7908     return true;
7909   }
7910 
7911   case CK_FloatingComplexCast: {
7912     if (!Visit(E->getSubExpr()))
7913       return false;
7914 
7915     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7916     QualType From
7917       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7918 
7919     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7920            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
7921   }
7922 
7923   case CK_FloatingComplexToIntegralComplex: {
7924     if (!Visit(E->getSubExpr()))
7925       return false;
7926 
7927     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7928     QualType From
7929       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7930     Result.makeComplexInt();
7931     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7932                                 To, Result.IntReal) &&
7933            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7934                                 To, Result.IntImag);
7935   }
7936 
7937   case CK_IntegralRealToComplex: {
7938     APSInt &Real = Result.IntReal;
7939     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7940       return false;
7941 
7942     Result.makeComplexInt();
7943     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7944     return true;
7945   }
7946 
7947   case CK_IntegralComplexCast: {
7948     if (!Visit(E->getSubExpr()))
7949       return false;
7950 
7951     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7952     QualType From
7953       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7954 
7955     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7956     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
7957     return true;
7958   }
7959 
7960   case CK_IntegralComplexToFloatingComplex: {
7961     if (!Visit(E->getSubExpr()))
7962       return false;
7963 
7964     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
7965     QualType From
7966       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
7967     Result.makeComplexFloat();
7968     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7969                                 To, Result.FloatReal) &&
7970            HandleIntToFloatCast(Info, E, From, Result.IntImag,
7971                                 To, Result.FloatImag);
7972   }
7973   }
7974 
7975   llvm_unreachable("unknown cast resulting in complex value");
7976 }
7977 
VisitBinaryOperator(const BinaryOperator * E)7978 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7979   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7980     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7981 
7982   // Track whether the LHS or RHS is real at the type system level. When this is
7983   // the case we can simplify our evaluation strategy.
7984   bool LHSReal = false, RHSReal = false;
7985 
7986   bool LHSOK;
7987   if (E->getLHS()->getType()->isRealFloatingType()) {
7988     LHSReal = true;
7989     APFloat &Real = Result.FloatReal;
7990     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
7991     if (LHSOK) {
7992       Result.makeComplexFloat();
7993       Result.FloatImag = APFloat(Real.getSemantics());
7994     }
7995   } else {
7996     LHSOK = Visit(E->getLHS());
7997   }
7998   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7999     return false;
8000 
8001   ComplexValue RHS;
8002   if (E->getRHS()->getType()->isRealFloatingType()) {
8003     RHSReal = true;
8004     APFloat &Real = RHS.FloatReal;
8005     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8006       return false;
8007     RHS.makeComplexFloat();
8008     RHS.FloatImag = APFloat(Real.getSemantics());
8009   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8010     return false;
8011 
8012   assert(!(LHSReal && RHSReal) &&
8013          "Cannot have both operands of a complex operation be real.");
8014   switch (E->getOpcode()) {
8015   default: return Error(E);
8016   case BO_Add:
8017     if (Result.isComplexFloat()) {
8018       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8019                                        APFloat::rmNearestTiesToEven);
8020       if (LHSReal)
8021         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8022       else if (!RHSReal)
8023         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8024                                          APFloat::rmNearestTiesToEven);
8025     } else {
8026       Result.getComplexIntReal() += RHS.getComplexIntReal();
8027       Result.getComplexIntImag() += RHS.getComplexIntImag();
8028     }
8029     break;
8030   case BO_Sub:
8031     if (Result.isComplexFloat()) {
8032       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8033                                             APFloat::rmNearestTiesToEven);
8034       if (LHSReal) {
8035         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8036         Result.getComplexFloatImag().changeSign();
8037       } else if (!RHSReal) {
8038         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8039                                               APFloat::rmNearestTiesToEven);
8040       }
8041     } else {
8042       Result.getComplexIntReal() -= RHS.getComplexIntReal();
8043       Result.getComplexIntImag() -= RHS.getComplexIntImag();
8044     }
8045     break;
8046   case BO_Mul:
8047     if (Result.isComplexFloat()) {
8048       // This is an implementation of complex multiplication according to the
8049       // constraints laid out in C11 Annex G. The implemantion uses the
8050       // following naming scheme:
8051       //   (a + ib) * (c + id)
8052       ComplexValue LHS = Result;
8053       APFloat &A = LHS.getComplexFloatReal();
8054       APFloat &B = LHS.getComplexFloatImag();
8055       APFloat &C = RHS.getComplexFloatReal();
8056       APFloat &D = RHS.getComplexFloatImag();
8057       APFloat &ResR = Result.getComplexFloatReal();
8058       APFloat &ResI = Result.getComplexFloatImag();
8059       if (LHSReal) {
8060         assert(!RHSReal && "Cannot have two real operands for a complex op!");
8061         ResR = A * C;
8062         ResI = A * D;
8063       } else if (RHSReal) {
8064         ResR = C * A;
8065         ResI = C * B;
8066       } else {
8067         // In the fully general case, we need to handle NaNs and infinities
8068         // robustly.
8069         APFloat AC = A * C;
8070         APFloat BD = B * D;
8071         APFloat AD = A * D;
8072         APFloat BC = B * C;
8073         ResR = AC - BD;
8074         ResI = AD + BC;
8075         if (ResR.isNaN() && ResI.isNaN()) {
8076           bool Recalc = false;
8077           if (A.isInfinity() || B.isInfinity()) {
8078             A = APFloat::copySign(
8079                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8080             B = APFloat::copySign(
8081                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8082             if (C.isNaN())
8083               C = APFloat::copySign(APFloat(C.getSemantics()), C);
8084             if (D.isNaN())
8085               D = APFloat::copySign(APFloat(D.getSemantics()), D);
8086             Recalc = true;
8087           }
8088           if (C.isInfinity() || D.isInfinity()) {
8089             C = APFloat::copySign(
8090                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8091             D = APFloat::copySign(
8092                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8093             if (A.isNaN())
8094               A = APFloat::copySign(APFloat(A.getSemantics()), A);
8095             if (B.isNaN())
8096               B = APFloat::copySign(APFloat(B.getSemantics()), B);
8097             Recalc = true;
8098           }
8099           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8100                           AD.isInfinity() || BC.isInfinity())) {
8101             if (A.isNaN())
8102               A = APFloat::copySign(APFloat(A.getSemantics()), A);
8103             if (B.isNaN())
8104               B = APFloat::copySign(APFloat(B.getSemantics()), B);
8105             if (C.isNaN())
8106               C = APFloat::copySign(APFloat(C.getSemantics()), C);
8107             if (D.isNaN())
8108               D = APFloat::copySign(APFloat(D.getSemantics()), D);
8109             Recalc = true;
8110           }
8111           if (Recalc) {
8112             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8113             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8114           }
8115         }
8116       }
8117     } else {
8118       ComplexValue LHS = Result;
8119       Result.getComplexIntReal() =
8120         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8121          LHS.getComplexIntImag() * RHS.getComplexIntImag());
8122       Result.getComplexIntImag() =
8123         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8124          LHS.getComplexIntImag() * RHS.getComplexIntReal());
8125     }
8126     break;
8127   case BO_Div:
8128     if (Result.isComplexFloat()) {
8129       // This is an implementation of complex division according to the
8130       // constraints laid out in C11 Annex G. The implemantion uses the
8131       // following naming scheme:
8132       //   (a + ib) / (c + id)
8133       ComplexValue LHS = Result;
8134       APFloat &A = LHS.getComplexFloatReal();
8135       APFloat &B = LHS.getComplexFloatImag();
8136       APFloat &C = RHS.getComplexFloatReal();
8137       APFloat &D = RHS.getComplexFloatImag();
8138       APFloat &ResR = Result.getComplexFloatReal();
8139       APFloat &ResI = Result.getComplexFloatImag();
8140       if (RHSReal) {
8141         ResR = A / C;
8142         ResI = B / C;
8143       } else {
8144         if (LHSReal) {
8145           // No real optimizations we can do here, stub out with zero.
8146           B = APFloat::getZero(A.getSemantics());
8147         }
8148         int DenomLogB = 0;
8149         APFloat MaxCD = maxnum(abs(C), abs(D));
8150         if (MaxCD.isFinite()) {
8151           DenomLogB = ilogb(MaxCD);
8152           C = scalbn(C, -DenomLogB);
8153           D = scalbn(D, -DenomLogB);
8154         }
8155         APFloat Denom = C * C + D * D;
8156         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8157         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8158         if (ResR.isNaN() && ResI.isNaN()) {
8159           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8160             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8161             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8162           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8163                      D.isFinite()) {
8164             A = APFloat::copySign(
8165                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8166             B = APFloat::copySign(
8167                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8168             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8169             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8170           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8171             C = APFloat::copySign(
8172                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8173             D = APFloat::copySign(
8174                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8175             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8176             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8177           }
8178         }
8179       }
8180     } else {
8181       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8182         return Error(E, diag::note_expr_divide_by_zero);
8183 
8184       ComplexValue LHS = Result;
8185       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8186         RHS.getComplexIntImag() * RHS.getComplexIntImag();
8187       Result.getComplexIntReal() =
8188         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8189          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8190       Result.getComplexIntImag() =
8191         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8192          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8193     }
8194     break;
8195   }
8196 
8197   return true;
8198 }
8199 
VisitUnaryOperator(const UnaryOperator * E)8200 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8201   // Get the operand value into 'Result'.
8202   if (!Visit(E->getSubExpr()))
8203     return false;
8204 
8205   switch (E->getOpcode()) {
8206   default:
8207     return Error(E);
8208   case UO_Extension:
8209     return true;
8210   case UO_Plus:
8211     // The result is always just the subexpr.
8212     return true;
8213   case UO_Minus:
8214     if (Result.isComplexFloat()) {
8215       Result.getComplexFloatReal().changeSign();
8216       Result.getComplexFloatImag().changeSign();
8217     }
8218     else {
8219       Result.getComplexIntReal() = -Result.getComplexIntReal();
8220       Result.getComplexIntImag() = -Result.getComplexIntImag();
8221     }
8222     return true;
8223   case UO_Not:
8224     if (Result.isComplexFloat())
8225       Result.getComplexFloatImag().changeSign();
8226     else
8227       Result.getComplexIntImag() = -Result.getComplexIntImag();
8228     return true;
8229   }
8230 }
8231 
VisitInitListExpr(const InitListExpr * E)8232 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8233   if (E->getNumInits() == 2) {
8234     if (E->getType()->isComplexType()) {
8235       Result.makeComplexFloat();
8236       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8237         return false;
8238       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8239         return false;
8240     } else {
8241       Result.makeComplexInt();
8242       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8243         return false;
8244       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8245         return false;
8246     }
8247     return true;
8248   }
8249   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8250 }
8251 
8252 //===----------------------------------------------------------------------===//
8253 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8254 // implicit conversion.
8255 //===----------------------------------------------------------------------===//
8256 
8257 namespace {
8258 class AtomicExprEvaluator :
8259     public ExprEvaluatorBase<AtomicExprEvaluator> {
8260   APValue &Result;
8261 public:
AtomicExprEvaluator(EvalInfo & Info,APValue & Result)8262   AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8263       : ExprEvaluatorBaseTy(Info), Result(Result) {}
8264 
Success(const APValue & V,const Expr * E)8265   bool Success(const APValue &V, const Expr *E) {
8266     Result = V;
8267     return true;
8268   }
8269 
ZeroInitialization(const Expr * E)8270   bool ZeroInitialization(const Expr *E) {
8271     ImplicitValueInitExpr VIE(
8272         E->getType()->castAs<AtomicType>()->getValueType());
8273     return Evaluate(Result, Info, &VIE);
8274   }
8275 
VisitCastExpr(const CastExpr * E)8276   bool VisitCastExpr(const CastExpr *E) {
8277     switch (E->getCastKind()) {
8278     default:
8279       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8280     case CK_NonAtomicToAtomic:
8281       return Evaluate(Result, Info, E->getSubExpr());
8282     }
8283   }
8284 };
8285 } // end anonymous namespace
8286 
EvaluateAtomic(const Expr * E,APValue & Result,EvalInfo & Info)8287 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8288   assert(E->isRValue() && E->getType()->isAtomicType());
8289   return AtomicExprEvaluator(Info, Result).Visit(E);
8290 }
8291 
8292 //===----------------------------------------------------------------------===//
8293 // Void expression evaluation, primarily for a cast to void on the LHS of a
8294 // comma operator
8295 //===----------------------------------------------------------------------===//
8296 
8297 namespace {
8298 class VoidExprEvaluator
8299   : public ExprEvaluatorBase<VoidExprEvaluator> {
8300 public:
VoidExprEvaluator(EvalInfo & Info)8301   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8302 
Success(const APValue & V,const Expr * e)8303   bool Success(const APValue &V, const Expr *e) { return true; }
8304 
VisitCastExpr(const CastExpr * E)8305   bool VisitCastExpr(const CastExpr *E) {
8306     switch (E->getCastKind()) {
8307     default:
8308       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8309     case CK_ToVoid:
8310       VisitIgnoredValue(E->getSubExpr());
8311       return true;
8312     }
8313   }
8314 
VisitCallExpr(const CallExpr * E)8315   bool VisitCallExpr(const CallExpr *E) {
8316     switch (E->getBuiltinCallee()) {
8317     default:
8318       return ExprEvaluatorBaseTy::VisitCallExpr(E);
8319     case Builtin::BI__assume:
8320     case Builtin::BI__builtin_assume:
8321       // The argument is not evaluated!
8322       return true;
8323     }
8324   }
8325 };
8326 } // end anonymous namespace
8327 
EvaluateVoid(const Expr * E,EvalInfo & Info)8328 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8329   assert(E->isRValue() && E->getType()->isVoidType());
8330   return VoidExprEvaluator(Info).Visit(E);
8331 }
8332 
8333 //===----------------------------------------------------------------------===//
8334 // Top level Expr::EvaluateAsRValue method.
8335 //===----------------------------------------------------------------------===//
8336 
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)8337 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
8338   // In C, function designators are not lvalues, but we evaluate them as if they
8339   // are.
8340   QualType T = E->getType();
8341   if (E->isGLValue() || T->isFunctionType()) {
8342     LValue LV;
8343     if (!EvaluateLValue(E, LV, Info))
8344       return false;
8345     LV.moveInto(Result);
8346   } else if (T->isVectorType()) {
8347     if (!EvaluateVector(E, Result, Info))
8348       return false;
8349   } else if (T->isIntegralOrEnumerationType()) {
8350     if (!IntExprEvaluator(Info, Result).Visit(E))
8351       return false;
8352   } else if (T->hasPointerRepresentation()) {
8353     LValue LV;
8354     if (!EvaluatePointer(E, LV, Info))
8355       return false;
8356     LV.moveInto(Result);
8357   } else if (T->isRealFloatingType()) {
8358     llvm::APFloat F(0.0);
8359     if (!EvaluateFloat(E, F, Info))
8360       return false;
8361     Result = APValue(F);
8362   } else if (T->isAnyComplexType()) {
8363     ComplexValue C;
8364     if (!EvaluateComplex(E, C, Info))
8365       return false;
8366     C.moveInto(Result);
8367   } else if (T->isMemberPointerType()) {
8368     MemberPtr P;
8369     if (!EvaluateMemberPointer(E, P, Info))
8370       return false;
8371     P.moveInto(Result);
8372     return true;
8373   } else if (T->isArrayType()) {
8374     LValue LV;
8375     LV.set(E, Info.CurrentCall->Index);
8376     APValue &Value = Info.CurrentCall->createTemporary(E, false);
8377     if (!EvaluateArray(E, LV, Value, Info))
8378       return false;
8379     Result = Value;
8380   } else if (T->isRecordType()) {
8381     LValue LV;
8382     LV.set(E, Info.CurrentCall->Index);
8383     APValue &Value = Info.CurrentCall->createTemporary(E, false);
8384     if (!EvaluateRecord(E, LV, Value, Info))
8385       return false;
8386     Result = Value;
8387   } else if (T->isVoidType()) {
8388     if (!Info.getLangOpts().CPlusPlus11)
8389       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
8390         << E->getType();
8391     if (!EvaluateVoid(E, Info))
8392       return false;
8393   } else if (T->isAtomicType()) {
8394     if (!EvaluateAtomic(E, Result, Info))
8395       return false;
8396   } else if (Info.getLangOpts().CPlusPlus11) {
8397     Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
8398     return false;
8399   } else {
8400     Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
8401     return false;
8402   }
8403 
8404   return true;
8405 }
8406 
8407 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8408 /// cases, the in-place evaluation is essential, since later initializers for
8409 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,bool AllowNonLiteralTypes)8410 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
8411                             const Expr *E, bool AllowNonLiteralTypes) {
8412   assert(!E->isValueDependent());
8413 
8414   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
8415     return false;
8416 
8417   if (E->isRValue()) {
8418     // Evaluate arrays and record types in-place, so that later initializers can
8419     // refer to earlier-initialized members of the object.
8420     if (E->getType()->isArrayType())
8421       return EvaluateArray(E, This, Result, Info);
8422     else if (E->getType()->isRecordType())
8423       return EvaluateRecord(E, This, Result, Info);
8424   }
8425 
8426   // For any other type, in-place evaluation is unimportant.
8427   return Evaluate(Result, Info, E);
8428 }
8429 
8430 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8431 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)8432 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
8433   if (E->getType().isNull())
8434     return false;
8435 
8436   if (!CheckLiteralType(Info, E))
8437     return false;
8438 
8439   if (!::Evaluate(Result, Info, E))
8440     return false;
8441 
8442   if (E->isGLValue()) {
8443     LValue LV;
8444     LV.setFrom(Info.Ctx, Result);
8445     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8446       return false;
8447   }
8448 
8449   // Check this core constant expression is a constant expression.
8450   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8451 }
8452 
FastEvaluateAsRValue(const Expr * Exp,Expr::EvalResult & Result,const ASTContext & Ctx,bool & IsConst)8453 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8454                                  const ASTContext &Ctx, bool &IsConst) {
8455   // Fast-path evaluations of integer literals, since we sometimes see files
8456   // containing vast quantities of these.
8457   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8458     Result.Val = APValue(APSInt(L->getValue(),
8459                                 L->getType()->isUnsignedIntegerType()));
8460     IsConst = true;
8461     return true;
8462   }
8463 
8464   // This case should be rare, but we need to check it before we check on
8465   // the type below.
8466   if (Exp->getType().isNull()) {
8467     IsConst = false;
8468     return true;
8469   }
8470 
8471   // FIXME: Evaluating values of large array and record types can cause
8472   // performance problems. Only do so in C++11 for now.
8473   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8474                           Exp->getType()->isRecordType()) &&
8475       !Ctx.getLangOpts().CPlusPlus11) {
8476     IsConst = false;
8477     return true;
8478   }
8479   return false;
8480 }
8481 
8482 
8483 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
8484 /// any crazy technique (that has nothing to do with language standards) that
8485 /// we want to.  If this function returns true, it returns the folded constant
8486 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8487 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx) const8488 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
8489   bool IsConst;
8490   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8491     return IsConst;
8492 
8493   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
8494   return ::EvaluateAsRValue(Info, this, Result.Val);
8495 }
8496 
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx) const8497 bool Expr::EvaluateAsBooleanCondition(bool &Result,
8498                                       const ASTContext &Ctx) const {
8499   EvalResult Scratch;
8500   return EvaluateAsRValue(Scratch, Ctx) &&
8501          HandleConversionToBool(Scratch.Val, Result);
8502 }
8503 
EvaluateAsInt(APSInt & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects) const8504 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8505                          SideEffectsKind AllowSideEffects) const {
8506   if (!getType()->isIntegralOrEnumerationType())
8507     return false;
8508 
8509   EvalResult ExprResult;
8510   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8511       (!AllowSideEffects && ExprResult.HasSideEffects))
8512     return false;
8513 
8514   Result = ExprResult.Val.getInt();
8515   return true;
8516 }
8517 
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx) const8518 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
8519   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
8520 
8521   LValue LV;
8522   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8523       !CheckLValueConstantExpression(Info, getExprLoc(),
8524                                      Ctx.getLValueReferenceType(getType()), LV))
8525     return false;
8526 
8527   LV.moveInto(Result.Val);
8528   return true;
8529 }
8530 
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,SmallVectorImpl<PartialDiagnosticAt> & Notes) const8531 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8532                                  const VarDecl *VD,
8533                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
8534   // FIXME: Evaluating initializers for large array and record types can cause
8535   // performance problems. Only do so in C++11 for now.
8536   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
8537       !Ctx.getLangOpts().CPlusPlus11)
8538     return false;
8539 
8540   Expr::EvalStatus EStatus;
8541   EStatus.Diag = &Notes;
8542 
8543   EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
8544   InitInfo.setEvaluatingDecl(VD, Value);
8545 
8546   LValue LVal;
8547   LVal.set(VD);
8548 
8549   // C++11 [basic.start.init]p2:
8550   //  Variables with static storage duration or thread storage duration shall be
8551   //  zero-initialized before any other initialization takes place.
8552   // This behavior is not present in C.
8553   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
8554       !VD->getType()->isReferenceType()) {
8555     ImplicitValueInitExpr VIE(VD->getType());
8556     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
8557                          /*AllowNonLiteralTypes=*/true))
8558       return false;
8559   }
8560 
8561   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8562                        /*AllowNonLiteralTypes=*/true) ||
8563       EStatus.HasSideEffects)
8564     return false;
8565 
8566   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8567                                  Value);
8568 }
8569 
8570 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8571 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx) const8572 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
8573   EvalResult Result;
8574   return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
8575 }
8576 
EvaluateKnownConstInt(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const8577 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
8578                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
8579   EvalResult EvalResult;
8580   EvalResult.Diag = Diag;
8581   bool Result = EvaluateAsRValue(EvalResult, Ctx);
8582   (void)Result;
8583   assert(Result && "Could not evaluate expression");
8584   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
8585 
8586   return EvalResult.Val.getInt();
8587 }
8588 
EvaluateForOverflow(const ASTContext & Ctx) const8589 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
8590   bool IsConst;
8591   EvalResult EvalResult;
8592   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8593     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
8594     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8595   }
8596 }
8597 
isGlobalLValue() const8598 bool Expr::EvalResult::isGlobalLValue() const {
8599   assert(Val.isLValue());
8600   return IsGlobalLValue(Val.getLValueBase());
8601 }
8602 
8603 
8604 /// isIntegerConstantExpr - this recursive routine will test if an expression is
8605 /// an integer constant expression.
8606 
8607 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8608 /// comma, etc
8609 
8610 // CheckICE - This function does the fundamental ICE checking: the returned
8611 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8612 // and a (possibly null) SourceLocation indicating the location of the problem.
8613 //
8614 // Note that to reduce code duplication, this helper does no evaluation
8615 // itself; the caller checks whether the expression is evaluatable, and
8616 // in the rare cases where CheckICE actually cares about the evaluated
8617 // value, it calls into Evalute.
8618 
8619 namespace {
8620 
8621 enum ICEKind {
8622   /// This expression is an ICE.
8623   IK_ICE,
8624   /// This expression is not an ICE, but if it isn't evaluated, it's
8625   /// a legal subexpression for an ICE. This return value is used to handle
8626   /// the comma operator in C99 mode, and non-constant subexpressions.
8627   IK_ICEIfUnevaluated,
8628   /// This expression is not an ICE, and is not a legal subexpression for one.
8629   IK_NotICE
8630 };
8631 
8632 struct ICEDiag {
8633   ICEKind Kind;
8634   SourceLocation Loc;
8635 
ICEDiag__anona626307c1911::ICEDiag8636   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
8637 };
8638 
8639 }
8640 
NoDiag()8641 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8642 
Worst(ICEDiag A,ICEDiag B)8643 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
8644 
CheckEvalInICE(const Expr * E,const ASTContext & Ctx)8645 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
8646   Expr::EvalResult EVResult;
8647   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
8648       !EVResult.Val.isInt())
8649     return ICEDiag(IK_NotICE, E->getLocStart());
8650 
8651   return NoDiag();
8652 }
8653 
CheckICE(const Expr * E,const ASTContext & Ctx)8654 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
8655   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
8656   if (!E->getType()->isIntegralOrEnumerationType())
8657     return ICEDiag(IK_NotICE, E->getLocStart());
8658 
8659   switch (E->getStmtClass()) {
8660 #define ABSTRACT_STMT(Node)
8661 #define STMT(Node, Base) case Expr::Node##Class:
8662 #define EXPR(Node, Base)
8663 #include "clang/AST/StmtNodes.inc"
8664   case Expr::PredefinedExprClass:
8665   case Expr::FloatingLiteralClass:
8666   case Expr::ImaginaryLiteralClass:
8667   case Expr::StringLiteralClass:
8668   case Expr::ArraySubscriptExprClass:
8669   case Expr::MemberExprClass:
8670   case Expr::CompoundAssignOperatorClass:
8671   case Expr::CompoundLiteralExprClass:
8672   case Expr::ExtVectorElementExprClass:
8673   case Expr::DesignatedInitExprClass:
8674   case Expr::ImplicitValueInitExprClass:
8675   case Expr::ParenListExprClass:
8676   case Expr::VAArgExprClass:
8677   case Expr::AddrLabelExprClass:
8678   case Expr::StmtExprClass:
8679   case Expr::CXXMemberCallExprClass:
8680   case Expr::CUDAKernelCallExprClass:
8681   case Expr::CXXDynamicCastExprClass:
8682   case Expr::CXXTypeidExprClass:
8683   case Expr::CXXUuidofExprClass:
8684   case Expr::MSPropertyRefExprClass:
8685   case Expr::CXXNullPtrLiteralExprClass:
8686   case Expr::UserDefinedLiteralClass:
8687   case Expr::CXXThisExprClass:
8688   case Expr::CXXThrowExprClass:
8689   case Expr::CXXNewExprClass:
8690   case Expr::CXXDeleteExprClass:
8691   case Expr::CXXPseudoDestructorExprClass:
8692   case Expr::UnresolvedLookupExprClass:
8693   case Expr::TypoExprClass:
8694   case Expr::DependentScopeDeclRefExprClass:
8695   case Expr::CXXConstructExprClass:
8696   case Expr::CXXStdInitializerListExprClass:
8697   case Expr::CXXBindTemporaryExprClass:
8698   case Expr::ExprWithCleanupsClass:
8699   case Expr::CXXTemporaryObjectExprClass:
8700   case Expr::CXXUnresolvedConstructExprClass:
8701   case Expr::CXXDependentScopeMemberExprClass:
8702   case Expr::UnresolvedMemberExprClass:
8703   case Expr::ObjCStringLiteralClass:
8704   case Expr::ObjCBoxedExprClass:
8705   case Expr::ObjCArrayLiteralClass:
8706   case Expr::ObjCDictionaryLiteralClass:
8707   case Expr::ObjCEncodeExprClass:
8708   case Expr::ObjCMessageExprClass:
8709   case Expr::ObjCSelectorExprClass:
8710   case Expr::ObjCProtocolExprClass:
8711   case Expr::ObjCIvarRefExprClass:
8712   case Expr::ObjCPropertyRefExprClass:
8713   case Expr::ObjCSubscriptRefExprClass:
8714   case Expr::ObjCIsaExprClass:
8715   case Expr::ShuffleVectorExprClass:
8716   case Expr::ConvertVectorExprClass:
8717   case Expr::BlockExprClass:
8718   case Expr::NoStmtClass:
8719   case Expr::OpaqueValueExprClass:
8720   case Expr::PackExpansionExprClass:
8721   case Expr::SubstNonTypeTemplateParmPackExprClass:
8722   case Expr::FunctionParmPackExprClass:
8723   case Expr::AsTypeExprClass:
8724   case Expr::ObjCIndirectCopyRestoreExprClass:
8725   case Expr::MaterializeTemporaryExprClass:
8726   case Expr::PseudoObjectExprClass:
8727   case Expr::AtomicExprClass:
8728   case Expr::LambdaExprClass:
8729   case Expr::CXXFoldExprClass:
8730     return ICEDiag(IK_NotICE, E->getLocStart());
8731 
8732   case Expr::InitListExprClass: {
8733     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8734     // form "T x = { a };" is equivalent to "T x = a;".
8735     // Unless we're initializing a reference, T is a scalar as it is known to be
8736     // of integral or enumeration type.
8737     if (E->isRValue())
8738       if (cast<InitListExpr>(E)->getNumInits() == 1)
8739         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8740     return ICEDiag(IK_NotICE, E->getLocStart());
8741   }
8742 
8743   case Expr::SizeOfPackExprClass:
8744   case Expr::GNUNullExprClass:
8745     // GCC considers the GNU __null value to be an integral constant expression.
8746     return NoDiag();
8747 
8748   case Expr::SubstNonTypeTemplateParmExprClass:
8749     return
8750       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8751 
8752   case Expr::ParenExprClass:
8753     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
8754   case Expr::GenericSelectionExprClass:
8755     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
8756   case Expr::IntegerLiteralClass:
8757   case Expr::CharacterLiteralClass:
8758   case Expr::ObjCBoolLiteralExprClass:
8759   case Expr::CXXBoolLiteralExprClass:
8760   case Expr::CXXScalarValueInitExprClass:
8761   case Expr::TypeTraitExprClass:
8762   case Expr::ArrayTypeTraitExprClass:
8763   case Expr::ExpressionTraitExprClass:
8764   case Expr::CXXNoexceptExprClass:
8765     return NoDiag();
8766   case Expr::CallExprClass:
8767   case Expr::CXXOperatorCallExprClass: {
8768     // C99 6.6/3 allows function calls within unevaluated subexpressions of
8769     // constant expressions, but they can never be ICEs because an ICE cannot
8770     // contain an operand of (pointer to) function type.
8771     const CallExpr *CE = cast<CallExpr>(E);
8772     if (CE->getBuiltinCallee())
8773       return CheckEvalInICE(E, Ctx);
8774     return ICEDiag(IK_NotICE, E->getLocStart());
8775   }
8776   case Expr::DeclRefExprClass: {
8777     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8778       return NoDiag();
8779     const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
8780     if (Ctx.getLangOpts().CPlusPlus &&
8781         D && IsConstNonVolatile(D->getType())) {
8782       // Parameter variables are never constants.  Without this check,
8783       // getAnyInitializer() can find a default argument, which leads
8784       // to chaos.
8785       if (isa<ParmVarDecl>(D))
8786         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8787 
8788       // C++ 7.1.5.1p2
8789       //   A variable of non-volatile const-qualified integral or enumeration
8790       //   type initialized by an ICE can be used in ICEs.
8791       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
8792         if (!Dcl->getType()->isIntegralOrEnumerationType())
8793           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8794 
8795         const VarDecl *VD;
8796         // Look for a declaration of this variable that has an initializer, and
8797         // check whether it is an ICE.
8798         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8799           return NoDiag();
8800         else
8801           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8802       }
8803     }
8804     return ICEDiag(IK_NotICE, E->getLocStart());
8805   }
8806   case Expr::UnaryOperatorClass: {
8807     const UnaryOperator *Exp = cast<UnaryOperator>(E);
8808     switch (Exp->getOpcode()) {
8809     case UO_PostInc:
8810     case UO_PostDec:
8811     case UO_PreInc:
8812     case UO_PreDec:
8813     case UO_AddrOf:
8814     case UO_Deref:
8815       // C99 6.6/3 allows increment and decrement within unevaluated
8816       // subexpressions of constant expressions, but they can never be ICEs
8817       // because an ICE cannot contain an lvalue operand.
8818       return ICEDiag(IK_NotICE, E->getLocStart());
8819     case UO_Extension:
8820     case UO_LNot:
8821     case UO_Plus:
8822     case UO_Minus:
8823     case UO_Not:
8824     case UO_Real:
8825     case UO_Imag:
8826       return CheckICE(Exp->getSubExpr(), Ctx);
8827     }
8828 
8829     // OffsetOf falls through here.
8830   }
8831   case Expr::OffsetOfExprClass: {
8832     // Note that per C99, offsetof must be an ICE. And AFAIK, using
8833     // EvaluateAsRValue matches the proposed gcc behavior for cases like
8834     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
8835     // compliance: we should warn earlier for offsetof expressions with
8836     // array subscripts that aren't ICEs, and if the array subscripts
8837     // are ICEs, the value of the offsetof must be an integer constant.
8838     return CheckEvalInICE(E, Ctx);
8839   }
8840   case Expr::UnaryExprOrTypeTraitExprClass: {
8841     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8842     if ((Exp->getKind() ==  UETT_SizeOf) &&
8843         Exp->getTypeOfArgument()->isVariableArrayType())
8844       return ICEDiag(IK_NotICE, E->getLocStart());
8845     return NoDiag();
8846   }
8847   case Expr::BinaryOperatorClass: {
8848     const BinaryOperator *Exp = cast<BinaryOperator>(E);
8849     switch (Exp->getOpcode()) {
8850     case BO_PtrMemD:
8851     case BO_PtrMemI:
8852     case BO_Assign:
8853     case BO_MulAssign:
8854     case BO_DivAssign:
8855     case BO_RemAssign:
8856     case BO_AddAssign:
8857     case BO_SubAssign:
8858     case BO_ShlAssign:
8859     case BO_ShrAssign:
8860     case BO_AndAssign:
8861     case BO_XorAssign:
8862     case BO_OrAssign:
8863       // C99 6.6/3 allows assignments within unevaluated subexpressions of
8864       // constant expressions, but they can never be ICEs because an ICE cannot
8865       // contain an lvalue operand.
8866       return ICEDiag(IK_NotICE, E->getLocStart());
8867 
8868     case BO_Mul:
8869     case BO_Div:
8870     case BO_Rem:
8871     case BO_Add:
8872     case BO_Sub:
8873     case BO_Shl:
8874     case BO_Shr:
8875     case BO_LT:
8876     case BO_GT:
8877     case BO_LE:
8878     case BO_GE:
8879     case BO_EQ:
8880     case BO_NE:
8881     case BO_And:
8882     case BO_Xor:
8883     case BO_Or:
8884     case BO_Comma: {
8885       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8886       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8887       if (Exp->getOpcode() == BO_Div ||
8888           Exp->getOpcode() == BO_Rem) {
8889         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
8890         // we don't evaluate one.
8891         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
8892           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
8893           if (REval == 0)
8894             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8895           if (REval.isSigned() && REval.isAllOnesValue()) {
8896             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
8897             if (LEval.isMinSignedValue())
8898               return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8899           }
8900         }
8901       }
8902       if (Exp->getOpcode() == BO_Comma) {
8903         if (Ctx.getLangOpts().C99) {
8904           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8905           // if it isn't evaluated.
8906           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8907             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8908         } else {
8909           // In both C89 and C++, commas in ICEs are illegal.
8910           return ICEDiag(IK_NotICE, E->getLocStart());
8911         }
8912       }
8913       return Worst(LHSResult, RHSResult);
8914     }
8915     case BO_LAnd:
8916     case BO_LOr: {
8917       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8918       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8919       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
8920         // Rare case where the RHS has a comma "side-effect"; we need
8921         // to actually check the condition to see whether the side
8922         // with the comma is evaluated.
8923         if ((Exp->getOpcode() == BO_LAnd) !=
8924             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
8925           return RHSResult;
8926         return NoDiag();
8927       }
8928 
8929       return Worst(LHSResult, RHSResult);
8930     }
8931     }
8932   }
8933   case Expr::ImplicitCastExprClass:
8934   case Expr::CStyleCastExprClass:
8935   case Expr::CXXFunctionalCastExprClass:
8936   case Expr::CXXStaticCastExprClass:
8937   case Expr::CXXReinterpretCastExprClass:
8938   case Expr::CXXConstCastExprClass:
8939   case Expr::ObjCBridgedCastExprClass: {
8940     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
8941     if (isa<ExplicitCastExpr>(E)) {
8942       if (const FloatingLiteral *FL
8943             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8944         unsigned DestWidth = Ctx.getIntWidth(E->getType());
8945         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8946         APSInt IgnoredVal(DestWidth, !DestSigned);
8947         bool Ignored;
8948         // If the value does not fit in the destination type, the behavior is
8949         // undefined, so we are not required to treat it as a constant
8950         // expression.
8951         if (FL->getValue().convertToInteger(IgnoredVal,
8952                                             llvm::APFloat::rmTowardZero,
8953                                             &Ignored) & APFloat::opInvalidOp)
8954           return ICEDiag(IK_NotICE, E->getLocStart());
8955         return NoDiag();
8956       }
8957     }
8958     switch (cast<CastExpr>(E)->getCastKind()) {
8959     case CK_LValueToRValue:
8960     case CK_AtomicToNonAtomic:
8961     case CK_NonAtomicToAtomic:
8962     case CK_NoOp:
8963     case CK_IntegralToBoolean:
8964     case CK_IntegralCast:
8965       return CheckICE(SubExpr, Ctx);
8966     default:
8967       return ICEDiag(IK_NotICE, E->getLocStart());
8968     }
8969   }
8970   case Expr::BinaryConditionalOperatorClass: {
8971     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8972     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
8973     if (CommonResult.Kind == IK_NotICE) return CommonResult;
8974     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8975     if (FalseResult.Kind == IK_NotICE) return FalseResult;
8976     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8977     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
8978         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
8979     return FalseResult;
8980   }
8981   case Expr::ConditionalOperatorClass: {
8982     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8983     // If the condition (ignoring parens) is a __builtin_constant_p call,
8984     // then only the true side is actually considered in an integer constant
8985     // expression, and it is fully evaluated.  This is an important GNU
8986     // extension.  See GCC PR38377 for discussion.
8987     if (const CallExpr *CallCE
8988         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
8989       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8990         return CheckEvalInICE(E, Ctx);
8991     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
8992     if (CondResult.Kind == IK_NotICE)
8993       return CondResult;
8994 
8995     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8996     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8997 
8998     if (TrueResult.Kind == IK_NotICE)
8999       return TrueResult;
9000     if (FalseResult.Kind == IK_NotICE)
9001       return FalseResult;
9002     if (CondResult.Kind == IK_ICEIfUnevaluated)
9003       return CondResult;
9004     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
9005       return NoDiag();
9006     // Rare case where the diagnostics depend on which side is evaluated
9007     // Note that if we get here, CondResult is 0, and at least one of
9008     // TrueResult and FalseResult is non-zero.
9009     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
9010       return FalseResult;
9011     return TrueResult;
9012   }
9013   case Expr::CXXDefaultArgExprClass:
9014     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
9015   case Expr::CXXDefaultInitExprClass:
9016     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
9017   case Expr::ChooseExprClass: {
9018     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
9019   }
9020   }
9021 
9022   llvm_unreachable("Invalid StmtClass!");
9023 }
9024 
9025 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)9026 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
9027                                                     const Expr *E,
9028                                                     llvm::APSInt *Value,
9029                                                     SourceLocation *Loc) {
9030   if (!E->getType()->isIntegralOrEnumerationType()) {
9031     if (Loc) *Loc = E->getExprLoc();
9032     return false;
9033   }
9034 
9035   APValue Result;
9036   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
9037     return false;
9038 
9039   if (!Result.isInt()) {
9040     if (Loc) *Loc = E->getExprLoc();
9041     return false;
9042   }
9043 
9044   if (Value) *Value = Result.getInt();
9045   return true;
9046 }
9047 
isIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const9048 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9049                                  SourceLocation *Loc) const {
9050   if (Ctx.getLangOpts().CPlusPlus11)
9051     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
9052 
9053   ICEDiag D = CheckICE(this, Ctx);
9054   if (D.Kind != IK_ICE) {
9055     if (Loc) *Loc = D.Loc;
9056     return false;
9057   }
9058   return true;
9059 }
9060 
isIntegerConstantExpr(llvm::APSInt & Value,const ASTContext & Ctx,SourceLocation * Loc,bool isEvaluated) const9061 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
9062                                  SourceLocation *Loc, bool isEvaluated) const {
9063   if (Ctx.getLangOpts().CPlusPlus11)
9064     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9065 
9066   if (!isIntegerConstantExpr(Ctx, Loc))
9067     return false;
9068   if (!EvaluateAsInt(Value, Ctx))
9069     llvm_unreachable("ICE cannot be evaluated!");
9070   return true;
9071 }
9072 
isCXX98IntegralConstantExpr(const ASTContext & Ctx) const9073 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
9074   return CheckICE(this, Ctx).Kind == IK_ICE;
9075 }
9076 
isCXX11ConstantExpr(const ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const9077 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
9078                                SourceLocation *Loc) const {
9079   // We support this checking in C++98 mode in order to diagnose compatibility
9080   // issues.
9081   assert(Ctx.getLangOpts().CPlusPlus);
9082 
9083   // Build evaluation settings.
9084   Expr::EvalStatus Status;
9085   SmallVector<PartialDiagnosticAt, 8> Diags;
9086   Status.Diag = &Diags;
9087   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
9088 
9089   APValue Scratch;
9090   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9091 
9092   if (!Diags.empty()) {
9093     IsConstExpr = false;
9094     if (Loc) *Loc = Diags[0].first;
9095   } else if (!IsConstExpr) {
9096     // FIXME: This shouldn't happen.
9097     if (Loc) *Loc = getExprLoc();
9098   }
9099 
9100   return IsConstExpr;
9101 }
9102 
EvaluateWithSubstitution(APValue & Value,ASTContext & Ctx,const FunctionDecl * Callee,ArrayRef<const Expr * > Args) const9103 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9104                                     const FunctionDecl *Callee,
9105                                     ArrayRef<const Expr*> Args) const {
9106   Expr::EvalStatus Status;
9107   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9108 
9109   ArgVector ArgValues(Args.size());
9110   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9111        I != E; ++I) {
9112     if ((*I)->isValueDependent() ||
9113         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
9114       // If evaluation fails, throw away the argument entirely.
9115       ArgValues[I - Args.begin()] = APValue();
9116     if (Info.EvalStatus.HasSideEffects)
9117       return false;
9118   }
9119 
9120   // Build fake call to Callee.
9121   CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
9122                        ArgValues.data());
9123   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9124 }
9125 
isPotentialConstantExpr(const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)9126 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
9127                                    SmallVectorImpl<
9128                                      PartialDiagnosticAt> &Diags) {
9129   // FIXME: It would be useful to check constexpr function templates, but at the
9130   // moment the constant expression evaluator cannot cope with the non-rigorous
9131   // ASTs which we build for dependent expressions.
9132   if (FD->isDependentContext())
9133     return true;
9134 
9135   Expr::EvalStatus Status;
9136   Status.Diag = &Diags;
9137 
9138   EvalInfo Info(FD->getASTContext(), Status,
9139                 EvalInfo::EM_PotentialConstantExpression);
9140 
9141   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9142   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
9143 
9144   // Fabricate an arbitrary expression on the stack and pretend that it
9145   // is a temporary being used as the 'this' pointer.
9146   LValue This;
9147   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
9148   This.set(&VIE, Info.CurrentCall->Index);
9149 
9150   ArrayRef<const Expr*> Args;
9151 
9152   SourceLocation Loc = FD->getLocation();
9153 
9154   APValue Scratch;
9155   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9156     // Evaluate the call as a constant initializer, to allow the construction
9157     // of objects of non-literal types.
9158     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
9159     HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
9160   } else
9161     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
9162                        Args, FD->getBody(), Info, Scratch);
9163 
9164   return Diags.empty();
9165 }
9166 
isPotentialConstantExprUnevaluated(Expr * E,const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)9167 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9168                                               const FunctionDecl *FD,
9169                                               SmallVectorImpl<
9170                                                 PartialDiagnosticAt> &Diags) {
9171   Expr::EvalStatus Status;
9172   Status.Diag = &Diags;
9173 
9174   EvalInfo Info(FD->getASTContext(), Status,
9175                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9176 
9177   // Fabricate a call stack frame to give the arguments a plausible cover story.
9178   ArrayRef<const Expr*> Args;
9179   ArgVector ArgValues(0);
9180   bool Success = EvaluateArgs(Args, ArgValues, Info);
9181   (void)Success;
9182   assert(Success &&
9183          "Failed to set up arguments for potential constant evaluation");
9184   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
9185 
9186   APValue ResultScratch;
9187   Evaluate(ResultScratch, Info, E);
9188   return Diags.empty();
9189 }
9190