ExprConstant.cpp revision 86c3ae46250cdcc57778c27826060779a92f3815
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 rules only, at the moment), or, if folding failed too,
27//    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/CharUnits.h"
39#include "clang/AST/RecordLayout.h"
40#include "clang/AST/StmtVisitor.h"
41#include "clang/AST/TypeLoc.h"
42#include "clang/AST/ASTDiagnostic.h"
43#include "clang/AST/Expr.h"
44#include "clang/Basic/Builtins.h"
45#include "clang/Basic/TargetInfo.h"
46#include "llvm/ADT/SmallString.h"
47#include <cstring>
48#include <functional>
49
50using namespace clang;
51using llvm::APSInt;
52using llvm::APFloat;
53
54/// EvalInfo - This is a private struct used by the evaluator to capture
55/// information about a subexpression as it is folded.  It retains information
56/// about the AST context, but also maintains information about the folded
57/// expression.
58///
59/// If an expression could be evaluated, it is still possible it is not a C
60/// "integer constant expression" or constant expression.  If not, this struct
61/// captures information about how and why not.
62///
63/// One bit of information passed *into* the request for constant folding
64/// indicates whether the subexpression is "evaluated" or not according to C
65/// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
66/// evaluate the expression regardless of what the RHS is, but C only allows
67/// certain things in certain situations.
68namespace {
69  struct LValue;
70  struct CallStackFrame;
71  struct EvalInfo;
72
73  QualType getType(APValue::LValueBase B) {
74    if (!B) return QualType();
75    if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
76      return D->getType();
77    return B.get<const Expr*>()->getType();
78  }
79
80  /// Get an LValue path entry, which is known to not be an array index, as a
81  /// field or base class.
82  APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
83    APValue::BaseOrMemberType Value;
84    Value.setFromOpaqueValue(E.BaseOrMember);
85    return Value;
86  }
87
88  /// Get an LValue path entry, which is known to not be an array index, as a
89  /// field declaration.
90  const FieldDecl *getAsField(APValue::LValuePathEntry E) {
91    return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
92  }
93  /// Get an LValue path entry, which is known to not be an array index, as a
94  /// base class declaration.
95  const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
96    return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
97  }
98  /// Determine whether this LValue path entry for a base class names a virtual
99  /// base class.
100  bool isVirtualBaseClass(APValue::LValuePathEntry E) {
101    return getAsBaseOrMember(E).getInt();
102  }
103
104  /// Find the path length and type of the most-derived subobject in the given
105  /// path, and find the size of the containing array, if any.
106  static
107  unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
108                                    ArrayRef<APValue::LValuePathEntry> Path,
109                                    uint64_t &ArraySize, QualType &Type) {
110    unsigned MostDerivedLength = 0;
111    Type = Base;
112    for (unsigned I = 0, N = Path.size(); I != N; ++I) {
113      if (Type->isArrayType()) {
114        const ConstantArrayType *CAT =
115          cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
116        Type = CAT->getElementType();
117        ArraySize = CAT->getSize().getZExtValue();
118        MostDerivedLength = I + 1;
119      } else if (const FieldDecl *FD = getAsField(Path[I])) {
120        Type = FD->getType();
121        ArraySize = 0;
122        MostDerivedLength = I + 1;
123      } else {
124        // Path[I] describes a base class.
125        ArraySize = 0;
126      }
127    }
128    return MostDerivedLength;
129  }
130
131  // The order of this enum is important for diagnostics.
132  enum CheckSubobjectKind {
133    CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
134    CSK_This
135  };
136
137  /// A path from a glvalue to a subobject of that glvalue.
138  struct SubobjectDesignator {
139    /// True if the subobject was named in a manner not supported by C++11. Such
140    /// lvalues can still be folded, but they are not core constant expressions
141    /// and we cannot perform lvalue-to-rvalue conversions on them.
142    bool Invalid : 1;
143
144    /// Is this a pointer one past the end of an object?
145    bool IsOnePastTheEnd : 1;
146
147    /// The length of the path to the most-derived object of which this is a
148    /// subobject.
149    unsigned MostDerivedPathLength : 30;
150
151    /// The size of the array of which the most-derived object is an element, or
152    /// 0 if the most-derived object is not an array element.
153    uint64_t MostDerivedArraySize;
154
155    /// The type of the most derived object referred to by this address.
156    QualType MostDerivedType;
157
158    typedef APValue::LValuePathEntry PathEntry;
159
160    /// The entries on the path from the glvalue to the designated subobject.
161    SmallVector<PathEntry, 8> Entries;
162
163    SubobjectDesignator() : Invalid(true) {}
164
165    explicit SubobjectDesignator(QualType T)
166      : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
167        MostDerivedArraySize(0), MostDerivedType(T) {}
168
169    SubobjectDesignator(ASTContext &Ctx, const APValue &V)
170      : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
171        MostDerivedPathLength(0), MostDerivedArraySize(0) {
172      if (!Invalid) {
173        IsOnePastTheEnd = V.isLValueOnePastTheEnd();
174        ArrayRef<PathEntry> VEntries = V.getLValuePath();
175        Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
176        if (V.getLValueBase())
177          MostDerivedPathLength =
178              findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
179                                       V.getLValuePath(), MostDerivedArraySize,
180                                       MostDerivedType);
181      }
182    }
183
184    void setInvalid() {
185      Invalid = true;
186      Entries.clear();
187    }
188
189    /// Determine whether this is a one-past-the-end pointer.
190    bool isOnePastTheEnd() const {
191      if (IsOnePastTheEnd)
192        return true;
193      if (MostDerivedArraySize &&
194          Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
195        return true;
196      return false;
197    }
198
199    /// Check that this refers to a valid subobject.
200    bool isValidSubobject() const {
201      if (Invalid)
202        return false;
203      return !isOnePastTheEnd();
204    }
205    /// Check that this refers to a valid subobject, and if not, produce a
206    /// relevant diagnostic and set the designator as invalid.
207    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
208
209    /// Update this designator to refer to the first element within this array.
210    void addArrayUnchecked(const ConstantArrayType *CAT) {
211      PathEntry Entry;
212      Entry.ArrayIndex = 0;
213      Entries.push_back(Entry);
214
215      // This is a most-derived object.
216      MostDerivedType = CAT->getElementType();
217      MostDerivedArraySize = CAT->getSize().getZExtValue();
218      MostDerivedPathLength = Entries.size();
219    }
220    /// Update this designator to refer to the given base or member of this
221    /// object.
222    void addDeclUnchecked(const Decl *D, bool Virtual = false) {
223      PathEntry Entry;
224      APValue::BaseOrMemberType Value(D, Virtual);
225      Entry.BaseOrMember = Value.getOpaqueValue();
226      Entries.push_back(Entry);
227
228      // If this isn't a base class, it's a new most-derived object.
229      if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
230        MostDerivedType = FD->getType();
231        MostDerivedArraySize = 0;
232        MostDerivedPathLength = Entries.size();
233      }
234    }
235    void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
236    /// Add N to the address of this subobject.
237    void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
238      if (Invalid) return;
239      if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
240        Entries.back().ArrayIndex += N;
241        if (Entries.back().ArrayIndex > MostDerivedArraySize) {
242          diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
243          setInvalid();
244        }
245        return;
246      }
247      // [expr.add]p4: For the purposes of these operators, a pointer to a
248      // nonarray object behaves the same as a pointer to the first element of
249      // an array of length one with the type of the object as its element type.
250      if (IsOnePastTheEnd && N == (uint64_t)-1)
251        IsOnePastTheEnd = false;
252      else if (!IsOnePastTheEnd && N == 1)
253        IsOnePastTheEnd = true;
254      else if (N != 0) {
255        diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
256        setInvalid();
257      }
258    }
259  };
260
261  /// A core constant value. This can be the value of any constant expression,
262  /// or a pointer or reference to a non-static object or function parameter.
263  ///
264  /// For an LValue, the base and offset are stored in the APValue subobject,
265  /// but the other information is stored in the SubobjectDesignator. For all
266  /// other value kinds, the value is stored directly in the APValue subobject.
267  class CCValue : public APValue {
268    typedef llvm::APSInt APSInt;
269    typedef llvm::APFloat APFloat;
270    /// If the value is a reference or pointer into a parameter or temporary,
271    /// this is the corresponding call stack frame.
272    CallStackFrame *CallFrame;
273    /// If the value is a reference or pointer, this is a description of how the
274    /// subobject was specified.
275    SubobjectDesignator Designator;
276  public:
277    struct GlobalValue {};
278
279    CCValue() {}
280    explicit CCValue(const APSInt &I) : APValue(I) {}
281    explicit CCValue(const APFloat &F) : APValue(F) {}
282    CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
283    CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
284    CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
285    CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
286    CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
287            const SubobjectDesignator &D) :
288      APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
289    CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
290      APValue(V), CallFrame(0), Designator(Ctx, V) {}
291    CCValue(const ValueDecl *D, bool IsDerivedMember,
292            ArrayRef<const CXXRecordDecl*> Path) :
293      APValue(D, IsDerivedMember, Path) {}
294    CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
295      APValue(LHSExpr, RHSExpr) {}
296
297    CallStackFrame *getLValueFrame() const {
298      assert(getKind() == LValue);
299      return CallFrame;
300    }
301    SubobjectDesignator &getLValueDesignator() {
302      assert(getKind() == LValue);
303      return Designator;
304    }
305    const SubobjectDesignator &getLValueDesignator() const {
306      return const_cast<CCValue*>(this)->getLValueDesignator();
307    }
308  };
309
310  /// A stack frame in the constexpr call stack.
311  struct CallStackFrame {
312    EvalInfo &Info;
313
314    /// Parent - The caller of this stack frame.
315    CallStackFrame *Caller;
316
317    /// CallLoc - The location of the call expression for this call.
318    SourceLocation CallLoc;
319
320    /// Callee - The function which was called.
321    const FunctionDecl *Callee;
322
323    /// This - The binding for the this pointer in this call, if any.
324    const LValue *This;
325
326    /// ParmBindings - Parameter bindings for this function call, indexed by
327    /// parameters' function scope indices.
328    const CCValue *Arguments;
329
330    typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
331    typedef MapTy::const_iterator temp_iterator;
332    /// Temporaries - Temporary lvalues materialized within this stack frame.
333    MapTy Temporaries;
334
335    CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
336                   const FunctionDecl *Callee, const LValue *This,
337                   const CCValue *Arguments);
338    ~CallStackFrame();
339  };
340
341  /// A partial diagnostic which we might know in advance that we are not going
342  /// to emit.
343  class OptionalDiagnostic {
344    PartialDiagnostic *Diag;
345
346  public:
347    explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
348
349    template<typename T>
350    OptionalDiagnostic &operator<<(const T &v) {
351      if (Diag)
352        *Diag << v;
353      return *this;
354    }
355
356    OptionalDiagnostic &operator<<(const APSInt &I) {
357      if (Diag) {
358        llvm::SmallVector<char, 32> Buffer;
359        I.toString(Buffer);
360        *Diag << StringRef(Buffer.data(), Buffer.size());
361      }
362      return *this;
363    }
364
365    OptionalDiagnostic &operator<<(const APFloat &F) {
366      if (Diag) {
367        llvm::SmallVector<char, 32> Buffer;
368        F.toString(Buffer);
369        *Diag << StringRef(Buffer.data(), Buffer.size());
370      }
371      return *this;
372    }
373  };
374
375  struct EvalInfo {
376    ASTContext &Ctx;
377
378    /// EvalStatus - Contains information about the evaluation.
379    Expr::EvalStatus &EvalStatus;
380
381    /// CurrentCall - The top of the constexpr call stack.
382    CallStackFrame *CurrentCall;
383
384    /// CallStackDepth - The number of calls in the call stack right now.
385    unsigned CallStackDepth;
386
387    typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
388    /// OpaqueValues - Values used as the common expression in a
389    /// BinaryConditionalOperator.
390    MapTy OpaqueValues;
391
392    /// BottomFrame - The frame in which evaluation started. This must be
393    /// initialized after CurrentCall and CallStackDepth.
394    CallStackFrame BottomFrame;
395
396    /// EvaluatingDecl - This is the declaration whose initializer is being
397    /// evaluated, if any.
398    const VarDecl *EvaluatingDecl;
399
400    /// EvaluatingDeclValue - This is the value being constructed for the
401    /// declaration whose initializer is being evaluated, if any.
402    APValue *EvaluatingDeclValue;
403
404    /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
405    /// notes attached to it will also be stored, otherwise they will not be.
406    bool HasActiveDiagnostic;
407
408    /// CheckingPotentialConstantExpression - Are we checking whether the
409    /// expression is a potential constant expression? If so, some diagnostics
410    /// are suppressed.
411    bool CheckingPotentialConstantExpression;
412
413
414    EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
415      : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
416        CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
417        EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
418        CheckingPotentialConstantExpression(false) {}
419
420    const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
421      MapTy::const_iterator i = OpaqueValues.find(e);
422      if (i == OpaqueValues.end()) return 0;
423      return &i->second;
424    }
425
426    void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
427      EvaluatingDecl = VD;
428      EvaluatingDeclValue = &Value;
429    }
430
431    const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
432
433    bool CheckCallLimit(SourceLocation Loc) {
434      // Don't perform any constexpr calls (other than the call we're checking)
435      // when checking a potential constant expression.
436      if (CheckingPotentialConstantExpression && CallStackDepth > 1)
437        return false;
438      if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
439        return true;
440      Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
441        << getLangOpts().ConstexprCallDepth;
442      return false;
443    }
444
445  private:
446    /// Add a diagnostic to the diagnostics list.
447    PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
448      PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
449      EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
450      return EvalStatus.Diag->back().second;
451    }
452
453    /// Add notes containing a call stack to the current point of evaluation.
454    void addCallStack(unsigned Limit);
455
456  public:
457    /// Diagnose that the evaluation cannot be folded.
458    OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
459                              = diag::note_invalid_subexpr_in_const_expr,
460                            unsigned ExtraNotes = 0) {
461      // If we have a prior diagnostic, it will be noting that the expression
462      // isn't a constant expression. This diagnostic is more important.
463      // FIXME: We might want to show both diagnostics to the user.
464      if (EvalStatus.Diag) {
465        unsigned CallStackNotes = CallStackDepth - 1;
466        unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
467        if (Limit)
468          CallStackNotes = std::min(CallStackNotes, Limit + 1);
469        if (CheckingPotentialConstantExpression)
470          CallStackNotes = 0;
471
472        HasActiveDiagnostic = true;
473        EvalStatus.Diag->clear();
474        EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
475        addDiag(Loc, DiagId);
476        if (!CheckingPotentialConstantExpression)
477          addCallStack(Limit);
478        return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
479      }
480      HasActiveDiagnostic = false;
481      return OptionalDiagnostic();
482    }
483
484    /// Diagnose that the evaluation does not produce a C++11 core constant
485    /// expression.
486    OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
487                                 = diag::note_invalid_subexpr_in_const_expr,
488                               unsigned ExtraNotes = 0) {
489      // Don't override a previous diagnostic.
490      if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
491        return OptionalDiagnostic();
492      return Diag(Loc, DiagId, ExtraNotes);
493    }
494
495    /// Add a note to a prior diagnostic.
496    OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
497      if (!HasActiveDiagnostic)
498        return OptionalDiagnostic();
499      return OptionalDiagnostic(&addDiag(Loc, DiagId));
500    }
501
502    /// Add a stack of notes to a prior diagnostic.
503    void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
504      if (HasActiveDiagnostic) {
505        EvalStatus.Diag->insert(EvalStatus.Diag->end(),
506                                Diags.begin(), Diags.end());
507      }
508    }
509
510    /// Should we continue evaluation as much as possible after encountering a
511    /// construct which can't be folded?
512    bool keepEvaluatingAfterFailure() {
513      return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
514    }
515  };
516
517  /// Object used to treat all foldable expressions as constant expressions.
518  struct FoldConstant {
519    bool Enabled;
520
521    explicit FoldConstant(EvalInfo &Info)
522      : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
523                !Info.EvalStatus.HasSideEffects) {
524    }
525    // Treat the value we've computed since this object was created as constant.
526    void Fold(EvalInfo &Info) {
527      if (Enabled && !Info.EvalStatus.Diag->empty() &&
528          !Info.EvalStatus.HasSideEffects)
529        Info.EvalStatus.Diag->clear();
530    }
531  };
532}
533
534bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
535                                         CheckSubobjectKind CSK) {
536  if (Invalid)
537    return false;
538  if (isOnePastTheEnd()) {
539    Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
540      << CSK;
541    setInvalid();
542    return false;
543  }
544  return true;
545}
546
547void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
548                                                    const Expr *E, uint64_t N) {
549  if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
550    Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
551      << static_cast<int>(N) << /*array*/ 0
552      << static_cast<unsigned>(MostDerivedArraySize);
553  else
554    Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
555      << static_cast<int>(N) << /*non-array*/ 1;
556  setInvalid();
557}
558
559CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
560                               const FunctionDecl *Callee, const LValue *This,
561                               const CCValue *Arguments)
562    : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
563      This(This), Arguments(Arguments) {
564  Info.CurrentCall = this;
565  ++Info.CallStackDepth;
566}
567
568CallStackFrame::~CallStackFrame() {
569  assert(Info.CurrentCall == this && "calls retired out of order");
570  --Info.CallStackDepth;
571  Info.CurrentCall = Caller;
572}
573
574/// Produce a string describing the given constexpr call.
575static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
576  unsigned ArgIndex = 0;
577  bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
578                      !isa<CXXConstructorDecl>(Frame->Callee) &&
579                      cast<CXXMethodDecl>(Frame->Callee)->isInstance();
580
581  if (!IsMemberCall)
582    Out << *Frame->Callee << '(';
583
584  for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
585       E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
586    if (ArgIndex > (unsigned)IsMemberCall)
587      Out << ", ";
588
589    const ParmVarDecl *Param = *I;
590    const CCValue &Arg = Frame->Arguments[ArgIndex];
591    if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
592      Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
593    else {
594      // Deliberately slice off the frame to form an APValue we can print.
595      APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
596                    Arg.getLValueDesignator().Entries,
597                    Arg.getLValueDesignator().IsOnePastTheEnd);
598      Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
599    }
600
601    if (ArgIndex == 0 && IsMemberCall)
602      Out << "->" << *Frame->Callee << '(';
603  }
604
605  Out << ')';
606}
607
608void EvalInfo::addCallStack(unsigned Limit) {
609  // Determine which calls to skip, if any.
610  unsigned ActiveCalls = CallStackDepth - 1;
611  unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
612  if (Limit && Limit < ActiveCalls) {
613    SkipStart = Limit / 2 + Limit % 2;
614    SkipEnd = ActiveCalls - Limit / 2;
615  }
616
617  // Walk the call stack and add the diagnostics.
618  unsigned CallIdx = 0;
619  for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
620       Frame = Frame->Caller, ++CallIdx) {
621    // Skip this call?
622    if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
623      if (CallIdx == SkipStart) {
624        // Note that we're skipping calls.
625        addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
626          << unsigned(ActiveCalls - Limit);
627      }
628      continue;
629    }
630
631    llvm::SmallVector<char, 128> Buffer;
632    llvm::raw_svector_ostream Out(Buffer);
633    describeCall(Frame, Out);
634    addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
635  }
636}
637
638namespace {
639  struct ComplexValue {
640  private:
641    bool IsInt;
642
643  public:
644    APSInt IntReal, IntImag;
645    APFloat FloatReal, FloatImag;
646
647    ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
648
649    void makeComplexFloat() { IsInt = false; }
650    bool isComplexFloat() const { return !IsInt; }
651    APFloat &getComplexFloatReal() { return FloatReal; }
652    APFloat &getComplexFloatImag() { return FloatImag; }
653
654    void makeComplexInt() { IsInt = true; }
655    bool isComplexInt() const { return IsInt; }
656    APSInt &getComplexIntReal() { return IntReal; }
657    APSInt &getComplexIntImag() { return IntImag; }
658
659    void moveInto(CCValue &v) const {
660      if (isComplexFloat())
661        v = CCValue(FloatReal, FloatImag);
662      else
663        v = CCValue(IntReal, IntImag);
664    }
665    void setFrom(const CCValue &v) {
666      assert(v.isComplexFloat() || v.isComplexInt());
667      if (v.isComplexFloat()) {
668        makeComplexFloat();
669        FloatReal = v.getComplexFloatReal();
670        FloatImag = v.getComplexFloatImag();
671      } else {
672        makeComplexInt();
673        IntReal = v.getComplexIntReal();
674        IntImag = v.getComplexIntImag();
675      }
676    }
677  };
678
679  struct LValue {
680    APValue::LValueBase Base;
681    CharUnits Offset;
682    CallStackFrame *Frame;
683    SubobjectDesignator Designator;
684
685    const APValue::LValueBase getLValueBase() const { return Base; }
686    CharUnits &getLValueOffset() { return Offset; }
687    const CharUnits &getLValueOffset() const { return Offset; }
688    CallStackFrame *getLValueFrame() const { return Frame; }
689    SubobjectDesignator &getLValueDesignator() { return Designator; }
690    const SubobjectDesignator &getLValueDesignator() const { return Designator;}
691
692    void moveInto(CCValue &V) const {
693      V = CCValue(Base, Offset, Frame, Designator);
694    }
695    void setFrom(const CCValue &V) {
696      assert(V.isLValue());
697      Base = V.getLValueBase();
698      Offset = V.getLValueOffset();
699      Frame = V.getLValueFrame();
700      Designator = V.getLValueDesignator();
701    }
702
703    void set(APValue::LValueBase B, CallStackFrame *F = 0) {
704      Base = B;
705      Offset = CharUnits::Zero();
706      Frame = F;
707      Designator = SubobjectDesignator(getType(B));
708    }
709
710    // Check that this LValue is not based on a null pointer. If it is, produce
711    // a diagnostic and mark the designator as invalid.
712    bool checkNullPointer(EvalInfo &Info, const Expr *E,
713                          CheckSubobjectKind CSK) {
714      if (Designator.Invalid)
715        return false;
716      if (!Base) {
717        Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
718          << CSK;
719        Designator.setInvalid();
720        return false;
721      }
722      return true;
723    }
724
725    // Check this LValue refers to an object. If not, set the designator to be
726    // invalid and emit a diagnostic.
727    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
728      return checkNullPointer(Info, E, CSK) &&
729             Designator.checkSubobject(Info, E, CSK);
730    }
731
732    void addDecl(EvalInfo &Info, const Expr *E,
733                 const Decl *D, bool Virtual = false) {
734      checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
735      Designator.addDeclUnchecked(D, Virtual);
736    }
737    void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
738      checkSubobject(Info, E, CSK_ArrayToPointer);
739      Designator.addArrayUnchecked(CAT);
740    }
741    void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
742      if (!checkNullPointer(Info, E, CSK_ArrayIndex))
743        return;
744      Designator.adjustIndex(Info, E, N);
745    }
746  };
747
748  struct MemberPtr {
749    MemberPtr() {}
750    explicit MemberPtr(const ValueDecl *Decl) :
751      DeclAndIsDerivedMember(Decl, false), Path() {}
752
753    /// The member or (direct or indirect) field referred to by this member
754    /// pointer, or 0 if this is a null member pointer.
755    const ValueDecl *getDecl() const {
756      return DeclAndIsDerivedMember.getPointer();
757    }
758    /// Is this actually a member of some type derived from the relevant class?
759    bool isDerivedMember() const {
760      return DeclAndIsDerivedMember.getInt();
761    }
762    /// Get the class which the declaration actually lives in.
763    const CXXRecordDecl *getContainingRecord() const {
764      return cast<CXXRecordDecl>(
765          DeclAndIsDerivedMember.getPointer()->getDeclContext());
766    }
767
768    void moveInto(CCValue &V) const {
769      V = CCValue(getDecl(), isDerivedMember(), Path);
770    }
771    void setFrom(const CCValue &V) {
772      assert(V.isMemberPointer());
773      DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
774      DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
775      Path.clear();
776      ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
777      Path.insert(Path.end(), P.begin(), P.end());
778    }
779
780    /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
781    /// whether the member is a member of some class derived from the class type
782    /// of the member pointer.
783    llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
784    /// Path - The path of base/derived classes from the member declaration's
785    /// class (exclusive) to the class type of the member pointer (inclusive).
786    SmallVector<const CXXRecordDecl*, 4> Path;
787
788    /// Perform a cast towards the class of the Decl (either up or down the
789    /// hierarchy).
790    bool castBack(const CXXRecordDecl *Class) {
791      assert(!Path.empty());
792      const CXXRecordDecl *Expected;
793      if (Path.size() >= 2)
794        Expected = Path[Path.size() - 2];
795      else
796        Expected = getContainingRecord();
797      if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
798        // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
799        // if B does not contain the original member and is not a base or
800        // derived class of the class containing the original member, the result
801        // of the cast is undefined.
802        // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
803        // (D::*). We consider that to be a language defect.
804        return false;
805      }
806      Path.pop_back();
807      return true;
808    }
809    /// Perform a base-to-derived member pointer cast.
810    bool castToDerived(const CXXRecordDecl *Derived) {
811      if (!getDecl())
812        return true;
813      if (!isDerivedMember()) {
814        Path.push_back(Derived);
815        return true;
816      }
817      if (!castBack(Derived))
818        return false;
819      if (Path.empty())
820        DeclAndIsDerivedMember.setInt(false);
821      return true;
822    }
823    /// Perform a derived-to-base member pointer cast.
824    bool castToBase(const CXXRecordDecl *Base) {
825      if (!getDecl())
826        return true;
827      if (Path.empty())
828        DeclAndIsDerivedMember.setInt(true);
829      if (isDerivedMember()) {
830        Path.push_back(Base);
831        return true;
832      }
833      return castBack(Base);
834    }
835  };
836
837  /// Compare two member pointers, which are assumed to be of the same type.
838  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
839    if (!LHS.getDecl() || !RHS.getDecl())
840      return !LHS.getDecl() && !RHS.getDecl();
841    if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
842      return false;
843    return LHS.Path == RHS.Path;
844  }
845
846  /// Kinds of constant expression checking, for diagnostics.
847  enum CheckConstantExpressionKind {
848    CCEK_Constant,    ///< A normal constant.
849    CCEK_ReturnValue, ///< A constexpr function return value.
850    CCEK_MemberInit   ///< A constexpr constructor mem-initializer.
851  };
852}
853
854static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
855static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
856                                       const LValue &This, const Expr *E,
857                                       CheckConstantExpressionKind CCEK
858                                        = CCEK_Constant);
859static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
860static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
861static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
862                                  EvalInfo &Info);
863static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
864static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
865static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
866                                    EvalInfo &Info);
867static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
868static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
869
870//===----------------------------------------------------------------------===//
871// Misc utilities
872//===----------------------------------------------------------------------===//
873
874/// Should this call expression be treated as a string literal?
875static bool IsStringLiteralCall(const CallExpr *E) {
876  unsigned Builtin = E->isBuiltinCall();
877  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
878          Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
879}
880
881static bool IsGlobalLValue(APValue::LValueBase B) {
882  // C++11 [expr.const]p3 An address constant expression is a prvalue core
883  // constant expression of pointer type that evaluates to...
884
885  // ... a null pointer value, or a prvalue core constant expression of type
886  // std::nullptr_t.
887  if (!B) return true;
888
889  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
890    // ... the address of an object with static storage duration,
891    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
892      return VD->hasGlobalStorage();
893    // ... the address of a function,
894    return isa<FunctionDecl>(D);
895  }
896
897  const Expr *E = B.get<const Expr*>();
898  switch (E->getStmtClass()) {
899  default:
900    return false;
901  case Expr::CompoundLiteralExprClass:
902    return cast<CompoundLiteralExpr>(E)->isFileScope();
903  // A string literal has static storage duration.
904  case Expr::StringLiteralClass:
905  case Expr::PredefinedExprClass:
906  case Expr::ObjCStringLiteralClass:
907  case Expr::ObjCEncodeExprClass:
908  case Expr::CXXTypeidExprClass:
909    return true;
910  case Expr::CallExprClass:
911    return IsStringLiteralCall(cast<CallExpr>(E));
912  // For GCC compatibility, &&label has static storage duration.
913  case Expr::AddrLabelExprClass:
914    return true;
915  // A Block literal expression may be used as the initialization value for
916  // Block variables at global or local static scope.
917  case Expr::BlockExprClass:
918    return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
919  case Expr::ImplicitValueInitExprClass:
920    // FIXME:
921    // We can never form an lvalue with an implicit value initialization as its
922    // base through expression evaluation, so these only appear in one case: the
923    // implicit variable declaration we invent when checking whether a constexpr
924    // constructor can produce a constant expression. We must assume that such
925    // an expression might be a global lvalue.
926    return true;
927  }
928}
929
930/// Check that this reference or pointer core constant expression is a valid
931/// value for an address or reference constant expression. Type T should be
932/// either LValue or CCValue. Return true if we can fold this expression,
933/// whether or not it's a constant expression.
934template<typename T>
935static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
936                                          const T &LVal, APValue &Value,
937                                          CheckConstantExpressionKind CCEK) {
938  APValue::LValueBase Base = LVal.getLValueBase();
939  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
940
941  if (!IsGlobalLValue(Base)) {
942    if (Info.getLangOpts().CPlusPlus0x) {
943      const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
944      Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
945        << E->isGLValue() << !Designator.Entries.empty()
946        << !!VD << CCEK << VD;
947      if (VD)
948        Info.Note(VD->getLocation(), diag::note_declared_at);
949      else
950        Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
951                  diag::note_constexpr_temporary_here);
952    } else {
953      Info.Diag(E->getExprLoc());
954    }
955    // Don't allow references to temporaries to escape.
956    return false;
957  }
958
959  bool IsReferenceType = E->isGLValue();
960
961  if (Designator.Invalid) {
962    // This is not a core constant expression. An appropriate diagnostic will
963    // have already been produced.
964    Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
965                    APValue::NoLValuePath());
966    return true;
967  }
968
969  Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
970                  Designator.Entries, Designator.IsOnePastTheEnd);
971
972  // Allow address constant expressions to be past-the-end pointers. This is
973  // an extension: the standard requires them to point to an object.
974  if (!IsReferenceType)
975    return true;
976
977  // A reference constant expression must refer to an object.
978  if (!Base) {
979    // FIXME: diagnostic
980    Info.CCEDiag(E->getExprLoc());
981    return true;
982  }
983
984  // Does this refer one past the end of some object?
985  if (Designator.isOnePastTheEnd()) {
986    const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
987    Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
988      << !Designator.Entries.empty() << !!VD << VD;
989    if (VD)
990      Info.Note(VD->getLocation(), diag::note_declared_at);
991    else
992      Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
993                diag::note_constexpr_temporary_here);
994  }
995
996  return true;
997}
998
999/// Check that this core constant expression is of literal type, and if not,
1000/// produce an appropriate diagnostic.
1001static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1002  if (!E->isRValue() || E->getType()->isLiteralType())
1003    return true;
1004
1005  // Prvalue constant expressions must be of literal types.
1006  if (Info.getLangOpts().CPlusPlus0x)
1007    Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1008      << E->getType();
1009  else
1010    Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1011  return false;
1012}
1013
1014/// Check that this core constant expression value is a valid value for a
1015/// constant expression, and if it is, produce the corresponding constant value.
1016/// If not, report an appropriate diagnostic. Does not check that the expression
1017/// is of literal type.
1018static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
1019                                    const CCValue &CCValue, APValue &Value,
1020                                    CheckConstantExpressionKind CCEK
1021                                      = CCEK_Constant) {
1022  if (!CCValue.isLValue()) {
1023    Value = CCValue;
1024    return true;
1025  }
1026  return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
1027}
1028
1029const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1030  return LVal.Base.dyn_cast<const ValueDecl*>();
1031}
1032
1033static bool IsLiteralLValue(const LValue &Value) {
1034  return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
1035}
1036
1037static bool IsWeakLValue(const LValue &Value) {
1038  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1039  return Decl && Decl->isWeak();
1040}
1041
1042static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
1043  // A null base expression indicates a null pointer.  These are always
1044  // evaluatable, and they are false unless the offset is zero.
1045  if (!Value.getLValueBase()) {
1046    Result = !Value.getLValueOffset().isZero();
1047    return true;
1048  }
1049
1050  // We have a non-null base.  These are generally known to be true, but if it's
1051  // a weak declaration it can be null at runtime.
1052  Result = true;
1053  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1054  return !Decl || !Decl->isWeak();
1055}
1056
1057static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
1058  switch (Val.getKind()) {
1059  case APValue::Uninitialized:
1060    return false;
1061  case APValue::Int:
1062    Result = Val.getInt().getBoolValue();
1063    return true;
1064  case APValue::Float:
1065    Result = !Val.getFloat().isZero();
1066    return true;
1067  case APValue::ComplexInt:
1068    Result = Val.getComplexIntReal().getBoolValue() ||
1069             Val.getComplexIntImag().getBoolValue();
1070    return true;
1071  case APValue::ComplexFloat:
1072    Result = !Val.getComplexFloatReal().isZero() ||
1073             !Val.getComplexFloatImag().isZero();
1074    return true;
1075  case APValue::LValue:
1076    return EvalPointerValueAsBool(Val, Result);
1077  case APValue::MemberPointer:
1078    Result = Val.getMemberPointerDecl();
1079    return true;
1080  case APValue::Vector:
1081  case APValue::Array:
1082  case APValue::Struct:
1083  case APValue::Union:
1084  case APValue::AddrLabelDiff:
1085    return false;
1086  }
1087
1088  llvm_unreachable("unknown APValue kind");
1089}
1090
1091static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1092                                       EvalInfo &Info) {
1093  assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1094  CCValue Val;
1095  if (!Evaluate(Val, Info, E))
1096    return false;
1097  return HandleConversionToBool(Val, Result);
1098}
1099
1100template<typename T>
1101static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1102                           const T &SrcValue, QualType DestType) {
1103  Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1104    << SrcValue << DestType;
1105  return false;
1106}
1107
1108static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1109                                 QualType SrcType, const APFloat &Value,
1110                                 QualType DestType, APSInt &Result) {
1111  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1112  // Determine whether we are converting to unsigned or signed.
1113  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1114
1115  Result = APSInt(DestWidth, !DestSigned);
1116  bool ignored;
1117  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1118      & APFloat::opInvalidOp)
1119    return HandleOverflow(Info, E, Value, DestType);
1120  return true;
1121}
1122
1123static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1124                                   QualType SrcType, QualType DestType,
1125                                   APFloat &Result) {
1126  APFloat Value = Result;
1127  bool ignored;
1128  if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1129                     APFloat::rmNearestTiesToEven, &ignored)
1130      & APFloat::opOverflow)
1131    return HandleOverflow(Info, E, Value, DestType);
1132  return true;
1133}
1134
1135static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1136                                 QualType DestType, QualType SrcType,
1137                                 APSInt &Value) {
1138  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1139  APSInt Result = Value;
1140  // Figure out if this is a truncate, extend or noop cast.
1141  // If the input is signed, do a sign extend, noop, or truncate.
1142  Result = Result.extOrTrunc(DestWidth);
1143  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1144  return Result;
1145}
1146
1147static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1148                                 QualType SrcType, const APSInt &Value,
1149                                 QualType DestType, APFloat &Result) {
1150  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1151  if (Result.convertFromAPInt(Value, Value.isSigned(),
1152                              APFloat::rmNearestTiesToEven)
1153      & APFloat::opOverflow)
1154    return HandleOverflow(Info, E, Value, DestType);
1155  return true;
1156}
1157
1158static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1159                                  llvm::APInt &Res) {
1160  CCValue SVal;
1161  if (!Evaluate(SVal, Info, E))
1162    return false;
1163  if (SVal.isInt()) {
1164    Res = SVal.getInt();
1165    return true;
1166  }
1167  if (SVal.isFloat()) {
1168    Res = SVal.getFloat().bitcastToAPInt();
1169    return true;
1170  }
1171  if (SVal.isVector()) {
1172    QualType VecTy = E->getType();
1173    unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1174    QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1175    unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1176    bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1177    Res = llvm::APInt::getNullValue(VecSize);
1178    for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1179      APValue &Elt = SVal.getVectorElt(i);
1180      llvm::APInt EltAsInt;
1181      if (Elt.isInt()) {
1182        EltAsInt = Elt.getInt();
1183      } else if (Elt.isFloat()) {
1184        EltAsInt = Elt.getFloat().bitcastToAPInt();
1185      } else {
1186        // Don't try to handle vectors of anything other than int or float
1187        // (not sure if it's possible to hit this case).
1188        Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1189        return false;
1190      }
1191      unsigned BaseEltSize = EltAsInt.getBitWidth();
1192      if (BigEndian)
1193        Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1194      else
1195        Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1196    }
1197    return true;
1198  }
1199  // Give up if the input isn't an int, float, or vector.  For example, we
1200  // reject "(v4i16)(intptr_t)&a".
1201  Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1202  return false;
1203}
1204
1205/// Cast an lvalue referring to a base subobject to a derived class, by
1206/// truncating the lvalue's path to the given length.
1207static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1208                               const RecordDecl *TruncatedType,
1209                               unsigned TruncatedElements) {
1210  SubobjectDesignator &D = Result.Designator;
1211
1212  // Check we actually point to a derived class object.
1213  if (TruncatedElements == D.Entries.size())
1214    return true;
1215  assert(TruncatedElements >= D.MostDerivedPathLength &&
1216         "not casting to a derived class");
1217  if (!Result.checkSubobject(Info, E, CSK_Derived))
1218    return false;
1219
1220  // Truncate the path to the subobject, and remove any derived-to-base offsets.
1221  const RecordDecl *RD = TruncatedType;
1222  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1223    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1224    const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1225    if (isVirtualBaseClass(D.Entries[I]))
1226      Result.Offset -= Layout.getVBaseClassOffset(Base);
1227    else
1228      Result.Offset -= Layout.getBaseClassOffset(Base);
1229    RD = Base;
1230  }
1231  D.Entries.resize(TruncatedElements);
1232  return true;
1233}
1234
1235static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1236                                   const CXXRecordDecl *Derived,
1237                                   const CXXRecordDecl *Base,
1238                                   const ASTRecordLayout *RL = 0) {
1239  if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1240  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1241  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1242}
1243
1244static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1245                             const CXXRecordDecl *DerivedDecl,
1246                             const CXXBaseSpecifier *Base) {
1247  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1248
1249  if (!Base->isVirtual()) {
1250    HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1251    return true;
1252  }
1253
1254  SubobjectDesignator &D = Obj.Designator;
1255  if (D.Invalid)
1256    return false;
1257
1258  // Extract most-derived object and corresponding type.
1259  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1260  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1261    return false;
1262
1263  // Find the virtual base class.
1264  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1265  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1266  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1267  return true;
1268}
1269
1270/// Update LVal to refer to the given field, which must be a member of the type
1271/// currently described by LVal.
1272static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1273                               const FieldDecl *FD,
1274                               const ASTRecordLayout *RL = 0) {
1275  if (!RL)
1276    RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1277
1278  unsigned I = FD->getFieldIndex();
1279  LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1280  LVal.addDecl(Info, E, FD);
1281}
1282
1283/// Update LVal to refer to the given indirect field.
1284static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1285                                       LValue &LVal,
1286                                       const IndirectFieldDecl *IFD) {
1287  for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1288                                         CE = IFD->chain_end(); C != CE; ++C)
1289    HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1290}
1291
1292/// Get the size of the given type in char units.
1293static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1294  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1295  // extension.
1296  if (Type->isVoidType() || Type->isFunctionType()) {
1297    Size = CharUnits::One();
1298    return true;
1299  }
1300
1301  if (!Type->isConstantSizeType()) {
1302    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1303    // FIXME: Diagnostic.
1304    return false;
1305  }
1306
1307  Size = Info.Ctx.getTypeSizeInChars(Type);
1308  return true;
1309}
1310
1311/// Update a pointer value to model pointer arithmetic.
1312/// \param Info - Information about the ongoing evaluation.
1313/// \param E - The expression being evaluated, for diagnostic purposes.
1314/// \param LVal - The pointer value to be updated.
1315/// \param EltTy - The pointee type represented by LVal.
1316/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1317static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1318                                        LValue &LVal, QualType EltTy,
1319                                        int64_t Adjustment) {
1320  CharUnits SizeOfPointee;
1321  if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1322    return false;
1323
1324  // Compute the new offset in the appropriate width.
1325  LVal.Offset += Adjustment * SizeOfPointee;
1326  LVal.adjustIndex(Info, E, Adjustment);
1327  return true;
1328}
1329
1330/// Try to evaluate the initializer for a variable declaration.
1331static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1332                                const VarDecl *VD,
1333                                CallStackFrame *Frame, CCValue &Result) {
1334  // If this is a parameter to an active constexpr function call, perform
1335  // argument substitution.
1336  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1337    // Assume arguments of a potential constant expression are unknown
1338    // constant expressions.
1339    if (Info.CheckingPotentialConstantExpression)
1340      return false;
1341    if (!Frame || !Frame->Arguments) {
1342      Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1343      return false;
1344    }
1345    Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1346    return true;
1347  }
1348
1349  // Dig out the initializer, and use the declaration which it's attached to.
1350  const Expr *Init = VD->getAnyInitializer(VD);
1351  if (!Init || Init->isValueDependent()) {
1352    // If we're checking a potential constant expression, the variable could be
1353    // initialized later.
1354    if (!Info.CheckingPotentialConstantExpression)
1355      Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1356    return false;
1357  }
1358
1359  // If we're currently evaluating the initializer of this declaration, use that
1360  // in-flight value.
1361  if (Info.EvaluatingDecl == VD) {
1362    Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1363                     CCValue::GlobalValue());
1364    return !Result.isUninit();
1365  }
1366
1367  // Never evaluate the initializer of a weak variable. We can't be sure that
1368  // this is the definition which will be used.
1369  if (VD->isWeak()) {
1370    Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1371    return false;
1372  }
1373
1374  // Check that we can fold the initializer. In C++, we will have already done
1375  // this in the cases where it matters for conformance.
1376  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1377  if (!VD->evaluateValue(Notes)) {
1378    Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1379              Notes.size() + 1) << VD;
1380    Info.Note(VD->getLocation(), diag::note_declared_at);
1381    Info.addNotes(Notes);
1382    return false;
1383  } else if (!VD->checkInitIsICE()) {
1384    Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1385                 Notes.size() + 1) << VD;
1386    Info.Note(VD->getLocation(), diag::note_declared_at);
1387    Info.addNotes(Notes);
1388  }
1389
1390  Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
1391  return true;
1392}
1393
1394static bool IsConstNonVolatile(QualType T) {
1395  Qualifiers Quals = T.getQualifiers();
1396  return Quals.hasConst() && !Quals.hasVolatile();
1397}
1398
1399/// Get the base index of the given base class within an APValue representing
1400/// the given derived class.
1401static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1402                             const CXXRecordDecl *Base) {
1403  Base = Base->getCanonicalDecl();
1404  unsigned Index = 0;
1405  for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1406         E = Derived->bases_end(); I != E; ++I, ++Index) {
1407    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1408      return Index;
1409  }
1410
1411  llvm_unreachable("base class missing from derived class's bases list");
1412}
1413
1414/// Extract the designated sub-object of an rvalue.
1415static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1416                             CCValue &Obj, QualType ObjType,
1417                             const SubobjectDesignator &Sub, QualType SubType) {
1418  if (Sub.Invalid)
1419    // A diagnostic will have already been produced.
1420    return false;
1421  if (Sub.isOnePastTheEnd()) {
1422    Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1423                (unsigned)diag::note_constexpr_read_past_end :
1424                (unsigned)diag::note_invalid_subexpr_in_const_expr);
1425    return false;
1426  }
1427  if (Sub.Entries.empty())
1428    return true;
1429  if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1430    // This object might be initialized later.
1431    return false;
1432
1433  assert(!Obj.isLValue() && "extracting subobject of lvalue");
1434  const APValue *O = &Obj;
1435  // Walk the designator's path to find the subobject.
1436  for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
1437    if (ObjType->isArrayType()) {
1438      // Next subobject is an array element.
1439      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
1440      assert(CAT && "vla in literal type?");
1441      uint64_t Index = Sub.Entries[I].ArrayIndex;
1442      if (CAT->getSize().ule(Index)) {
1443        // Note, it should not be possible to form a pointer with a valid
1444        // designator which points more than one past the end of the array.
1445        Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1446                    (unsigned)diag::note_constexpr_read_past_end :
1447                    (unsigned)diag::note_invalid_subexpr_in_const_expr);
1448        return false;
1449      }
1450      if (O->getArrayInitializedElts() > Index)
1451        O = &O->getArrayInitializedElt(Index);
1452      else
1453        O = &O->getArrayFiller();
1454      ObjType = CAT->getElementType();
1455    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1456      if (Field->isMutable()) {
1457        Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1458          << Field;
1459        Info.Note(Field->getLocation(), diag::note_declared_at);
1460        return false;
1461      }
1462
1463      // Next subobject is a class, struct or union field.
1464      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1465      if (RD->isUnion()) {
1466        const FieldDecl *UnionField = O->getUnionField();
1467        if (!UnionField ||
1468            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
1469          Info.Diag(E->getExprLoc(),
1470                    diag::note_constexpr_read_inactive_union_member)
1471            << Field << !UnionField << UnionField;
1472          return false;
1473        }
1474        O = &O->getUnionValue();
1475      } else
1476        O = &O->getStructField(Field->getFieldIndex());
1477      ObjType = Field->getType();
1478
1479      if (ObjType.isVolatileQualified()) {
1480        if (Info.getLangOpts().CPlusPlus) {
1481          // FIXME: Include a description of the path to the volatile subobject.
1482          Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1483            << 2 << Field;
1484          Info.Note(Field->getLocation(), diag::note_declared_at);
1485        } else {
1486          Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1487        }
1488        return false;
1489      }
1490    } else {
1491      // Next subobject is a base class.
1492      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1493      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1494      O = &O->getStructBase(getBaseIndex(Derived, Base));
1495      ObjType = Info.Ctx.getRecordType(Base);
1496    }
1497
1498    if (O->isUninit()) {
1499      if (!Info.CheckingPotentialConstantExpression)
1500        Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
1501      return false;
1502    }
1503  }
1504
1505  Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
1506  return true;
1507}
1508
1509/// Find the position where two subobject designators diverge, or equivalently
1510/// the length of the common initial subsequence.
1511static unsigned FindDesignatorMismatch(QualType ObjType,
1512                                       const SubobjectDesignator &A,
1513                                       const SubobjectDesignator &B,
1514                                       bool &WasArrayIndex) {
1515  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1516  for (/**/; I != N; ++I) {
1517    if (!ObjType.isNull() && ObjType->isArrayType()) {
1518      // Next subobject is an array element.
1519      if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1520        WasArrayIndex = true;
1521        return I;
1522      }
1523      ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1524    } else {
1525      if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1526        WasArrayIndex = false;
1527        return I;
1528      }
1529      if (const FieldDecl *FD = getAsField(A.Entries[I]))
1530        // Next subobject is a field.
1531        ObjType = FD->getType();
1532      else
1533        // Next subobject is a base class.
1534        ObjType = QualType();
1535    }
1536  }
1537  WasArrayIndex = false;
1538  return I;
1539}
1540
1541/// Determine whether the given subobject designators refer to elements of the
1542/// same array object.
1543static bool AreElementsOfSameArray(QualType ObjType,
1544                                   const SubobjectDesignator &A,
1545                                   const SubobjectDesignator &B) {
1546  if (A.Entries.size() != B.Entries.size())
1547    return false;
1548
1549  bool IsArray = A.MostDerivedArraySize != 0;
1550  if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1551    // A is a subobject of the array element.
1552    return false;
1553
1554  // If A (and B) designates an array element, the last entry will be the array
1555  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1556  // of length 1' case, and the entire path must match.
1557  bool WasArrayIndex;
1558  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1559  return CommonLength >= A.Entries.size() - IsArray;
1560}
1561
1562/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1563/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1564/// for looking up the glvalue referred to by an entity of reference type.
1565///
1566/// \param Info - Information about the ongoing evaluation.
1567/// \param Conv - The expression for which we are performing the conversion.
1568///               Used for diagnostics.
1569/// \param Type - The type we expect this conversion to produce, before
1570///               stripping cv-qualifiers in the case of a non-clas type.
1571/// \param LVal - The glvalue on which we are attempting to perform this action.
1572/// \param RVal - The produced value will be placed here.
1573static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1574                                           QualType Type,
1575                                           const LValue &LVal, CCValue &RVal) {
1576  // In C, an lvalue-to-rvalue conversion is never a constant expression.
1577  if (!Info.getLangOpts().CPlusPlus)
1578    Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1579
1580  if (LVal.Designator.Invalid)
1581    // A diagnostic will have already been produced.
1582    return false;
1583
1584  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
1585  CallStackFrame *Frame = LVal.Frame;
1586  SourceLocation Loc = Conv->getExprLoc();
1587
1588  if (!LVal.Base) {
1589    // FIXME: Indirection through a null pointer deserves a specific diagnostic.
1590    Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1591    return false;
1592  }
1593
1594  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1595  // is not a constant expression (even if the object is non-volatile). We also
1596  // apply this rule to C++98, in order to conform to the expected 'volatile'
1597  // semantics.
1598  if (Type.isVolatileQualified()) {
1599    if (Info.getLangOpts().CPlusPlus)
1600      Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1601    else
1602      Info.Diag(Loc);
1603    return false;
1604  }
1605
1606  if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1607    // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1608    // In C++11, constexpr, non-volatile variables initialized with constant
1609    // expressions are constant expressions too. Inside constexpr functions,
1610    // parameters are constant expressions even if they're non-const.
1611    // In C, such things can also be folded, although they are not ICEs.
1612    const VarDecl *VD = dyn_cast<VarDecl>(D);
1613    if (const VarDecl *VDef = VD->getDefinition())
1614      VD = VDef;
1615    if (!VD || VD->isInvalidDecl()) {
1616      Info.Diag(Loc);
1617      return false;
1618    }
1619
1620    // DR1313: If the object is volatile-qualified but the glvalue was not,
1621    // behavior is undefined so the result is not a constant expression.
1622    QualType VT = VD->getType();
1623    if (VT.isVolatileQualified()) {
1624      if (Info.getLangOpts().CPlusPlus) {
1625        Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1626        Info.Note(VD->getLocation(), diag::note_declared_at);
1627      } else {
1628        Info.Diag(Loc);
1629      }
1630      return false;
1631    }
1632
1633    if (!isa<ParmVarDecl>(VD)) {
1634      if (VD->isConstexpr()) {
1635        // OK, we can read this variable.
1636      } else if (VT->isIntegralOrEnumerationType()) {
1637        if (!VT.isConstQualified()) {
1638          if (Info.getLangOpts().CPlusPlus) {
1639            Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1640            Info.Note(VD->getLocation(), diag::note_declared_at);
1641          } else {
1642            Info.Diag(Loc);
1643          }
1644          return false;
1645        }
1646      } else if (VT->isFloatingType() && VT.isConstQualified()) {
1647        // We support folding of const floating-point types, in order to make
1648        // static const data members of such types (supported as an extension)
1649        // more useful.
1650        if (Info.getLangOpts().CPlusPlus0x) {
1651          Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1652          Info.Note(VD->getLocation(), diag::note_declared_at);
1653        } else {
1654          Info.CCEDiag(Loc);
1655        }
1656      } else {
1657        // FIXME: Allow folding of values of any literal type in all languages.
1658        if (Info.getLangOpts().CPlusPlus0x) {
1659          Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1660          Info.Note(VD->getLocation(), diag::note_declared_at);
1661        } else {
1662          Info.Diag(Loc);
1663        }
1664        return false;
1665      }
1666    }
1667
1668    if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
1669      return false;
1670
1671    if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
1672      return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
1673
1674    // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1675    // conversion. This happens when the declaration and the lvalue should be
1676    // considered synonymous, for instance when initializing an array of char
1677    // from a string literal. Continue as if the initializer lvalue was the
1678    // value we were originally given.
1679    assert(RVal.getLValueOffset().isZero() &&
1680           "offset for lvalue init of non-reference");
1681    Base = RVal.getLValueBase().get<const Expr*>();
1682    Frame = RVal.getLValueFrame();
1683  }
1684
1685  // Volatile temporary objects cannot be read in constant expressions.
1686  if (Base->getType().isVolatileQualified()) {
1687    if (Info.getLangOpts().CPlusPlus) {
1688      Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1689      Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1690    } else {
1691      Info.Diag(Loc);
1692    }
1693    return false;
1694  }
1695
1696  // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1697  if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1698    const SubobjectDesignator &Designator = LVal.Designator;
1699    if (Designator.Invalid || Designator.Entries.size() != 1) {
1700      Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1701      return false;
1702    }
1703
1704    assert(Type->isIntegerType() && "string element not integer type");
1705    uint64_t Index = Designator.Entries[0].ArrayIndex;
1706    const ConstantArrayType *CAT =
1707        Info.Ctx.getAsConstantArrayType(S->getType());
1708    if (Index >= CAT->getSize().getZExtValue()) {
1709      // Note, it should not be possible to form a pointer which points more
1710      // than one past the end of the array without producing a prior const expr
1711      // diagnostic.
1712      Info.Diag(Loc, diag::note_constexpr_read_past_end);
1713      return false;
1714    }
1715    APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1716                 Type->isUnsignedIntegerType());
1717    if (Index < S->getLength())
1718      Value = S->getCodeUnit(Index);
1719    RVal = CCValue(Value);
1720    return true;
1721  }
1722
1723  if (Frame) {
1724    // If this is a temporary expression with a nontrivial initializer, grab the
1725    // value from the relevant stack frame.
1726    RVal = Frame->Temporaries[Base];
1727  } else if (const CompoundLiteralExpr *CLE
1728             = dyn_cast<CompoundLiteralExpr>(Base)) {
1729    // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1730    // initializer until now for such expressions. Such an expression can't be
1731    // an ICE in C, so this only matters for fold.
1732    assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1733    if (!Evaluate(RVal, Info, CLE->getInitializer()))
1734      return false;
1735  } else {
1736    Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1737    return false;
1738  }
1739
1740  return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1741                          Type);
1742}
1743
1744/// Build an lvalue for the object argument of a member function call.
1745static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1746                                   LValue &This) {
1747  if (Object->getType()->isPointerType())
1748    return EvaluatePointer(Object, This, Info);
1749
1750  if (Object->isGLValue())
1751    return EvaluateLValue(Object, This, Info);
1752
1753  if (Object->getType()->isLiteralType())
1754    return EvaluateTemporary(Object, This, Info);
1755
1756  return false;
1757}
1758
1759/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1760/// lvalue referring to the result.
1761///
1762/// \param Info - Information about the ongoing evaluation.
1763/// \param BO - The member pointer access operation.
1764/// \param LV - Filled in with a reference to the resulting object.
1765/// \param IncludeMember - Specifies whether the member itself is included in
1766///        the resulting LValue subobject designator. This is not possible when
1767///        creating a bound member function.
1768/// \return The field or method declaration to which the member pointer refers,
1769///         or 0 if evaluation fails.
1770static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1771                                                  const BinaryOperator *BO,
1772                                                  LValue &LV,
1773                                                  bool IncludeMember = true) {
1774  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1775
1776  bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1777  if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
1778    return 0;
1779
1780  MemberPtr MemPtr;
1781  if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1782    return 0;
1783
1784  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1785  // member value, the behavior is undefined.
1786  if (!MemPtr.getDecl())
1787    return 0;
1788
1789  if (!EvalObjOK)
1790    return 0;
1791
1792  if (MemPtr.isDerivedMember()) {
1793    // This is a member of some derived class. Truncate LV appropriately.
1794    // The end of the derived-to-base path for the base object must match the
1795    // derived-to-base path for the member pointer.
1796    if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
1797        LV.Designator.Entries.size())
1798      return 0;
1799    unsigned PathLengthToMember =
1800        LV.Designator.Entries.size() - MemPtr.Path.size();
1801    for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1802      const CXXRecordDecl *LVDecl = getAsBaseClass(
1803          LV.Designator.Entries[PathLengthToMember + I]);
1804      const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1805      if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1806        return 0;
1807    }
1808
1809    // Truncate the lvalue to the appropriate derived class.
1810    if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1811                            PathLengthToMember))
1812      return 0;
1813  } else if (!MemPtr.Path.empty()) {
1814    // Extend the LValue path with the member pointer's path.
1815    LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1816                                  MemPtr.Path.size() + IncludeMember);
1817
1818    // Walk down to the appropriate base class.
1819    QualType LVType = BO->getLHS()->getType();
1820    if (const PointerType *PT = LVType->getAs<PointerType>())
1821      LVType = PT->getPointeeType();
1822    const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1823    assert(RD && "member pointer access on non-class-type expression");
1824    // The first class in the path is that of the lvalue.
1825    for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1826      const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1827      HandleLValueDirectBase(Info, BO, LV, RD, Base);
1828      RD = Base;
1829    }
1830    // Finally cast to the class containing the member.
1831    HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
1832  }
1833
1834  // Add the member. Note that we cannot build bound member functions here.
1835  if (IncludeMember) {
1836    if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1837      HandleLValueMember(Info, BO, LV, FD);
1838    else if (const IndirectFieldDecl *IFD =
1839               dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1840      HandleLValueIndirectMember(Info, BO, LV, IFD);
1841    else
1842      llvm_unreachable("can't construct reference to bound member function");
1843  }
1844
1845  return MemPtr.getDecl();
1846}
1847
1848/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1849/// the provided lvalue, which currently refers to the base object.
1850static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1851                                    LValue &Result) {
1852  SubobjectDesignator &D = Result.Designator;
1853  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
1854    return false;
1855
1856  QualType TargetQT = E->getType();
1857  if (const PointerType *PT = TargetQT->getAs<PointerType>())
1858    TargetQT = PT->getPointeeType();
1859
1860  // Check this cast lands within the final derived-to-base subobject path.
1861  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1862    Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1863      << D.MostDerivedType << TargetQT;
1864    return false;
1865  }
1866
1867  // Check the type of the final cast. We don't need to check the path,
1868  // since a cast can only be formed if the path is unique.
1869  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1870  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1871  const CXXRecordDecl *FinalType;
1872  if (NewEntriesSize == D.MostDerivedPathLength)
1873    FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1874  else
1875    FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1876  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1877    Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1878      << D.MostDerivedType << TargetQT;
1879    return false;
1880  }
1881
1882  // Truncate the lvalue to the appropriate derived class.
1883  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
1884}
1885
1886namespace {
1887enum EvalStmtResult {
1888  /// Evaluation failed.
1889  ESR_Failed,
1890  /// Hit a 'return' statement.
1891  ESR_Returned,
1892  /// Evaluation succeeded.
1893  ESR_Succeeded
1894};
1895}
1896
1897// Evaluate a statement.
1898static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
1899                                   const Stmt *S) {
1900  switch (S->getStmtClass()) {
1901  default:
1902    return ESR_Failed;
1903
1904  case Stmt::NullStmtClass:
1905  case Stmt::DeclStmtClass:
1906    return ESR_Succeeded;
1907
1908  case Stmt::ReturnStmtClass: {
1909    CCValue CCResult;
1910    const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1911    if (!Evaluate(CCResult, Info, RetExpr) ||
1912        !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1913                                 CCEK_ReturnValue))
1914      return ESR_Failed;
1915    return ESR_Returned;
1916  }
1917
1918  case Stmt::CompoundStmtClass: {
1919    const CompoundStmt *CS = cast<CompoundStmt>(S);
1920    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1921           BE = CS->body_end(); BI != BE; ++BI) {
1922      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1923      if (ESR != ESR_Succeeded)
1924        return ESR;
1925    }
1926    return ESR_Succeeded;
1927  }
1928  }
1929}
1930
1931/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1932/// default constructor. If so, we'll fold it whether or not it's marked as
1933/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1934/// so we need special handling.
1935static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
1936                                           const CXXConstructorDecl *CD,
1937                                           bool IsValueInitialization) {
1938  if (!CD->isTrivial() || !CD->isDefaultConstructor())
1939    return false;
1940
1941  // Value-initialization does not call a trivial default constructor, so such a
1942  // call is a core constant expression whether or not the constructor is
1943  // constexpr.
1944  if (!CD->isConstexpr() && !IsValueInitialization) {
1945    if (Info.getLangOpts().CPlusPlus0x) {
1946      // FIXME: If DiagDecl is an implicitly-declared special member function,
1947      // we should be much more explicit about why it's not constexpr.
1948      Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1949        << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1950      Info.Note(CD->getLocation(), diag::note_declared_at);
1951    } else {
1952      Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1953    }
1954  }
1955  return true;
1956}
1957
1958/// CheckConstexprFunction - Check that a function can be called in a constant
1959/// expression.
1960static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1961                                   const FunctionDecl *Declaration,
1962                                   const FunctionDecl *Definition) {
1963  // Potential constant expressions can contain calls to declared, but not yet
1964  // defined, constexpr functions.
1965  if (Info.CheckingPotentialConstantExpression && !Definition &&
1966      Declaration->isConstexpr())
1967    return false;
1968
1969  // Can we evaluate this function call?
1970  if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1971    return true;
1972
1973  if (Info.getLangOpts().CPlusPlus0x) {
1974    const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
1975    // FIXME: If DiagDecl is an implicitly-declared special member function, we
1976    // should be much more explicit about why it's not constexpr.
1977    Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1978      << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1979      << DiagDecl;
1980    Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1981  } else {
1982    Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1983  }
1984  return false;
1985}
1986
1987namespace {
1988typedef SmallVector<CCValue, 8> ArgVector;
1989}
1990
1991/// EvaluateArgs - Evaluate the arguments to a function call.
1992static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1993                         EvalInfo &Info) {
1994  bool Success = true;
1995  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1996       I != E; ++I) {
1997    if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1998      // If we're checking for a potential constant expression, evaluate all
1999      // initializers even if some of them fail.
2000      if (!Info.keepEvaluatingAfterFailure())
2001        return false;
2002      Success = false;
2003    }
2004  }
2005  return Success;
2006}
2007
2008/// Evaluate a function call.
2009static bool HandleFunctionCall(SourceLocation CallLoc,
2010                               const FunctionDecl *Callee, const LValue *This,
2011                               ArrayRef<const Expr*> Args, const Stmt *Body,
2012                               EvalInfo &Info, APValue &Result) {
2013  ArgVector ArgValues(Args.size());
2014  if (!EvaluateArgs(Args, ArgValues, Info))
2015    return false;
2016
2017  if (!Info.CheckCallLimit(CallLoc))
2018    return false;
2019
2020  CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
2021  return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2022}
2023
2024/// Evaluate a constructor call.
2025static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
2026                                  ArrayRef<const Expr*> Args,
2027                                  const CXXConstructorDecl *Definition,
2028                                  EvalInfo &Info, APValue &Result) {
2029  ArgVector ArgValues(Args.size());
2030  if (!EvaluateArgs(Args, ArgValues, Info))
2031    return false;
2032
2033  if (!Info.CheckCallLimit(CallLoc))
2034    return false;
2035
2036  const CXXRecordDecl *RD = Definition->getParent();
2037  if (RD->getNumVBases()) {
2038    Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2039    return false;
2040  }
2041
2042  CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
2043
2044  // If it's a delegating constructor, just delegate.
2045  if (Definition->isDelegatingConstructor()) {
2046    CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2047    return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
2048  }
2049
2050  // For a trivial copy or move constructor, perform an APValue copy. This is
2051  // essential for unions, where the operations performed by the constructor
2052  // cannot be represented by ctor-initializers.
2053  if (Definition->isDefaulted() &&
2054      ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2055       (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2056    LValue RHS;
2057    RHS.setFrom(ArgValues[0]);
2058    CCValue Value;
2059    if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2060                                        RHS, Value))
2061      return false;
2062    assert((Value.isStruct() || Value.isUnion()) &&
2063           "trivial copy/move from non-class type?");
2064    // Any CCValue of class type must already be a constant expression.
2065    Result = Value;
2066    return true;
2067  }
2068
2069  // Reserve space for the struct members.
2070  if (!RD->isUnion() && Result.isUninit())
2071    Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2072                     std::distance(RD->field_begin(), RD->field_end()));
2073
2074  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2075
2076  bool Success = true;
2077  unsigned BasesSeen = 0;
2078#ifndef NDEBUG
2079  CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2080#endif
2081  for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2082       E = Definition->init_end(); I != E; ++I) {
2083    LValue Subobject = This;
2084    APValue *Value = &Result;
2085
2086    // Determine the subobject to initialize.
2087    if ((*I)->isBaseInitializer()) {
2088      QualType BaseType((*I)->getBaseClass(), 0);
2089#ifndef NDEBUG
2090      // Non-virtual base classes are initialized in the order in the class
2091      // definition. We have already checked for virtual base classes.
2092      assert(!BaseIt->isVirtual() && "virtual base for literal type");
2093      assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2094             "base class initializers not in expected order");
2095      ++BaseIt;
2096#endif
2097      HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2098                             BaseType->getAsCXXRecordDecl(), &Layout);
2099      Value = &Result.getStructBase(BasesSeen++);
2100    } else if (FieldDecl *FD = (*I)->getMember()) {
2101      HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
2102      if (RD->isUnion()) {
2103        Result = APValue(FD);
2104        Value = &Result.getUnionValue();
2105      } else {
2106        Value = &Result.getStructField(FD->getFieldIndex());
2107      }
2108    } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
2109      // Walk the indirect field decl's chain to find the object to initialize,
2110      // and make sure we've initialized every step along it.
2111      for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2112                                             CE = IFD->chain_end();
2113           C != CE; ++C) {
2114        FieldDecl *FD = cast<FieldDecl>(*C);
2115        CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2116        // Switch the union field if it differs. This happens if we had
2117        // preceding zero-initialization, and we're now initializing a union
2118        // subobject other than the first.
2119        // FIXME: In this case, the values of the other subobjects are
2120        // specified, since zero-initialization sets all padding bits to zero.
2121        if (Value->isUninit() ||
2122            (Value->isUnion() && Value->getUnionField() != FD)) {
2123          if (CD->isUnion())
2124            *Value = APValue(FD);
2125          else
2126            *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2127                             std::distance(CD->field_begin(), CD->field_end()));
2128        }
2129        HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
2130        if (CD->isUnion())
2131          Value = &Value->getUnionValue();
2132        else
2133          Value = &Value->getStructField(FD->getFieldIndex());
2134      }
2135    } else {
2136      llvm_unreachable("unknown base initializer kind");
2137    }
2138
2139    if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2140                                    (*I)->isBaseInitializer()
2141                                      ? CCEK_Constant : CCEK_MemberInit)) {
2142      // If we're checking for a potential constant expression, evaluate all
2143      // initializers even if some of them fail.
2144      if (!Info.keepEvaluatingAfterFailure())
2145        return false;
2146      Success = false;
2147    }
2148  }
2149
2150  return Success;
2151}
2152
2153namespace {
2154class HasSideEffect
2155  : public ConstStmtVisitor<HasSideEffect, bool> {
2156  const ASTContext &Ctx;
2157public:
2158
2159  HasSideEffect(const ASTContext &C) : Ctx(C) {}
2160
2161  // Unhandled nodes conservatively default to having side effects.
2162  bool VisitStmt(const Stmt *S) {
2163    return true;
2164  }
2165
2166  bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2167  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
2168    return Visit(E->getResultExpr());
2169  }
2170  bool VisitDeclRefExpr(const DeclRefExpr *E) {
2171    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2172      return true;
2173    return false;
2174  }
2175  bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
2176    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2177      return true;
2178    return false;
2179  }
2180  bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
2181    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2182      return true;
2183    return false;
2184  }
2185
2186  // We don't want to evaluate BlockExprs multiple times, as they generate
2187  // a ton of code.
2188  bool VisitBlockExpr(const BlockExpr *E) { return true; }
2189  bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2190  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
2191    { return Visit(E->getInitializer()); }
2192  bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2193  bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2194  bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2195  bool VisitStringLiteral(const StringLiteral *E) { return false; }
2196  bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2197  bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
2198    { return false; }
2199  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
2200    { return Visit(E->getLHS()) || Visit(E->getRHS()); }
2201  bool VisitChooseExpr(const ChooseExpr *E)
2202    { return Visit(E->getChosenSubExpr(Ctx)); }
2203  bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2204  bool VisitBinAssign(const BinaryOperator *E) { return true; }
2205  bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2206  bool VisitBinaryOperator(const BinaryOperator *E)
2207  { return Visit(E->getLHS()) || Visit(E->getRHS()); }
2208  bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2209  bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2210  bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2211  bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2212  bool VisitUnaryDeref(const UnaryOperator *E) {
2213    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2214      return true;
2215    return Visit(E->getSubExpr());
2216  }
2217  bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
2218
2219  // Has side effects if any element does.
2220  bool VisitInitListExpr(const InitListExpr *E) {
2221    for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2222      if (Visit(E->getInit(i))) return true;
2223    if (const Expr *filler = E->getArrayFiller())
2224      return Visit(filler);
2225    return false;
2226  }
2227
2228  bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
2229};
2230
2231class OpaqueValueEvaluation {
2232  EvalInfo &info;
2233  OpaqueValueExpr *opaqueValue;
2234
2235public:
2236  OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2237                        Expr *value)
2238    : info(info), opaqueValue(opaqueValue) {
2239
2240    // If evaluation fails, fail immediately.
2241    if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
2242      this->opaqueValue = 0;
2243      return;
2244    }
2245  }
2246
2247  bool hasError() const { return opaqueValue == 0; }
2248
2249  ~OpaqueValueEvaluation() {
2250    // FIXME: This will not work for recursive constexpr functions using opaque
2251    // values. Restore the former value.
2252    if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2253  }
2254};
2255
2256} // end anonymous namespace
2257
2258//===----------------------------------------------------------------------===//
2259// Generic Evaluation
2260//===----------------------------------------------------------------------===//
2261namespace {
2262
2263// FIXME: RetTy is always bool. Remove it.
2264template <class Derived, typename RetTy=bool>
2265class ExprEvaluatorBase
2266  : public ConstStmtVisitor<Derived, RetTy> {
2267private:
2268  RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
2269    return static_cast<Derived*>(this)->Success(V, E);
2270  }
2271  RetTy DerivedZeroInitialization(const Expr *E) {
2272    return static_cast<Derived*>(this)->ZeroInitialization(E);
2273  }
2274
2275protected:
2276  EvalInfo &Info;
2277  typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2278  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2279
2280  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
2281    return Info.CCEDiag(E->getExprLoc(), D);
2282  }
2283
2284  /// Report an evaluation error. This should only be called when an error is
2285  /// first discovered. When propagating an error, just return false.
2286  bool Error(const Expr *E, diag::kind D) {
2287    Info.Diag(E->getExprLoc(), D);
2288    return false;
2289  }
2290  bool Error(const Expr *E) {
2291    return Error(E, diag::note_invalid_subexpr_in_const_expr);
2292  }
2293
2294  RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2295
2296public:
2297  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2298
2299  RetTy VisitStmt(const Stmt *) {
2300    llvm_unreachable("Expression evaluator should not be called on stmts");
2301  }
2302  RetTy VisitExpr(const Expr *E) {
2303    return Error(E);
2304  }
2305
2306  RetTy VisitParenExpr(const ParenExpr *E)
2307    { return StmtVisitorTy::Visit(E->getSubExpr()); }
2308  RetTy VisitUnaryExtension(const UnaryOperator *E)
2309    { return StmtVisitorTy::Visit(E->getSubExpr()); }
2310  RetTy VisitUnaryPlus(const UnaryOperator *E)
2311    { return StmtVisitorTy::Visit(E->getSubExpr()); }
2312  RetTy VisitChooseExpr(const ChooseExpr *E)
2313    { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2314  RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2315    { return StmtVisitorTy::Visit(E->getResultExpr()); }
2316  RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2317    { return StmtVisitorTy::Visit(E->getReplacement()); }
2318  RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2319    { return StmtVisitorTy::Visit(E->getExpr()); }
2320  // We cannot create any objects for which cleanups are required, so there is
2321  // nothing to do here; all cleanups must come from unevaluated subexpressions.
2322  RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2323    { return StmtVisitorTy::Visit(E->getSubExpr()); }
2324
2325  RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2326    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2327    return static_cast<Derived*>(this)->VisitCastExpr(E);
2328  }
2329  RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2330    CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2331    return static_cast<Derived*>(this)->VisitCastExpr(E);
2332  }
2333
2334  RetTy VisitBinaryOperator(const BinaryOperator *E) {
2335    switch (E->getOpcode()) {
2336    default:
2337      return Error(E);
2338
2339    case BO_Comma:
2340      VisitIgnoredValue(E->getLHS());
2341      return StmtVisitorTy::Visit(E->getRHS());
2342
2343    case BO_PtrMemD:
2344    case BO_PtrMemI: {
2345      LValue Obj;
2346      if (!HandleMemberPointerAccess(Info, E, Obj))
2347        return false;
2348      CCValue Result;
2349      if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
2350        return false;
2351      return DerivedSuccess(Result, E);
2352    }
2353    }
2354  }
2355
2356  RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2357    OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2358    if (opaque.hasError())
2359      return false;
2360
2361    bool cond;
2362    if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
2363      return false;
2364
2365    return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2366  }
2367
2368  RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2369    bool IsBcpCall = false;
2370    // If the condition (ignoring parens) is a __builtin_constant_p call,
2371    // the result is a constant expression if it can be folded without
2372    // side-effects. This is an important GNU extension. See GCC PR38377
2373    // for discussion.
2374    if (const CallExpr *CallCE =
2375          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2376      if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2377        IsBcpCall = true;
2378
2379    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2380    // constant expression; we can't check whether it's potentially foldable.
2381    if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2382      return false;
2383
2384    FoldConstant Fold(Info);
2385
2386    bool BoolResult;
2387    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
2388      return false;
2389
2390    Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2391    if (!StmtVisitorTy::Visit(EvalExpr))
2392      return false;
2393
2394    if (IsBcpCall)
2395      Fold.Fold(Info);
2396
2397    return true;
2398  }
2399
2400  RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2401    const CCValue *Value = Info.getOpaqueValue(E);
2402    if (!Value) {
2403      const Expr *Source = E->getSourceExpr();
2404      if (!Source)
2405        return Error(E);
2406      if (Source == E) { // sanity checking.
2407        assert(0 && "OpaqueValueExpr recursively refers to itself");
2408        return Error(E);
2409      }
2410      return StmtVisitorTy::Visit(Source);
2411    }
2412    return DerivedSuccess(*Value, E);
2413  }
2414
2415  RetTy VisitCallExpr(const CallExpr *E) {
2416    const Expr *Callee = E->getCallee()->IgnoreParens();
2417    QualType CalleeType = Callee->getType();
2418
2419    const FunctionDecl *FD = 0;
2420    LValue *This = 0, ThisVal;
2421    llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
2422    bool HasQualifier = false;
2423
2424    // Extract function decl and 'this' pointer from the callee.
2425    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
2426      const ValueDecl *Member = 0;
2427      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2428        // Explicit bound member calls, such as x.f() or p->g();
2429        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
2430          return false;
2431        Member = ME->getMemberDecl();
2432        This = &ThisVal;
2433        HasQualifier = ME->hasQualifier();
2434      } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2435        // Indirect bound member calls ('.*' or '->*').
2436        Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2437        if (!Member) return false;
2438        This = &ThisVal;
2439      } else
2440        return Error(Callee);
2441
2442      FD = dyn_cast<FunctionDecl>(Member);
2443      if (!FD)
2444        return Error(Callee);
2445    } else if (CalleeType->isFunctionPointerType()) {
2446      LValue Call;
2447      if (!EvaluatePointer(Callee, Call, Info))
2448        return false;
2449
2450      if (!Call.getLValueOffset().isZero())
2451        return Error(Callee);
2452      FD = dyn_cast_or_null<FunctionDecl>(
2453                             Call.getLValueBase().dyn_cast<const ValueDecl*>());
2454      if (!FD)
2455        return Error(Callee);
2456
2457      // Overloaded operator calls to member functions are represented as normal
2458      // calls with '*this' as the first argument.
2459      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2460      if (MD && !MD->isStatic()) {
2461        // FIXME: When selecting an implicit conversion for an overloaded
2462        // operator delete, we sometimes try to evaluate calls to conversion
2463        // operators without a 'this' parameter!
2464        if (Args.empty())
2465          return Error(E);
2466
2467        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2468          return false;
2469        This = &ThisVal;
2470        Args = Args.slice(1);
2471      }
2472
2473      // Don't call function pointers which have been cast to some other type.
2474      if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
2475        return Error(E);
2476    } else
2477      return Error(E);
2478
2479    if (This && !This->checkSubobject(Info, E, CSK_This))
2480      return false;
2481
2482    // DR1358 allows virtual constexpr functions in some cases. Don't allow
2483    // calls to such functions in constant expressions.
2484    if (This && !HasQualifier &&
2485        isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2486      return Error(E, diag::note_constexpr_virtual_call);
2487
2488    const FunctionDecl *Definition = 0;
2489    Stmt *Body = FD->getBody(Definition);
2490    APValue Result;
2491
2492    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
2493        !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2494                            Info, Result))
2495      return false;
2496
2497    return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
2498  }
2499
2500  RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2501    return StmtVisitorTy::Visit(E->getInitializer());
2502  }
2503  RetTy VisitInitListExpr(const InitListExpr *E) {
2504    if (E->getNumInits() == 0)
2505      return DerivedZeroInitialization(E);
2506    if (E->getNumInits() == 1)
2507      return StmtVisitorTy::Visit(E->getInit(0));
2508    return Error(E);
2509  }
2510  RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2511    return DerivedZeroInitialization(E);
2512  }
2513  RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2514    return DerivedZeroInitialization(E);
2515  }
2516  RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2517    return DerivedZeroInitialization(E);
2518  }
2519
2520  /// A member expression where the object is a prvalue is itself a prvalue.
2521  RetTy VisitMemberExpr(const MemberExpr *E) {
2522    assert(!E->isArrow() && "missing call to bound member function?");
2523
2524    CCValue Val;
2525    if (!Evaluate(Val, Info, E->getBase()))
2526      return false;
2527
2528    QualType BaseTy = E->getBase()->getType();
2529
2530    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2531    if (!FD) return Error(E);
2532    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2533    assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2534           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2535
2536    SubobjectDesignator Designator(BaseTy);
2537    Designator.addDeclUnchecked(FD);
2538
2539    return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
2540           DerivedSuccess(Val, E);
2541  }
2542
2543  RetTy VisitCastExpr(const CastExpr *E) {
2544    switch (E->getCastKind()) {
2545    default:
2546      break;
2547
2548    case CK_AtomicToNonAtomic:
2549    case CK_NonAtomicToAtomic:
2550    case CK_NoOp:
2551    case CK_UserDefinedConversion:
2552      return StmtVisitorTy::Visit(E->getSubExpr());
2553
2554    case CK_LValueToRValue: {
2555      LValue LVal;
2556      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2557        return false;
2558      CCValue RVal;
2559      // Note, we use the subexpression's type in order to retain cv-qualifiers.
2560      if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2561                                          LVal, RVal))
2562        return false;
2563      return DerivedSuccess(RVal, E);
2564    }
2565    }
2566
2567    return Error(E);
2568  }
2569
2570  /// Visit a value which is evaluated, but whose value is ignored.
2571  void VisitIgnoredValue(const Expr *E) {
2572    CCValue Scratch;
2573    if (!Evaluate(Scratch, Info, E))
2574      Info.EvalStatus.HasSideEffects = true;
2575  }
2576};
2577
2578}
2579
2580//===----------------------------------------------------------------------===//
2581// Common base class for lvalue and temporary evaluation.
2582//===----------------------------------------------------------------------===//
2583namespace {
2584template<class Derived>
2585class LValueExprEvaluatorBase
2586  : public ExprEvaluatorBase<Derived, bool> {
2587protected:
2588  LValue &Result;
2589  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2590  typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2591
2592  bool Success(APValue::LValueBase B) {
2593    Result.set(B);
2594    return true;
2595  }
2596
2597public:
2598  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2599    ExprEvaluatorBaseTy(Info), Result(Result) {}
2600
2601  bool Success(const CCValue &V, const Expr *E) {
2602    Result.setFrom(V);
2603    return true;
2604  }
2605
2606  bool VisitMemberExpr(const MemberExpr *E) {
2607    // Handle non-static data members.
2608    QualType BaseTy;
2609    if (E->isArrow()) {
2610      if (!EvaluatePointer(E->getBase(), Result, this->Info))
2611        return false;
2612      BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
2613    } else if (E->getBase()->isRValue()) {
2614      assert(E->getBase()->getType()->isRecordType());
2615      if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2616        return false;
2617      BaseTy = E->getBase()->getType();
2618    } else {
2619      if (!this->Visit(E->getBase()))
2620        return false;
2621      BaseTy = E->getBase()->getType();
2622    }
2623
2624    const ValueDecl *MD = E->getMemberDecl();
2625    if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2626      assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2627             FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2628      (void)BaseTy;
2629      HandleLValueMember(this->Info, E, Result, FD);
2630    } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2631      HandleLValueIndirectMember(this->Info, E, Result, IFD);
2632    } else
2633      return this->Error(E);
2634
2635    if (MD->getType()->isReferenceType()) {
2636      CCValue RefValue;
2637      if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
2638                                          RefValue))
2639        return false;
2640      return Success(RefValue, E);
2641    }
2642    return true;
2643  }
2644
2645  bool VisitBinaryOperator(const BinaryOperator *E) {
2646    switch (E->getOpcode()) {
2647    default:
2648      return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2649
2650    case BO_PtrMemD:
2651    case BO_PtrMemI:
2652      return HandleMemberPointerAccess(this->Info, E, Result);
2653    }
2654  }
2655
2656  bool VisitCastExpr(const CastExpr *E) {
2657    switch (E->getCastKind()) {
2658    default:
2659      return ExprEvaluatorBaseTy::VisitCastExpr(E);
2660
2661    case CK_DerivedToBase:
2662    case CK_UncheckedDerivedToBase: {
2663      if (!this->Visit(E->getSubExpr()))
2664        return false;
2665
2666      // Now figure out the necessary offset to add to the base LV to get from
2667      // the derived class to the base class.
2668      QualType Type = E->getSubExpr()->getType();
2669
2670      for (CastExpr::path_const_iterator PathI = E->path_begin(),
2671           PathE = E->path_end(); PathI != PathE; ++PathI) {
2672        if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
2673                              *PathI))
2674          return false;
2675        Type = (*PathI)->getType();
2676      }
2677
2678      return true;
2679    }
2680    }
2681  }
2682};
2683}
2684
2685//===----------------------------------------------------------------------===//
2686// LValue Evaluation
2687//
2688// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2689// function designators (in C), decl references to void objects (in C), and
2690// temporaries (if building with -Wno-address-of-temporary).
2691//
2692// LValue evaluation produces values comprising a base expression of one of the
2693// following types:
2694// - Declarations
2695//  * VarDecl
2696//  * FunctionDecl
2697// - Literals
2698//  * CompoundLiteralExpr in C
2699//  * StringLiteral
2700//  * CXXTypeidExpr
2701//  * PredefinedExpr
2702//  * ObjCStringLiteralExpr
2703//  * ObjCEncodeExpr
2704//  * AddrLabelExpr
2705//  * BlockExpr
2706//  * CallExpr for a MakeStringConstant builtin
2707// - Locals and temporaries
2708//  * Any Expr, with a Frame indicating the function in which the temporary was
2709//    evaluated.
2710// plus an offset in bytes.
2711//===----------------------------------------------------------------------===//
2712namespace {
2713class LValueExprEvaluator
2714  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
2715public:
2716  LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2717    LValueExprEvaluatorBaseTy(Info, Result) {}
2718
2719  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2720
2721  bool VisitDeclRefExpr(const DeclRefExpr *E);
2722  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
2723  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2724  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2725  bool VisitMemberExpr(const MemberExpr *E);
2726  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2727  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2728  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2729  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2730  bool VisitUnaryDeref(const UnaryOperator *E);
2731
2732  bool VisitCastExpr(const CastExpr *E) {
2733    switch (E->getCastKind()) {
2734    default:
2735      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2736
2737    case CK_LValueBitCast:
2738      this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2739      if (!Visit(E->getSubExpr()))
2740        return false;
2741      Result.Designator.setInvalid();
2742      return true;
2743
2744    case CK_BaseToDerived:
2745      if (!Visit(E->getSubExpr()))
2746        return false;
2747      return HandleBaseToDerivedCast(Info, E, Result);
2748    }
2749  }
2750
2751  // FIXME: Missing: __real__, __imag__
2752
2753};
2754} // end anonymous namespace
2755
2756/// Evaluate an expression as an lvalue. This can be legitimately called on
2757/// expressions which are not glvalues, in a few cases:
2758///  * function designators in C,
2759///  * "extern void" objects,
2760///  * temporaries, if building with -Wno-address-of-temporary.
2761static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
2762  assert((E->isGLValue() || E->getType()->isFunctionType() ||
2763          E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2764         "can't evaluate expression as an lvalue");
2765  return LValueExprEvaluator(Info, Result).Visit(E);
2766}
2767
2768bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2769  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2770    return Success(FD);
2771  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
2772    return VisitVarDecl(E, VD);
2773  return Error(E);
2774}
2775
2776bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
2777  if (!VD->getType()->isReferenceType()) {
2778    if (isa<ParmVarDecl>(VD)) {
2779      Result.set(VD, Info.CurrentCall);
2780      return true;
2781    }
2782    return Success(VD);
2783  }
2784
2785  CCValue V;
2786  if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2787    return false;
2788  return Success(V, E);
2789}
2790
2791bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2792    const MaterializeTemporaryExpr *E) {
2793  if (E->GetTemporaryExpr()->isRValue()) {
2794    if (E->getType()->isRecordType())
2795      return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2796
2797    Result.set(E, Info.CurrentCall);
2798    return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2799                                      Result, E->GetTemporaryExpr());
2800  }
2801
2802  // Materialization of an lvalue temporary occurs when we need to force a copy
2803  // (for instance, if it's a bitfield).
2804  // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2805  if (!Visit(E->GetTemporaryExpr()))
2806    return false;
2807  if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
2808                                      Info.CurrentCall->Temporaries[E]))
2809    return false;
2810  Result.set(E, Info.CurrentCall);
2811  return true;
2812}
2813
2814bool
2815LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2816  assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2817  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2818  // only see this when folding in C, so there's no standard to follow here.
2819  return Success(E);
2820}
2821
2822bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2823  if (E->isTypeOperand())
2824    return Success(E);
2825  CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2826  if (RD && RD->isPolymorphic()) {
2827    Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2828      << E->getExprOperand()->getType()
2829      << E->getExprOperand()->getSourceRange();
2830    return false;
2831  }
2832  return Success(E);
2833}
2834
2835bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
2836  // Handle static data members.
2837  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2838    VisitIgnoredValue(E->getBase());
2839    return VisitVarDecl(E, VD);
2840  }
2841
2842  // Handle static member functions.
2843  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2844    if (MD->isStatic()) {
2845      VisitIgnoredValue(E->getBase());
2846      return Success(MD);
2847    }
2848  }
2849
2850  // Handle non-static data members.
2851  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
2852}
2853
2854bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
2855  // FIXME: Deal with vectors as array subscript bases.
2856  if (E->getBase()->getType()->isVectorType())
2857    return Error(E);
2858
2859  if (!EvaluatePointer(E->getBase(), Result, Info))
2860    return false;
2861
2862  APSInt Index;
2863  if (!EvaluateInteger(E->getIdx(), Index, Info))
2864    return false;
2865  int64_t IndexValue
2866    = Index.isSigned() ? Index.getSExtValue()
2867                       : static_cast<int64_t>(Index.getZExtValue());
2868
2869  return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
2870}
2871
2872bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
2873  return EvaluatePointer(E->getSubExpr(), Result, Info);
2874}
2875
2876//===----------------------------------------------------------------------===//
2877// Pointer Evaluation
2878//===----------------------------------------------------------------------===//
2879
2880namespace {
2881class PointerExprEvaluator
2882  : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
2883  LValue &Result;
2884
2885  bool Success(const Expr *E) {
2886    Result.set(E);
2887    return true;
2888  }
2889public:
2890
2891  PointerExprEvaluator(EvalInfo &info, LValue &Result)
2892    : ExprEvaluatorBaseTy(info), Result(Result) {}
2893
2894  bool Success(const CCValue &V, const Expr *E) {
2895    Result.setFrom(V);
2896    return true;
2897  }
2898  bool ZeroInitialization(const Expr *E) {
2899    return Success((Expr*)0);
2900  }
2901
2902  bool VisitBinaryOperator(const BinaryOperator *E);
2903  bool VisitCastExpr(const CastExpr* E);
2904  bool VisitUnaryAddrOf(const UnaryOperator *E);
2905  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
2906      { return Success(E); }
2907  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
2908      { return Success(E); }
2909  bool VisitCallExpr(const CallExpr *E);
2910  bool VisitBlockExpr(const BlockExpr *E) {
2911    if (!E->getBlockDecl()->hasCaptures())
2912      return Success(E);
2913    return Error(E);
2914  }
2915  bool VisitCXXThisExpr(const CXXThisExpr *E) {
2916    if (!Info.CurrentCall->This)
2917      return Error(E);
2918    Result = *Info.CurrentCall->This;
2919    return true;
2920  }
2921
2922  // FIXME: Missing: @protocol, @selector
2923};
2924} // end anonymous namespace
2925
2926static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
2927  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
2928  return PointerExprEvaluator(Info, Result).Visit(E);
2929}
2930
2931bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2932  if (E->getOpcode() != BO_Add &&
2933      E->getOpcode() != BO_Sub)
2934    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2935
2936  const Expr *PExp = E->getLHS();
2937  const Expr *IExp = E->getRHS();
2938  if (IExp->getType()->isPointerType())
2939    std::swap(PExp, IExp);
2940
2941  bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2942  if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
2943    return false;
2944
2945  llvm::APSInt Offset;
2946  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
2947    return false;
2948  int64_t AdditionalOffset
2949    = Offset.isSigned() ? Offset.getSExtValue()
2950                        : static_cast<int64_t>(Offset.getZExtValue());
2951  if (E->getOpcode() == BO_Sub)
2952    AdditionalOffset = -AdditionalOffset;
2953
2954  QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
2955  return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2956                                     AdditionalOffset);
2957}
2958
2959bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2960  return EvaluateLValue(E->getSubExpr(), Result, Info);
2961}
2962
2963bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2964  const Expr* SubExpr = E->getSubExpr();
2965
2966  switch (E->getCastKind()) {
2967  default:
2968    break;
2969
2970  case CK_BitCast:
2971  case CK_CPointerToObjCPointerCast:
2972  case CK_BlockPointerToObjCPointerCast:
2973  case CK_AnyPointerToBlockPointerCast:
2974    if (!Visit(SubExpr))
2975      return false;
2976    // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2977    // permitted in constant expressions in C++11. Bitcasts from cv void* are
2978    // also static_casts, but we disallow them as a resolution to DR1312.
2979    if (!E->getType()->isVoidPointerType()) {
2980      Result.Designator.setInvalid();
2981      if (SubExpr->getType()->isVoidPointerType())
2982        CCEDiag(E, diag::note_constexpr_invalid_cast)
2983          << 3 << SubExpr->getType();
2984      else
2985        CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2986    }
2987    return true;
2988
2989  case CK_DerivedToBase:
2990  case CK_UncheckedDerivedToBase: {
2991    if (!EvaluatePointer(E->getSubExpr(), Result, Info))
2992      return false;
2993    if (!Result.Base && Result.Offset.isZero())
2994      return true;
2995
2996    // Now figure out the necessary offset to add to the base LV to get from
2997    // the derived class to the base class.
2998    QualType Type =
2999        E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3000
3001    for (CastExpr::path_const_iterator PathI = E->path_begin(),
3002         PathE = E->path_end(); PathI != PathE; ++PathI) {
3003      if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3004                            *PathI))
3005        return false;
3006      Type = (*PathI)->getType();
3007    }
3008
3009    return true;
3010  }
3011
3012  case CK_BaseToDerived:
3013    if (!Visit(E->getSubExpr()))
3014      return false;
3015    if (!Result.Base && Result.Offset.isZero())
3016      return true;
3017    return HandleBaseToDerivedCast(Info, E, Result);
3018
3019  case CK_NullToPointer:
3020    return ZeroInitialization(E);
3021
3022  case CK_IntegralToPointer: {
3023    CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3024
3025    CCValue Value;
3026    if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
3027      break;
3028
3029    if (Value.isInt()) {
3030      unsigned Size = Info.Ctx.getTypeSize(E->getType());
3031      uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
3032      Result.Base = (Expr*)0;
3033      Result.Offset = CharUnits::fromQuantity(N);
3034      Result.Frame = 0;
3035      Result.Designator.setInvalid();
3036      return true;
3037    } else {
3038      // Cast is of an lvalue, no need to change value.
3039      Result.setFrom(Value);
3040      return true;
3041    }
3042  }
3043  case CK_ArrayToPointerDecay:
3044    if (SubExpr->isGLValue()) {
3045      if (!EvaluateLValue(SubExpr, Result, Info))
3046        return false;
3047    } else {
3048      Result.set(SubExpr, Info.CurrentCall);
3049      if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
3050                                      Info, Result, SubExpr))
3051        return false;
3052    }
3053    // The result is a pointer to the first element of the array.
3054    if (const ConstantArrayType *CAT
3055          = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3056      Result.addArray(Info, E, CAT);
3057    else
3058      Result.Designator.setInvalid();
3059    return true;
3060
3061  case CK_FunctionToPointerDecay:
3062    return EvaluateLValue(SubExpr, Result, Info);
3063  }
3064
3065  return ExprEvaluatorBaseTy::VisitCastExpr(E);
3066}
3067
3068bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
3069  if (IsStringLiteralCall(E))
3070    return Success(E);
3071
3072  return ExprEvaluatorBaseTy::VisitCallExpr(E);
3073}
3074
3075//===----------------------------------------------------------------------===//
3076// Member Pointer Evaluation
3077//===----------------------------------------------------------------------===//
3078
3079namespace {
3080class MemberPointerExprEvaluator
3081  : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3082  MemberPtr &Result;
3083
3084  bool Success(const ValueDecl *D) {
3085    Result = MemberPtr(D);
3086    return true;
3087  }
3088public:
3089
3090  MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3091    : ExprEvaluatorBaseTy(Info), Result(Result) {}
3092
3093  bool Success(const CCValue &V, const Expr *E) {
3094    Result.setFrom(V);
3095    return true;
3096  }
3097  bool ZeroInitialization(const Expr *E) {
3098    return Success((const ValueDecl*)0);
3099  }
3100
3101  bool VisitCastExpr(const CastExpr *E);
3102  bool VisitUnaryAddrOf(const UnaryOperator *E);
3103};
3104} // end anonymous namespace
3105
3106static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3107                                  EvalInfo &Info) {
3108  assert(E->isRValue() && E->getType()->isMemberPointerType());
3109  return MemberPointerExprEvaluator(Info, Result).Visit(E);
3110}
3111
3112bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3113  switch (E->getCastKind()) {
3114  default:
3115    return ExprEvaluatorBaseTy::VisitCastExpr(E);
3116
3117  case CK_NullToMemberPointer:
3118    return ZeroInitialization(E);
3119
3120  case CK_BaseToDerivedMemberPointer: {
3121    if (!Visit(E->getSubExpr()))
3122      return false;
3123    if (E->path_empty())
3124      return true;
3125    // Base-to-derived member pointer casts store the path in derived-to-base
3126    // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3127    // the wrong end of the derived->base arc, so stagger the path by one class.
3128    typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3129    for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3130         PathI != PathE; ++PathI) {
3131      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3132      const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3133      if (!Result.castToDerived(Derived))
3134        return Error(E);
3135    }
3136    const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3137    if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
3138      return Error(E);
3139    return true;
3140  }
3141
3142  case CK_DerivedToBaseMemberPointer:
3143    if (!Visit(E->getSubExpr()))
3144      return false;
3145    for (CastExpr::path_const_iterator PathI = E->path_begin(),
3146         PathE = E->path_end(); PathI != PathE; ++PathI) {
3147      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3148      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3149      if (!Result.castToBase(Base))
3150        return Error(E);
3151    }
3152    return true;
3153  }
3154}
3155
3156bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3157  // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3158  // member can be formed.
3159  return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3160}
3161
3162//===----------------------------------------------------------------------===//
3163// Record Evaluation
3164//===----------------------------------------------------------------------===//
3165
3166namespace {
3167  class RecordExprEvaluator
3168  : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3169    const LValue &This;
3170    APValue &Result;
3171  public:
3172
3173    RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3174      : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3175
3176    bool Success(const CCValue &V, const Expr *E) {
3177      return CheckConstantExpression(Info, E, V, Result);
3178    }
3179    bool ZeroInitialization(const Expr *E);
3180
3181    bool VisitCastExpr(const CastExpr *E);
3182    bool VisitInitListExpr(const InitListExpr *E);
3183    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3184  };
3185}
3186
3187/// Perform zero-initialization on an object of non-union class type.
3188/// C++11 [dcl.init]p5:
3189///  To zero-initialize an object or reference of type T means:
3190///    [...]
3191///    -- if T is a (possibly cv-qualified) non-union class type,
3192///       each non-static data member and each base-class subobject is
3193///       zero-initialized
3194static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3195                                          const RecordDecl *RD,
3196                                          const LValue &This, APValue &Result) {
3197  assert(!RD->isUnion() && "Expected non-union class type");
3198  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3199  Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3200                   std::distance(RD->field_begin(), RD->field_end()));
3201
3202  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3203
3204  if (CD) {
3205    unsigned Index = 0;
3206    for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
3207           End = CD->bases_end(); I != End; ++I, ++Index) {
3208      const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3209      LValue Subobject = This;
3210      HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3211      if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
3212                                         Result.getStructBase(Index)))
3213        return false;
3214    }
3215  }
3216
3217  for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3218       I != End; ++I) {
3219    // -- if T is a reference type, no initialization is performed.
3220    if ((*I)->getType()->isReferenceType())
3221      continue;
3222
3223    LValue Subobject = This;
3224    HandleLValueMember(Info, E, Subobject, *I, &Layout);
3225
3226    ImplicitValueInitExpr VIE((*I)->getType());
3227    if (!EvaluateConstantExpression(
3228          Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3229      return false;
3230  }
3231
3232  return true;
3233}
3234
3235bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3236  const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3237  if (RD->isUnion()) {
3238    // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3239    // object's first non-static named data member is zero-initialized
3240    RecordDecl::field_iterator I = RD->field_begin();
3241    if (I == RD->field_end()) {
3242      Result = APValue((const FieldDecl*)0);
3243      return true;
3244    }
3245
3246    LValue Subobject = This;
3247    HandleLValueMember(Info, E, Subobject, *I);
3248    Result = APValue(*I);
3249    ImplicitValueInitExpr VIE((*I)->getType());
3250    return EvaluateConstantExpression(Result.getUnionValue(), Info,
3251                                      Subobject, &VIE);
3252  }
3253
3254  return HandleClassZeroInitialization(Info, E, RD, This, Result);
3255}
3256
3257bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3258  switch (E->getCastKind()) {
3259  default:
3260    return ExprEvaluatorBaseTy::VisitCastExpr(E);
3261
3262  case CK_ConstructorConversion:
3263    return Visit(E->getSubExpr());
3264
3265  case CK_DerivedToBase:
3266  case CK_UncheckedDerivedToBase: {
3267    CCValue DerivedObject;
3268    if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
3269      return false;
3270    if (!DerivedObject.isStruct())
3271      return Error(E->getSubExpr());
3272
3273    // Derived-to-base rvalue conversion: just slice off the derived part.
3274    APValue *Value = &DerivedObject;
3275    const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3276    for (CastExpr::path_const_iterator PathI = E->path_begin(),
3277         PathE = E->path_end(); PathI != PathE; ++PathI) {
3278      assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3279      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3280      Value = &Value->getStructBase(getBaseIndex(RD, Base));
3281      RD = Base;
3282    }
3283    Result = *Value;
3284    return true;
3285  }
3286  }
3287}
3288
3289bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3290  const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3291  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3292
3293  if (RD->isUnion()) {
3294    const FieldDecl *Field = E->getInitializedFieldInUnion();
3295    Result = APValue(Field);
3296    if (!Field)
3297      return true;
3298
3299    // If the initializer list for a union does not contain any elements, the
3300    // first element of the union is value-initialized.
3301    ImplicitValueInitExpr VIE(Field->getType());
3302    const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3303
3304    LValue Subobject = This;
3305    HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
3306    return EvaluateConstantExpression(Result.getUnionValue(), Info,
3307                                      Subobject, InitExpr);
3308  }
3309
3310  assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3311         "initializer list for class with base classes");
3312  Result = APValue(APValue::UninitStruct(), 0,
3313                   std::distance(RD->field_begin(), RD->field_end()));
3314  unsigned ElementNo = 0;
3315  bool Success = true;
3316  for (RecordDecl::field_iterator Field = RD->field_begin(),
3317       FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3318    // Anonymous bit-fields are not considered members of the class for
3319    // purposes of aggregate initialization.
3320    if (Field->isUnnamedBitfield())
3321      continue;
3322
3323    LValue Subobject = This;
3324
3325    bool HaveInit = ElementNo < E->getNumInits();
3326
3327    // FIXME: Diagnostics here should point to the end of the initializer
3328    // list, not the start.
3329    HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3330                       *Field, &Layout);
3331
3332    // Perform an implicit value-initialization for members beyond the end of
3333    // the initializer list.
3334    ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3335
3336    if (!EvaluateConstantExpression(
3337          Result.getStructField((*Field)->getFieldIndex()),
3338          Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3339      if (!Info.keepEvaluatingAfterFailure())
3340        return false;
3341      Success = false;
3342    }
3343  }
3344
3345  return Success;
3346}
3347
3348bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3349  const CXXConstructorDecl *FD = E->getConstructor();
3350  bool ZeroInit = E->requiresZeroInitialization();
3351  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3352    // If we've already performed zero-initialization, we're already done.
3353    if (!Result.isUninit())
3354      return true;
3355
3356    if (ZeroInit)
3357      return ZeroInitialization(E);
3358
3359    const CXXRecordDecl *RD = FD->getParent();
3360    if (RD->isUnion())
3361      Result = APValue((FieldDecl*)0);
3362    else
3363      Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3364                       std::distance(RD->field_begin(), RD->field_end()));
3365    return true;
3366  }
3367
3368  const FunctionDecl *Definition = 0;
3369  FD->getBody(Definition);
3370
3371  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3372    return false;
3373
3374  // Avoid materializing a temporary for an elidable copy/move constructor.
3375  if (E->isElidable() && !ZeroInit)
3376    if (const MaterializeTemporaryExpr *ME
3377          = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3378      return Visit(ME->GetTemporaryExpr());
3379
3380  if (ZeroInit && !ZeroInitialization(E))
3381    return false;
3382
3383  llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3384  return HandleConstructorCall(E->getExprLoc(), This, Args,
3385                               cast<CXXConstructorDecl>(Definition), Info,
3386                               Result);
3387}
3388
3389static bool EvaluateRecord(const Expr *E, const LValue &This,
3390                           APValue &Result, EvalInfo &Info) {
3391  assert(E->isRValue() && E->getType()->isRecordType() &&
3392         "can't evaluate expression as a record rvalue");
3393  return RecordExprEvaluator(Info, This, Result).Visit(E);
3394}
3395
3396//===----------------------------------------------------------------------===//
3397// Temporary Evaluation
3398//
3399// Temporaries are represented in the AST as rvalues, but generally behave like
3400// lvalues. The full-object of which the temporary is a subobject is implicitly
3401// materialized so that a reference can bind to it.
3402//===----------------------------------------------------------------------===//
3403namespace {
3404class TemporaryExprEvaluator
3405  : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3406public:
3407  TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3408    LValueExprEvaluatorBaseTy(Info, Result) {}
3409
3410  /// Visit an expression which constructs the value of this temporary.
3411  bool VisitConstructExpr(const Expr *E) {
3412    Result.set(E, Info.CurrentCall);
3413    return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3414                                      Result, E);
3415  }
3416
3417  bool VisitCastExpr(const CastExpr *E) {
3418    switch (E->getCastKind()) {
3419    default:
3420      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3421
3422    case CK_ConstructorConversion:
3423      return VisitConstructExpr(E->getSubExpr());
3424    }
3425  }
3426  bool VisitInitListExpr(const InitListExpr *E) {
3427    return VisitConstructExpr(E);
3428  }
3429  bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3430    return VisitConstructExpr(E);
3431  }
3432  bool VisitCallExpr(const CallExpr *E) {
3433    return VisitConstructExpr(E);
3434  }
3435};
3436} // end anonymous namespace
3437
3438/// Evaluate an expression of record type as a temporary.
3439static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
3440  assert(E->isRValue() && E->getType()->isRecordType());
3441  return TemporaryExprEvaluator(Info, Result).Visit(E);
3442}
3443
3444//===----------------------------------------------------------------------===//
3445// Vector Evaluation
3446//===----------------------------------------------------------------------===//
3447
3448namespace {
3449  class VectorExprEvaluator
3450  : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3451    APValue &Result;
3452  public:
3453
3454    VectorExprEvaluator(EvalInfo &info, APValue &Result)
3455      : ExprEvaluatorBaseTy(info), Result(Result) {}
3456
3457    bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3458      assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3459      // FIXME: remove this APValue copy.
3460      Result = APValue(V.data(), V.size());
3461      return true;
3462    }
3463    bool Success(const CCValue &V, const Expr *E) {
3464      assert(V.isVector());
3465      Result = V;
3466      return true;
3467    }
3468    bool ZeroInitialization(const Expr *E);
3469
3470    bool VisitUnaryReal(const UnaryOperator *E)
3471      { return Visit(E->getSubExpr()); }
3472    bool VisitCastExpr(const CastExpr* E);
3473    bool VisitInitListExpr(const InitListExpr *E);
3474    bool VisitUnaryImag(const UnaryOperator *E);
3475    // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
3476    //                 binary comparisons, binary and/or/xor,
3477    //                 shufflevector, ExtVectorElementExpr
3478  };
3479} // end anonymous namespace
3480
3481static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
3482  assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
3483  return VectorExprEvaluator(Info, Result).Visit(E);
3484}
3485
3486bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3487  const VectorType *VTy = E->getType()->castAs<VectorType>();
3488  unsigned NElts = VTy->getNumElements();
3489
3490  const Expr *SE = E->getSubExpr();
3491  QualType SETy = SE->getType();
3492
3493  switch (E->getCastKind()) {
3494  case CK_VectorSplat: {
3495    APValue Val = APValue();
3496    if (SETy->isIntegerType()) {
3497      APSInt IntResult;
3498      if (!EvaluateInteger(SE, IntResult, Info))
3499         return false;
3500      Val = APValue(IntResult);
3501    } else if (SETy->isRealFloatingType()) {
3502       APFloat F(0.0);
3503       if (!EvaluateFloat(SE, F, Info))
3504         return false;
3505       Val = APValue(F);
3506    } else {
3507      return Error(E);
3508    }
3509
3510    // Splat and create vector APValue.
3511    SmallVector<APValue, 4> Elts(NElts, Val);
3512    return Success(Elts, E);
3513  }
3514  case CK_BitCast: {
3515    // Evaluate the operand into an APInt we can extract from.
3516    llvm::APInt SValInt;
3517    if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3518      return false;
3519    // Extract the elements
3520    QualType EltTy = VTy->getElementType();
3521    unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3522    bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3523    SmallVector<APValue, 4> Elts;
3524    if (EltTy->isRealFloatingType()) {
3525      const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3526      bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3527      unsigned FloatEltSize = EltSize;
3528      if (&Sem == &APFloat::x87DoubleExtended)
3529        FloatEltSize = 80;
3530      for (unsigned i = 0; i < NElts; i++) {
3531        llvm::APInt Elt;
3532        if (BigEndian)
3533          Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3534        else
3535          Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3536        Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3537      }
3538    } else if (EltTy->isIntegerType()) {
3539      for (unsigned i = 0; i < NElts; i++) {
3540        llvm::APInt Elt;
3541        if (BigEndian)
3542          Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3543        else
3544          Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3545        Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3546      }
3547    } else {
3548      return Error(E);
3549    }
3550    return Success(Elts, E);
3551  }
3552  default:
3553    return ExprEvaluatorBaseTy::VisitCastExpr(E);
3554  }
3555}
3556
3557bool
3558VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3559  const VectorType *VT = E->getType()->castAs<VectorType>();
3560  unsigned NumInits = E->getNumInits();
3561  unsigned NumElements = VT->getNumElements();
3562
3563  QualType EltTy = VT->getElementType();
3564  SmallVector<APValue, 4> Elements;
3565
3566  // The number of initializers can be less than the number of
3567  // vector elements. For OpenCL, this can be due to nested vector
3568  // initialization. For GCC compatibility, missing trailing elements
3569  // should be initialized with zeroes.
3570  unsigned CountInits = 0, CountElts = 0;
3571  while (CountElts < NumElements) {
3572    // Handle nested vector initialization.
3573    if (CountInits < NumInits
3574        && E->getInit(CountInits)->getType()->isExtVectorType()) {
3575      APValue v;
3576      if (!EvaluateVector(E->getInit(CountInits), v, Info))
3577        return Error(E);
3578      unsigned vlen = v.getVectorLength();
3579      for (unsigned j = 0; j < vlen; j++)
3580        Elements.push_back(v.getVectorElt(j));
3581      CountElts += vlen;
3582    } else if (EltTy->isIntegerType()) {
3583      llvm::APSInt sInt(32);
3584      if (CountInits < NumInits) {
3585        if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3586          return Error(E);
3587      } else // trailing integer zero.
3588        sInt = Info.Ctx.MakeIntValue(0, EltTy);
3589      Elements.push_back(APValue(sInt));
3590      CountElts++;
3591    } else {
3592      llvm::APFloat f(0.0);
3593      if (CountInits < NumInits) {
3594        if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3595          return Error(E);
3596      } else // trailing float zero.
3597        f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3598      Elements.push_back(APValue(f));
3599      CountElts++;
3600    }
3601    CountInits++;
3602  }
3603  return Success(Elements, E);
3604}
3605
3606bool
3607VectorExprEvaluator::ZeroInitialization(const Expr *E) {
3608  const VectorType *VT = E->getType()->getAs<VectorType>();
3609  QualType EltTy = VT->getElementType();
3610  APValue ZeroElement;
3611  if (EltTy->isIntegerType())
3612    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3613  else
3614    ZeroElement =
3615        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3616
3617  SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
3618  return Success(Elements, E);
3619}
3620
3621bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3622  VisitIgnoredValue(E->getSubExpr());
3623  return ZeroInitialization(E);
3624}
3625
3626//===----------------------------------------------------------------------===//
3627// Array Evaluation
3628//===----------------------------------------------------------------------===//
3629
3630namespace {
3631  class ArrayExprEvaluator
3632  : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
3633    const LValue &This;
3634    APValue &Result;
3635  public:
3636
3637    ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3638      : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
3639
3640    bool Success(const APValue &V, const Expr *E) {
3641      assert(V.isArray() && "Expected array type");
3642      Result = V;
3643      return true;
3644    }
3645
3646    bool ZeroInitialization(const Expr *E) {
3647      const ConstantArrayType *CAT =
3648          Info.Ctx.getAsConstantArrayType(E->getType());
3649      if (!CAT)
3650        return Error(E);
3651
3652      Result = APValue(APValue::UninitArray(), 0,
3653                       CAT->getSize().getZExtValue());
3654      if (!Result.hasArrayFiller()) return true;
3655
3656      // Zero-initialize all elements.
3657      LValue Subobject = This;
3658      Subobject.addArray(Info, E, CAT);
3659      ImplicitValueInitExpr VIE(CAT->getElementType());
3660      return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3661                                        Subobject, &VIE);
3662    }
3663
3664    bool VisitInitListExpr(const InitListExpr *E);
3665    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3666  };
3667} // end anonymous namespace
3668
3669static bool EvaluateArray(const Expr *E, const LValue &This,
3670                          APValue &Result, EvalInfo &Info) {
3671  assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
3672  return ArrayExprEvaluator(Info, This, Result).Visit(E);
3673}
3674
3675bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3676  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3677  if (!CAT)
3678    return Error(E);
3679
3680  // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3681  // an appropriately-typed string literal enclosed in braces.
3682  if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
3683      Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3684    LValue LV;
3685    if (!EvaluateLValue(E->getInit(0), LV, Info))
3686      return false;
3687    uint64_t NumElements = CAT->getSize().getZExtValue();
3688    Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3689
3690    // Copy the string literal into the array. FIXME: Do this better.
3691    LV.addArray(Info, E, CAT);
3692    for (uint64_t I = 0; I < NumElements; ++I) {
3693      CCValue Char;
3694      if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3695                                          CAT->getElementType(), LV, Char) ||
3696          !CheckConstantExpression(Info, E->getInit(0), Char,
3697                                   Result.getArrayInitializedElt(I)) ||
3698          !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
3699                                       CAT->getElementType(), 1))
3700        return false;
3701    }
3702    return true;
3703  }
3704
3705  bool Success = true;
3706
3707  Result = APValue(APValue::UninitArray(), E->getNumInits(),
3708                   CAT->getSize().getZExtValue());
3709  LValue Subobject = This;
3710  Subobject.addArray(Info, E, CAT);
3711  unsigned Index = 0;
3712  for (InitListExpr::const_iterator I = E->begin(), End = E->end();
3713       I != End; ++I, ++Index) {
3714    if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3715                                    Info, Subobject, cast<Expr>(*I)) ||
3716        !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3717                                     CAT->getElementType(), 1)) {
3718      if (!Info.keepEvaluatingAfterFailure())
3719        return false;
3720      Success = false;
3721    }
3722  }
3723
3724  if (!Result.hasArrayFiller()) return Success;
3725  assert(E->hasArrayFiller() && "no array filler for incomplete init list");
3726  // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3727  // but sometimes does:
3728  //   struct S { constexpr S() : p(&p) {} void *p; };
3729  //   S s[10] = {};
3730  return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3731                                    Subobject, E->getArrayFiller()) && Success;
3732}
3733
3734bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3735  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3736  if (!CAT)
3737    return Error(E);
3738
3739  bool HadZeroInit = !Result.isUninit();
3740  if (!HadZeroInit)
3741    Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3742  if (!Result.hasArrayFiller())
3743    return true;
3744
3745  const CXXConstructorDecl *FD = E->getConstructor();
3746
3747  bool ZeroInit = E->requiresZeroInitialization();
3748  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3749    if (HadZeroInit)
3750      return true;
3751
3752    if (ZeroInit) {
3753      LValue Subobject = This;
3754      Subobject.addArray(Info, E, CAT);
3755      ImplicitValueInitExpr VIE(CAT->getElementType());
3756      return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3757                                        Subobject, &VIE);
3758    }
3759
3760    const CXXRecordDecl *RD = FD->getParent();
3761    if (RD->isUnion())
3762      Result.getArrayFiller() = APValue((FieldDecl*)0);
3763    else
3764      Result.getArrayFiller() =
3765          APValue(APValue::UninitStruct(), RD->getNumBases(),
3766                  std::distance(RD->field_begin(), RD->field_end()));
3767    return true;
3768  }
3769
3770  const FunctionDecl *Definition = 0;
3771  FD->getBody(Definition);
3772
3773  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3774    return false;
3775
3776  // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3777  // but sometimes does:
3778  //   struct S { constexpr S() : p(&p) {} void *p; };
3779  //   S s[10];
3780  LValue Subobject = This;
3781  Subobject.addArray(Info, E, CAT);
3782
3783  if (ZeroInit && !HadZeroInit) {
3784    ImplicitValueInitExpr VIE(CAT->getElementType());
3785    if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3786                                    &VIE))
3787      return false;
3788  }
3789
3790  llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3791  return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
3792                               cast<CXXConstructorDecl>(Definition),
3793                               Info, Result.getArrayFiller());
3794}
3795
3796//===----------------------------------------------------------------------===//
3797// Integer Evaluation
3798//
3799// As a GNU extension, we support casting pointers to sufficiently-wide integer
3800// types and back in constant folding. Integer values are thus represented
3801// either as an integer-valued APValue, or as an lvalue-valued APValue.
3802//===----------------------------------------------------------------------===//
3803
3804namespace {
3805class IntExprEvaluator
3806  : public ExprEvaluatorBase<IntExprEvaluator, bool> {
3807  CCValue &Result;
3808public:
3809  IntExprEvaluator(EvalInfo &info, CCValue &result)
3810    : ExprEvaluatorBaseTy(info), Result(result) {}
3811
3812  bool Success(const llvm::APSInt &SI, const Expr *E) {
3813    assert(E->getType()->isIntegralOrEnumerationType() &&
3814           "Invalid evaluation result.");
3815    assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
3816           "Invalid evaluation result.");
3817    assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3818           "Invalid evaluation result.");
3819    Result = CCValue(SI);
3820    return true;
3821  }
3822
3823  bool Success(const llvm::APInt &I, const Expr *E) {
3824    assert(E->getType()->isIntegralOrEnumerationType() &&
3825           "Invalid evaluation result.");
3826    assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3827           "Invalid evaluation result.");
3828    Result = CCValue(APSInt(I));
3829    Result.getInt().setIsUnsigned(
3830                            E->getType()->isUnsignedIntegerOrEnumerationType());
3831    return true;
3832  }
3833
3834  bool Success(uint64_t Value, const Expr *E) {
3835    assert(E->getType()->isIntegralOrEnumerationType() &&
3836           "Invalid evaluation result.");
3837    Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
3838    return true;
3839  }
3840
3841  bool Success(CharUnits Size, const Expr *E) {
3842    return Success(Size.getQuantity(), E);
3843  }
3844
3845  bool Success(const CCValue &V, const Expr *E) {
3846    if (V.isLValue() || V.isAddrLabelDiff()) {
3847      Result = V;
3848      return true;
3849    }
3850    return Success(V.getInt(), E);
3851  }
3852
3853  bool ZeroInitialization(const Expr *E) { return Success(0, E); }
3854
3855  //===--------------------------------------------------------------------===//
3856  //                            Visitor Methods
3857  //===--------------------------------------------------------------------===//
3858
3859  bool VisitIntegerLiteral(const IntegerLiteral *E) {
3860    return Success(E->getValue(), E);
3861  }
3862  bool VisitCharacterLiteral(const CharacterLiteral *E) {
3863    return Success(E->getValue(), E);
3864  }
3865
3866  bool CheckReferencedDecl(const Expr *E, const Decl *D);
3867  bool VisitDeclRefExpr(const DeclRefExpr *E) {
3868    if (CheckReferencedDecl(E, E->getDecl()))
3869      return true;
3870
3871    return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
3872  }
3873  bool VisitMemberExpr(const MemberExpr *E) {
3874    if (CheckReferencedDecl(E, E->getMemberDecl())) {
3875      VisitIgnoredValue(E->getBase());
3876      return true;
3877    }
3878
3879    return ExprEvaluatorBaseTy::VisitMemberExpr(E);
3880  }
3881
3882  bool VisitCallExpr(const CallExpr *E);
3883  bool VisitBinaryOperator(const BinaryOperator *E);
3884  bool VisitOffsetOfExpr(const OffsetOfExpr *E);
3885  bool VisitUnaryOperator(const UnaryOperator *E);
3886
3887  bool VisitCastExpr(const CastExpr* E);
3888  bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
3889
3890  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
3891    return Success(E->getValue(), E);
3892  }
3893
3894  // Note, GNU defines __null as an integer, not a pointer.
3895  bool VisitGNUNullExpr(const GNUNullExpr *E) {
3896    return ZeroInitialization(E);
3897  }
3898
3899  bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
3900    return Success(E->getValue(), E);
3901  }
3902
3903  bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3904    return Success(E->getValue(), E);
3905  }
3906
3907  bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3908    return Success(E->getValue(), E);
3909  }
3910
3911  bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3912    return Success(E->getValue(), E);
3913  }
3914
3915  bool VisitUnaryReal(const UnaryOperator *E);
3916  bool VisitUnaryImag(const UnaryOperator *E);
3917
3918  bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
3919  bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
3920
3921private:
3922  CharUnits GetAlignOfExpr(const Expr *E);
3923  CharUnits GetAlignOfType(QualType T);
3924  static QualType GetObjectType(APValue::LValueBase B);
3925  bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
3926  // FIXME: Missing: array subscript of vector, member of vector
3927};
3928} // end anonymous namespace
3929
3930/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3931/// produce either the integer value or a pointer.
3932///
3933/// GCC has a heinous extension which folds casts between pointer types and
3934/// pointer-sized integral types. We support this by allowing the evaluation of
3935/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3936/// Some simple arithmetic on such values is supported (they are treated much
3937/// like char*).
3938static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
3939                                    EvalInfo &Info) {
3940  assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
3941  return IntExprEvaluator(Info, Result).Visit(E);
3942}
3943
3944static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
3945  CCValue Val;
3946  if (!EvaluateIntegerOrLValue(E, Val, Info))
3947    return false;
3948  if (!Val.isInt()) {
3949    // FIXME: It would be better to produce the diagnostic for casting
3950    //        a pointer to an integer.
3951    Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
3952    return false;
3953  }
3954  Result = Val.getInt();
3955  return true;
3956}
3957
3958/// Check whether the given declaration can be directly converted to an integral
3959/// rvalue. If not, no diagnostic is produced; there are other things we can
3960/// try.
3961bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
3962  // Enums are integer constant exprs.
3963  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
3964    // Check for signedness/width mismatches between E type and ECD value.
3965    bool SameSign = (ECD->getInitVal().isSigned()
3966                     == E->getType()->isSignedIntegerOrEnumerationType());
3967    bool SameWidth = (ECD->getInitVal().getBitWidth()
3968                      == Info.Ctx.getIntWidth(E->getType()));
3969    if (SameSign && SameWidth)
3970      return Success(ECD->getInitVal(), E);
3971    else {
3972      // Get rid of mismatch (otherwise Success assertions will fail)
3973      // by computing a new value matching the type of E.
3974      llvm::APSInt Val = ECD->getInitVal();
3975      if (!SameSign)
3976        Val.setIsSigned(!ECD->getInitVal().isSigned());
3977      if (!SameWidth)
3978        Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3979      return Success(Val, E);
3980    }
3981  }
3982  return false;
3983}
3984
3985/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3986/// as GCC.
3987static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3988  // The following enum mimics the values returned by GCC.
3989  // FIXME: Does GCC differ between lvalue and rvalue references here?
3990  enum gcc_type_class {
3991    no_type_class = -1,
3992    void_type_class, integer_type_class, char_type_class,
3993    enumeral_type_class, boolean_type_class,
3994    pointer_type_class, reference_type_class, offset_type_class,
3995    real_type_class, complex_type_class,
3996    function_type_class, method_type_class,
3997    record_type_class, union_type_class,
3998    array_type_class, string_type_class,
3999    lang_type_class
4000  };
4001
4002  // If no argument was supplied, default to "no_type_class". This isn't
4003  // ideal, however it is what gcc does.
4004  if (E->getNumArgs() == 0)
4005    return no_type_class;
4006
4007  QualType ArgTy = E->getArg(0)->getType();
4008  if (ArgTy->isVoidType())
4009    return void_type_class;
4010  else if (ArgTy->isEnumeralType())
4011    return enumeral_type_class;
4012  else if (ArgTy->isBooleanType())
4013    return boolean_type_class;
4014  else if (ArgTy->isCharType())
4015    return string_type_class; // gcc doesn't appear to use char_type_class
4016  else if (ArgTy->isIntegerType())
4017    return integer_type_class;
4018  else if (ArgTy->isPointerType())
4019    return pointer_type_class;
4020  else if (ArgTy->isReferenceType())
4021    return reference_type_class;
4022  else if (ArgTy->isRealType())
4023    return real_type_class;
4024  else if (ArgTy->isComplexType())
4025    return complex_type_class;
4026  else if (ArgTy->isFunctionType())
4027    return function_type_class;
4028  else if (ArgTy->isStructureOrClassType())
4029    return record_type_class;
4030  else if (ArgTy->isUnionType())
4031    return union_type_class;
4032  else if (ArgTy->isArrayType())
4033    return array_type_class;
4034  else if (ArgTy->isUnionType())
4035    return union_type_class;
4036  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
4037    llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
4038}
4039
4040/// EvaluateBuiltinConstantPForLValue - Determine the result of
4041/// __builtin_constant_p when applied to the given lvalue.
4042///
4043/// An lvalue is only "constant" if it is a pointer or reference to the first
4044/// character of a string literal.
4045template<typename LValue>
4046static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4047  const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4048  return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4049}
4050
4051/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4052/// GCC as we can manage.
4053static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4054  QualType ArgType = Arg->getType();
4055
4056  // __builtin_constant_p always has one operand. The rules which gcc follows
4057  // are not precisely documented, but are as follows:
4058  //
4059  //  - If the operand is of integral, floating, complex or enumeration type,
4060  //    and can be folded to a known value of that type, it returns 1.
4061  //  - If the operand and can be folded to a pointer to the first character
4062  //    of a string literal (or such a pointer cast to an integral type), it
4063  //    returns 1.
4064  //
4065  // Otherwise, it returns 0.
4066  //
4067  // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4068  // its support for this does not currently work.
4069  if (ArgType->isIntegralOrEnumerationType()) {
4070    Expr::EvalResult Result;
4071    if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4072      return false;
4073
4074    APValue &V = Result.Val;
4075    if (V.getKind() == APValue::Int)
4076      return true;
4077
4078    return EvaluateBuiltinConstantPForLValue(V);
4079  } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4080    return Arg->isEvaluatable(Ctx);
4081  } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4082    LValue LV;
4083    Expr::EvalStatus Status;
4084    EvalInfo Info(Ctx, Status);
4085    if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4086                          : EvaluatePointer(Arg, LV, Info)) &&
4087        !Status.HasSideEffects)
4088      return EvaluateBuiltinConstantPForLValue(LV);
4089  }
4090
4091  // Anything else isn't considered to be sufficiently constant.
4092  return false;
4093}
4094
4095/// Retrieves the "underlying object type" of the given expression,
4096/// as used by __builtin_object_size.
4097QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4098  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4099    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4100      return VD->getType();
4101  } else if (const Expr *E = B.get<const Expr*>()) {
4102    if (isa<CompoundLiteralExpr>(E))
4103      return E->getType();
4104  }
4105
4106  return QualType();
4107}
4108
4109bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
4110  // TODO: Perhaps we should let LLVM lower this?
4111  LValue Base;
4112  if (!EvaluatePointer(E->getArg(0), Base, Info))
4113    return false;
4114
4115  // If we can prove the base is null, lower to zero now.
4116  if (!Base.getLValueBase()) return Success(0, E);
4117
4118  QualType T = GetObjectType(Base.getLValueBase());
4119  if (T.isNull() ||
4120      T->isIncompleteType() ||
4121      T->isFunctionType() ||
4122      T->isVariablyModifiedType() ||
4123      T->isDependentType())
4124    return Error(E);
4125
4126  CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4127  CharUnits Offset = Base.getLValueOffset();
4128
4129  if (!Offset.isNegative() && Offset <= Size)
4130    Size -= Offset;
4131  else
4132    Size = CharUnits::Zero();
4133  return Success(Size, E);
4134}
4135
4136bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
4137  switch (E->isBuiltinCall()) {
4138  default:
4139    return ExprEvaluatorBaseTy::VisitCallExpr(E);
4140
4141  case Builtin::BI__builtin_object_size: {
4142    if (TryEvaluateBuiltinObjectSize(E))
4143      return true;
4144
4145    // If evaluating the argument has side-effects we can't determine
4146    // the size of the object and lower it to unknown now.
4147    if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
4148      if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
4149        return Success(-1ULL, E);
4150      return Success(0, E);
4151    }
4152
4153    return Error(E);
4154  }
4155
4156  case Builtin::BI__builtin_classify_type:
4157    return Success(EvaluateBuiltinClassifyType(E), E);
4158
4159  case Builtin::BI__builtin_constant_p:
4160    return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
4161
4162  case Builtin::BI__builtin_eh_return_data_regno: {
4163    int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
4164    Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
4165    return Success(Operand, E);
4166  }
4167
4168  case Builtin::BI__builtin_expect:
4169    return Visit(E->getArg(0));
4170
4171  case Builtin::BIstrlen:
4172    // A call to strlen is not a constant expression.
4173    if (Info.getLangOpts().CPlusPlus0x)
4174      Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4175        << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4176    else
4177      Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4178    // Fall through.
4179  case Builtin::BI__builtin_strlen:
4180    // As an extension, we support strlen() and __builtin_strlen() as constant
4181    // expressions when the argument is a string literal.
4182    if (const StringLiteral *S
4183               = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4184      // The string literal may have embedded null characters. Find the first
4185      // one and truncate there.
4186      StringRef Str = S->getString();
4187      StringRef::size_type Pos = Str.find(0);
4188      if (Pos != StringRef::npos)
4189        Str = Str.substr(0, Pos);
4190
4191      return Success(Str.size(), E);
4192    }
4193
4194    return Error(E);
4195
4196  case Builtin::BI__atomic_is_lock_free: {
4197    APSInt SizeVal;
4198    if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4199      return false;
4200
4201    // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4202    // of two less than the maximum inline atomic width, we know it is
4203    // lock-free.  If the size isn't a power of two, or greater than the
4204    // maximum alignment where we promote atomics, we know it is not lock-free
4205    // (at least not in the sense of atomic_is_lock_free).  Otherwise,
4206    // the answer can only be determined at runtime; for example, 16-byte
4207    // atomics have lock-free implementations on some, but not all,
4208    // x86-64 processors.
4209
4210    // Check power-of-two.
4211    CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4212    if (!Size.isPowerOfTwo())
4213#if 0
4214      // FIXME: Suppress this folding until the ABI for the promotion width
4215      // settles.
4216      return Success(0, E);
4217#else
4218      return Error(E);
4219#endif
4220
4221#if 0
4222    // Check against promotion width.
4223    // FIXME: Suppress this folding until the ABI for the promotion width
4224    // settles.
4225    unsigned PromoteWidthBits =
4226        Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4227    if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4228      return Success(0, E);
4229#endif
4230
4231    // Check against inlining width.
4232    unsigned InlineWidthBits =
4233        Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4234    if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4235      return Success(1, E);
4236
4237    return Error(E);
4238  }
4239  }
4240}
4241
4242static bool HasSameBase(const LValue &A, const LValue &B) {
4243  if (!A.getLValueBase())
4244    return !B.getLValueBase();
4245  if (!B.getLValueBase())
4246    return false;
4247
4248  if (A.getLValueBase().getOpaqueValue() !=
4249      B.getLValueBase().getOpaqueValue()) {
4250    const Decl *ADecl = GetLValueBaseDecl(A);
4251    if (!ADecl)
4252      return false;
4253    const Decl *BDecl = GetLValueBaseDecl(B);
4254    if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
4255      return false;
4256  }
4257
4258  return IsGlobalLValue(A.getLValueBase()) ||
4259         A.getLValueFrame() == B.getLValueFrame();
4260}
4261
4262/// Perform the given integer operation, which is known to need at most BitWidth
4263/// bits, and check for overflow in the original type (if that type was not an
4264/// unsigned type).
4265template<typename Operation>
4266static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4267                                   const APSInt &LHS, const APSInt &RHS,
4268                                   unsigned BitWidth, Operation Op) {
4269  if (LHS.isUnsigned())
4270    return Op(LHS, RHS);
4271
4272  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4273  APSInt Result = Value.trunc(LHS.getBitWidth());
4274  if (Result.extend(BitWidth) != Value)
4275    HandleOverflow(Info, E, Value, E->getType());
4276  return Result;
4277}
4278
4279bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4280  if (E->isAssignmentOp())
4281    return Error(E);
4282
4283  if (E->getOpcode() == BO_Comma) {
4284    VisitIgnoredValue(E->getLHS());
4285    return Visit(E->getRHS());
4286  }
4287
4288  if (E->isLogicalOp()) {
4289    // These need to be handled specially because the operands aren't
4290    // necessarily integral
4291    bool lhsResult, rhsResult;
4292
4293    if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4294      // We were able to evaluate the LHS, see if we can get away with not
4295      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4296      if (lhsResult == (E->getOpcode() == BO_LOr))
4297        return Success(lhsResult, E);
4298
4299      if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4300        if (E->getOpcode() == BO_LOr)
4301          return Success(lhsResult || rhsResult, E);
4302        else
4303          return Success(lhsResult && rhsResult, E);
4304      }
4305    } else {
4306      // FIXME: If both evaluations fail, we should produce the diagnostic from
4307      // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4308      // less clear how to diagnose this.
4309      if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4310        // We can't evaluate the LHS; however, sometimes the result
4311        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4312        if (rhsResult == (E->getOpcode() == BO_LOr)) {
4313          // Since we weren't able to evaluate the left hand side, it
4314          // must have had side effects.
4315          Info.EvalStatus.HasSideEffects = true;
4316
4317          return Success(rhsResult, E);
4318        }
4319      }
4320    }
4321
4322    return false;
4323  }
4324
4325  QualType LHSTy = E->getLHS()->getType();
4326  QualType RHSTy = E->getRHS()->getType();
4327
4328  if (LHSTy->isAnyComplexType()) {
4329    assert(RHSTy->isAnyComplexType() && "Invalid comparison");
4330    ComplexValue LHS, RHS;
4331
4332    bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4333    if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4334      return false;
4335
4336    if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
4337      return false;
4338
4339    if (LHS.isComplexFloat()) {
4340      APFloat::cmpResult CR_r =
4341        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
4342      APFloat::cmpResult CR_i =
4343        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4344
4345      if (E->getOpcode() == BO_EQ)
4346        return Success((CR_r == APFloat::cmpEqual &&
4347                        CR_i == APFloat::cmpEqual), E);
4348      else {
4349        assert(E->getOpcode() == BO_NE &&
4350               "Invalid complex comparison.");
4351        return Success(((CR_r == APFloat::cmpGreaterThan ||
4352                         CR_r == APFloat::cmpLessThan ||
4353                         CR_r == APFloat::cmpUnordered) ||
4354                        (CR_i == APFloat::cmpGreaterThan ||
4355                         CR_i == APFloat::cmpLessThan ||
4356                         CR_i == APFloat::cmpUnordered)), E);
4357      }
4358    } else {
4359      if (E->getOpcode() == BO_EQ)
4360        return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4361                        LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4362      else {
4363        assert(E->getOpcode() == BO_NE &&
4364               "Invalid compex comparison.");
4365        return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4366                        LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4367      }
4368    }
4369  }
4370
4371  if (LHSTy->isRealFloatingType() &&
4372      RHSTy->isRealFloatingType()) {
4373    APFloat RHS(0.0), LHS(0.0);
4374
4375    bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4376    if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4377      return false;
4378
4379    if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
4380      return false;
4381
4382    APFloat::cmpResult CR = LHS.compare(RHS);
4383
4384    switch (E->getOpcode()) {
4385    default:
4386      llvm_unreachable("Invalid binary operator!");
4387    case BO_LT:
4388      return Success(CR == APFloat::cmpLessThan, E);
4389    case BO_GT:
4390      return Success(CR == APFloat::cmpGreaterThan, E);
4391    case BO_LE:
4392      return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
4393    case BO_GE:
4394      return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
4395                     E);
4396    case BO_EQ:
4397      return Success(CR == APFloat::cmpEqual, E);
4398    case BO_NE:
4399      return Success(CR == APFloat::cmpGreaterThan
4400                     || CR == APFloat::cmpLessThan
4401                     || CR == APFloat::cmpUnordered, E);
4402    }
4403  }
4404
4405  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4406    if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
4407      LValue LHSValue, RHSValue;
4408
4409      bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4410      if (!LHSOK && Info.keepEvaluatingAfterFailure())
4411        return false;
4412
4413      if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4414        return false;
4415
4416      // Reject differing bases from the normal codepath; we special-case
4417      // comparisons to null.
4418      if (!HasSameBase(LHSValue, RHSValue)) {
4419        if (E->getOpcode() == BO_Sub) {
4420          // Handle &&A - &&B.
4421          if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4422            return false;
4423          const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4424          const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4425          if (!LHSExpr || !RHSExpr)
4426            return false;
4427          const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4428          const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4429          if (!LHSAddrExpr || !RHSAddrExpr)
4430            return false;
4431          // Make sure both labels come from the same function.
4432          if (LHSAddrExpr->getLabel()->getDeclContext() !=
4433              RHSAddrExpr->getLabel()->getDeclContext())
4434            return false;
4435          Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4436          return true;
4437        }
4438        // Inequalities and subtractions between unrelated pointers have
4439        // unspecified or undefined behavior.
4440        if (!E->isEqualityOp())
4441          return Error(E);
4442        // A constant address may compare equal to the address of a symbol.
4443        // The one exception is that address of an object cannot compare equal
4444        // to a null pointer constant.
4445        if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4446            (!RHSValue.Base && !RHSValue.Offset.isZero()))
4447          return Error(E);
4448        // It's implementation-defined whether distinct literals will have
4449        // distinct addresses. In clang, the result of such a comparison is
4450        // unspecified, so it is not a constant expression. However, we do know
4451        // that the address of a literal will be non-null.
4452        if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4453            LHSValue.Base && RHSValue.Base)
4454          return Error(E);
4455        // We can't tell whether weak symbols will end up pointing to the same
4456        // object.
4457        if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
4458          return Error(E);
4459        // Pointers with different bases cannot represent the same object.
4460        // (Note that clang defaults to -fmerge-all-constants, which can
4461        // lead to inconsistent results for comparisons involving the address
4462        // of a constant; this generally doesn't matter in practice.)
4463        return Success(E->getOpcode() == BO_NE, E);
4464      }
4465
4466      const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4467      const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4468
4469      SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4470      SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4471
4472      if (E->getOpcode() == BO_Sub) {
4473        // C++11 [expr.add]p6:
4474        //   Unless both pointers point to elements of the same array object, or
4475        //   one past the last element of the array object, the behavior is
4476        //   undefined.
4477        if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4478            !AreElementsOfSameArray(getType(LHSValue.Base),
4479                                    LHSDesignator, RHSDesignator))
4480          CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4481
4482        QualType Type = E->getLHS()->getType();
4483        QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
4484
4485        CharUnits ElementSize;
4486        if (!HandleSizeof(Info, ElementType, ElementSize))
4487          return false;
4488
4489        // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4490        // and produce incorrect results when it overflows. Such behavior
4491        // appears to be non-conforming, but is common, so perhaps we should
4492        // assume the standard intended for such cases to be undefined behavior
4493        // and check for them.
4494
4495        // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4496        // overflow in the final conversion to ptrdiff_t.
4497        APSInt LHS(
4498          llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4499        APSInt RHS(
4500          llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4501        APSInt ElemSize(
4502          llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4503        APSInt TrueResult = (LHS - RHS) / ElemSize;
4504        APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4505
4506        if (Result.extend(65) != TrueResult)
4507          HandleOverflow(Info, E, TrueResult, E->getType());
4508        return Success(Result, E);
4509      }
4510
4511      // C++11 [expr.rel]p3:
4512      //   Pointers to void (after pointer conversions) can be compared, with a
4513      //   result defined as follows: If both pointers represent the same
4514      //   address or are both the null pointer value, the result is true if the
4515      //   operator is <= or >= and false otherwise; otherwise the result is
4516      //   unspecified.
4517      // We interpret this as applying to pointers to *cv* void.
4518      if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
4519          E->isRelationalOp())
4520        CCEDiag(E, diag::note_constexpr_void_comparison);
4521
4522      // C++11 [expr.rel]p2:
4523      // - If two pointers point to non-static data members of the same object,
4524      //   or to subobjects or array elements fo such members, recursively, the
4525      //   pointer to the later declared member compares greater provided the
4526      //   two members have the same access control and provided their class is
4527      //   not a union.
4528      //   [...]
4529      // - Otherwise pointer comparisons are unspecified.
4530      if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4531          E->isRelationalOp()) {
4532        bool WasArrayIndex;
4533        unsigned Mismatch =
4534          FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4535                                 RHSDesignator, WasArrayIndex);
4536        // At the point where the designators diverge, the comparison has a
4537        // specified value if:
4538        //  - we are comparing array indices
4539        //  - we are comparing fields of a union, or fields with the same access
4540        // Otherwise, the result is unspecified and thus the comparison is not a
4541        // constant expression.
4542        if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4543            Mismatch < RHSDesignator.Entries.size()) {
4544          const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4545          const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4546          if (!LF && !RF)
4547            CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4548          else if (!LF)
4549            CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4550              << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4551              << RF->getParent() << RF;
4552          else if (!RF)
4553            CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4554              << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4555              << LF->getParent() << LF;
4556          else if (!LF->getParent()->isUnion() &&
4557                   LF->getAccess() != RF->getAccess())
4558            CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4559              << LF << LF->getAccess() << RF << RF->getAccess()
4560              << LF->getParent();
4561        }
4562      }
4563
4564      switch (E->getOpcode()) {
4565      default: llvm_unreachable("missing comparison operator");
4566      case BO_LT: return Success(LHSOffset < RHSOffset, E);
4567      case BO_GT: return Success(LHSOffset > RHSOffset, E);
4568      case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4569      case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4570      case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4571      case BO_NE: return Success(LHSOffset != RHSOffset, E);
4572      }
4573    }
4574  }
4575
4576  if (LHSTy->isMemberPointerType()) {
4577    assert(E->isEqualityOp() && "unexpected member pointer operation");
4578    assert(RHSTy->isMemberPointerType() && "invalid comparison");
4579
4580    MemberPtr LHSValue, RHSValue;
4581
4582    bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4583    if (!LHSOK && Info.keepEvaluatingAfterFailure())
4584      return false;
4585
4586    if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4587      return false;
4588
4589    // C++11 [expr.eq]p2:
4590    //   If both operands are null, they compare equal. Otherwise if only one is
4591    //   null, they compare unequal.
4592    if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4593      bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4594      return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4595    }
4596
4597    //   Otherwise if either is a pointer to a virtual member function, the
4598    //   result is unspecified.
4599    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4600      if (MD->isVirtual())
4601        CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4602    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4603      if (MD->isVirtual())
4604        CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4605
4606    //   Otherwise they compare equal if and only if they would refer to the
4607    //   same member of the same most derived object or the same subobject if
4608    //   they were dereferenced with a hypothetical object of the associated
4609    //   class type.
4610    bool Equal = LHSValue == RHSValue;
4611    return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4612  }
4613
4614  if (!LHSTy->isIntegralOrEnumerationType() ||
4615      !RHSTy->isIntegralOrEnumerationType()) {
4616    // We can't continue from here for non-integral types.
4617    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4618  }
4619
4620  // The LHS of a constant expr is always evaluated and needed.
4621  CCValue LHSVal;
4622
4623  bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4624  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4625    return false;
4626
4627  if (!Visit(E->getRHS()) || !LHSOK)
4628    return false;
4629
4630  CCValue &RHSVal = Result;
4631
4632  // Handle cases like (unsigned long)&a + 4.
4633  if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4634    CharUnits AdditionalOffset = CharUnits::fromQuantity(
4635                                     RHSVal.getInt().getZExtValue());
4636    if (E->getOpcode() == BO_Add)
4637      LHSVal.getLValueOffset() += AdditionalOffset;
4638    else
4639      LHSVal.getLValueOffset() -= AdditionalOffset;
4640    Result = LHSVal;
4641    return true;
4642  }
4643
4644  // Handle cases like 4 + (unsigned long)&a
4645  if (E->getOpcode() == BO_Add &&
4646        RHSVal.isLValue() && LHSVal.isInt()) {
4647    RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4648                                    LHSVal.getInt().getZExtValue());
4649    // Note that RHSVal is Result.
4650    return true;
4651  }
4652
4653  if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4654    // Handle (intptr_t)&&A - (intptr_t)&&B.
4655    if (!LHSVal.getLValueOffset().isZero() ||
4656        !RHSVal.getLValueOffset().isZero())
4657      return false;
4658    const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4659    const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4660    if (!LHSExpr || !RHSExpr)
4661      return false;
4662    const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4663    const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4664    if (!LHSAddrExpr || !RHSAddrExpr)
4665      return false;
4666    // Make sure both labels come from the same function.
4667    if (LHSAddrExpr->getLabel()->getDeclContext() !=
4668        RHSAddrExpr->getLabel()->getDeclContext())
4669      return false;
4670    Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4671    return true;
4672  }
4673
4674  // All the following cases expect both operands to be an integer
4675  if (!LHSVal.isInt() || !RHSVal.isInt())
4676    return Error(E);
4677
4678  APSInt &LHS = LHSVal.getInt();
4679  APSInt &RHS = RHSVal.getInt();
4680
4681  switch (E->getOpcode()) {
4682  default:
4683    return Error(E);
4684  case BO_Mul:
4685    return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4686                                        LHS.getBitWidth() * 2,
4687                                        std::multiplies<APSInt>()), E);
4688  case BO_Add:
4689    return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4690                                        LHS.getBitWidth() + 1,
4691                                        std::plus<APSInt>()), E);
4692  case BO_Sub:
4693    return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4694                                        LHS.getBitWidth() + 1,
4695                                        std::minus<APSInt>()), E);
4696  case BO_And: return Success(LHS & RHS, E);
4697  case BO_Xor: return Success(LHS ^ RHS, E);
4698  case BO_Or:  return Success(LHS | RHS, E);
4699  case BO_Div:
4700  case BO_Rem:
4701    if (RHS == 0)
4702      return Error(E, diag::note_expr_divide_by_zero);
4703    // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4704    // actually undefined behavior in C++11 due to a language defect.
4705    if (RHS.isNegative() && RHS.isAllOnesValue() &&
4706        LHS.isSigned() && LHS.isMinSignedValue())
4707      HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4708    return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
4709  case BO_Shl: {
4710    // During constant-folding, a negative shift is an opposite shift. Such a
4711    // shift is not a constant expression.
4712    if (RHS.isSigned() && RHS.isNegative()) {
4713      CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4714      RHS = -RHS;
4715      goto shift_right;
4716    }
4717
4718  shift_left:
4719    // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4720    // shifted type.
4721    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4722    if (SA != RHS) {
4723      CCEDiag(E, diag::note_constexpr_large_shift)
4724        << RHS << E->getType() << LHS.getBitWidth();
4725    } else if (LHS.isSigned()) {
4726      // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4727      // operand, and must not overflow the corresponding unsigned type.
4728      if (LHS.isNegative())
4729        CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4730      else if (LHS.countLeadingZeros() < SA)
4731        CCEDiag(E, diag::note_constexpr_lshift_discards);
4732    }
4733
4734    return Success(LHS << SA, E);
4735  }
4736  case BO_Shr: {
4737    // During constant-folding, a negative shift is an opposite shift. Such a
4738    // shift is not a constant expression.
4739    if (RHS.isSigned() && RHS.isNegative()) {
4740      CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4741      RHS = -RHS;
4742      goto shift_left;
4743    }
4744
4745  shift_right:
4746    // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4747    // shifted type.
4748    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4749    if (SA != RHS)
4750      CCEDiag(E, diag::note_constexpr_large_shift)
4751        << RHS << E->getType() << LHS.getBitWidth();
4752
4753    return Success(LHS >> SA, E);
4754  }
4755
4756  case BO_LT: return Success(LHS < RHS, E);
4757  case BO_GT: return Success(LHS > RHS, E);
4758  case BO_LE: return Success(LHS <= RHS, E);
4759  case BO_GE: return Success(LHS >= RHS, E);
4760  case BO_EQ: return Success(LHS == RHS, E);
4761  case BO_NE: return Success(LHS != RHS, E);
4762  }
4763}
4764
4765CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
4766  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4767  //   the result is the size of the referenced type."
4768  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4769  //   result shall be the alignment of the referenced type."
4770  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4771    T = Ref->getPointeeType();
4772
4773  // __alignof is defined to return the preferred alignment.
4774  return Info.Ctx.toCharUnitsFromBits(
4775    Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4776}
4777
4778CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
4779  E = E->IgnoreParens();
4780
4781  // alignof decl is always accepted, even if it doesn't make sense: we default
4782  // to 1 in those cases.
4783  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4784    return Info.Ctx.getDeclAlign(DRE->getDecl(),
4785                                 /*RefAsPointee*/true);
4786
4787  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4788    return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4789                                 /*RefAsPointee*/true);
4790
4791  return GetAlignOfType(E->getType());
4792}
4793
4794
4795/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4796/// a result as the expression's type.
4797bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4798                                    const UnaryExprOrTypeTraitExpr *E) {
4799  switch(E->getKind()) {
4800  case UETT_AlignOf: {
4801    if (E->isArgumentType())
4802      return Success(GetAlignOfType(E->getArgumentType()), E);
4803    else
4804      return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
4805  }
4806
4807  case UETT_VecStep: {
4808    QualType Ty = E->getTypeOfArgument();
4809
4810    if (Ty->isVectorType()) {
4811      unsigned n = Ty->getAs<VectorType>()->getNumElements();
4812
4813      // The vec_step built-in functions that take a 3-component
4814      // vector return 4. (OpenCL 1.1 spec 6.11.12)
4815      if (n == 3)
4816        n = 4;
4817
4818      return Success(n, E);
4819    } else
4820      return Success(1, E);
4821  }
4822
4823  case UETT_SizeOf: {
4824    QualType SrcTy = E->getTypeOfArgument();
4825    // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4826    //   the result is the size of the referenced type."
4827    // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4828    //   result shall be the alignment of the referenced type."
4829    if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4830      SrcTy = Ref->getPointeeType();
4831
4832    CharUnits Sizeof;
4833    if (!HandleSizeof(Info, SrcTy, Sizeof))
4834      return false;
4835    return Success(Sizeof, E);
4836  }
4837  }
4838
4839  llvm_unreachable("unknown expr/type trait");
4840}
4841
4842bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
4843  CharUnits Result;
4844  unsigned n = OOE->getNumComponents();
4845  if (n == 0)
4846    return Error(OOE);
4847  QualType CurrentType = OOE->getTypeSourceInfo()->getType();
4848  for (unsigned i = 0; i != n; ++i) {
4849    OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4850    switch (ON.getKind()) {
4851    case OffsetOfExpr::OffsetOfNode::Array: {
4852      const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
4853      APSInt IdxResult;
4854      if (!EvaluateInteger(Idx, IdxResult, Info))
4855        return false;
4856      const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4857      if (!AT)
4858        return Error(OOE);
4859      CurrentType = AT->getElementType();
4860      CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4861      Result += IdxResult.getSExtValue() * ElementSize;
4862        break;
4863    }
4864
4865    case OffsetOfExpr::OffsetOfNode::Field: {
4866      FieldDecl *MemberDecl = ON.getField();
4867      const RecordType *RT = CurrentType->getAs<RecordType>();
4868      if (!RT)
4869        return Error(OOE);
4870      RecordDecl *RD = RT->getDecl();
4871      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4872      unsigned i = MemberDecl->getFieldIndex();
4873      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
4874      Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
4875      CurrentType = MemberDecl->getType().getNonReferenceType();
4876      break;
4877    }
4878
4879    case OffsetOfExpr::OffsetOfNode::Identifier:
4880      llvm_unreachable("dependent __builtin_offsetof");
4881
4882    case OffsetOfExpr::OffsetOfNode::Base: {
4883      CXXBaseSpecifier *BaseSpec = ON.getBase();
4884      if (BaseSpec->isVirtual())
4885        return Error(OOE);
4886
4887      // Find the layout of the class whose base we are looking into.
4888      const RecordType *RT = CurrentType->getAs<RecordType>();
4889      if (!RT)
4890        return Error(OOE);
4891      RecordDecl *RD = RT->getDecl();
4892      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4893
4894      // Find the base class itself.
4895      CurrentType = BaseSpec->getType();
4896      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4897      if (!BaseRT)
4898        return Error(OOE);
4899
4900      // Add the offset to the base.
4901      Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
4902      break;
4903    }
4904    }
4905  }
4906  return Success(Result, OOE);
4907}
4908
4909bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4910  switch (E->getOpcode()) {
4911  default:
4912    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4913    // See C99 6.6p3.
4914    return Error(E);
4915  case UO_Extension:
4916    // FIXME: Should extension allow i-c-e extension expressions in its scope?
4917    // If so, we could clear the diagnostic ID.
4918    return Visit(E->getSubExpr());
4919  case UO_Plus:
4920    // The result is just the value.
4921    return Visit(E->getSubExpr());
4922  case UO_Minus: {
4923    if (!Visit(E->getSubExpr()))
4924      return false;
4925    if (!Result.isInt()) return Error(E);
4926    const APSInt &Value = Result.getInt();
4927    if (Value.isSigned() && Value.isMinSignedValue())
4928      HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4929                     E->getType());
4930    return Success(-Value, E);
4931  }
4932  case UO_Not: {
4933    if (!Visit(E->getSubExpr()))
4934      return false;
4935    if (!Result.isInt()) return Error(E);
4936    return Success(~Result.getInt(), E);
4937  }
4938  case UO_LNot: {
4939    bool bres;
4940    if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
4941      return false;
4942    return Success(!bres, E);
4943  }
4944  }
4945}
4946
4947/// HandleCast - This is used to evaluate implicit or explicit casts where the
4948/// result type is integer.
4949bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4950  const Expr *SubExpr = E->getSubExpr();
4951  QualType DestType = E->getType();
4952  QualType SrcType = SubExpr->getType();
4953
4954  switch (E->getCastKind()) {
4955  case CK_BaseToDerived:
4956  case CK_DerivedToBase:
4957  case CK_UncheckedDerivedToBase:
4958  case CK_Dynamic:
4959  case CK_ToUnion:
4960  case CK_ArrayToPointerDecay:
4961  case CK_FunctionToPointerDecay:
4962  case CK_NullToPointer:
4963  case CK_NullToMemberPointer:
4964  case CK_BaseToDerivedMemberPointer:
4965  case CK_DerivedToBaseMemberPointer:
4966  case CK_ConstructorConversion:
4967  case CK_IntegralToPointer:
4968  case CK_ToVoid:
4969  case CK_VectorSplat:
4970  case CK_IntegralToFloating:
4971  case CK_FloatingCast:
4972  case CK_CPointerToObjCPointerCast:
4973  case CK_BlockPointerToObjCPointerCast:
4974  case CK_AnyPointerToBlockPointerCast:
4975  case CK_ObjCObjectLValueCast:
4976  case CK_FloatingRealToComplex:
4977  case CK_FloatingComplexToReal:
4978  case CK_FloatingComplexCast:
4979  case CK_FloatingComplexToIntegralComplex:
4980  case CK_IntegralRealToComplex:
4981  case CK_IntegralComplexCast:
4982  case CK_IntegralComplexToFloatingComplex:
4983    llvm_unreachable("invalid cast kind for integral value");
4984
4985  case CK_BitCast:
4986  case CK_Dependent:
4987  case CK_LValueBitCast:
4988  case CK_ARCProduceObject:
4989  case CK_ARCConsumeObject:
4990  case CK_ARCReclaimReturnedObject:
4991  case CK_ARCExtendBlockObject:
4992    return Error(E);
4993
4994  case CK_UserDefinedConversion:
4995  case CK_LValueToRValue:
4996  case CK_AtomicToNonAtomic:
4997  case CK_NonAtomicToAtomic:
4998  case CK_NoOp:
4999    return ExprEvaluatorBaseTy::VisitCastExpr(E);
5000
5001  case CK_MemberPointerToBoolean:
5002  case CK_PointerToBoolean:
5003  case CK_IntegralToBoolean:
5004  case CK_FloatingToBoolean:
5005  case CK_FloatingComplexToBoolean:
5006  case CK_IntegralComplexToBoolean: {
5007    bool BoolResult;
5008    if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
5009      return false;
5010    return Success(BoolResult, E);
5011  }
5012
5013  case CK_IntegralCast: {
5014    if (!Visit(SubExpr))
5015      return false;
5016
5017    if (!Result.isInt()) {
5018      // Allow casts of address-of-label differences if they are no-ops
5019      // or narrowing.  (The narrowing case isn't actually guaranteed to
5020      // be constant-evaluatable except in some narrow cases which are hard
5021      // to detect here.  We let it through on the assumption the user knows
5022      // what they are doing.)
5023      if (Result.isAddrLabelDiff())
5024        return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
5025      // Only allow casts of lvalues if they are lossless.
5026      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5027    }
5028
5029    return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5030                                      Result.getInt()), E);
5031  }
5032
5033  case CK_PointerToIntegral: {
5034    CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5035
5036    LValue LV;
5037    if (!EvaluatePointer(SubExpr, LV, Info))
5038      return false;
5039
5040    if (LV.getLValueBase()) {
5041      // Only allow based lvalue casts if they are lossless.
5042      // FIXME: Allow a larger integer size than the pointer size, and allow
5043      // narrowing back down to pointer width in subsequent integral casts.
5044      // FIXME: Check integer type's active bits, not its type size.
5045      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
5046        return Error(E);
5047
5048      LV.Designator.setInvalid();
5049      LV.moveInto(Result);
5050      return true;
5051    }
5052
5053    APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5054                                         SrcType);
5055    return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
5056  }
5057
5058  case CK_IntegralComplexToReal: {
5059    ComplexValue C;
5060    if (!EvaluateComplex(SubExpr, C, Info))
5061      return false;
5062    return Success(C.getComplexIntReal(), E);
5063  }
5064
5065  case CK_FloatingToIntegral: {
5066    APFloat F(0.0);
5067    if (!EvaluateFloat(SubExpr, F, Info))
5068      return false;
5069
5070    APSInt Value;
5071    if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5072      return false;
5073    return Success(Value, E);
5074  }
5075  }
5076
5077  llvm_unreachable("unknown cast resulting in integral value");
5078}
5079
5080bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5081  if (E->getSubExpr()->getType()->isAnyComplexType()) {
5082    ComplexValue LV;
5083    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5084      return false;
5085    if (!LV.isComplexInt())
5086      return Error(E);
5087    return Success(LV.getComplexIntReal(), E);
5088  }
5089
5090  return Visit(E->getSubExpr());
5091}
5092
5093bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5094  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
5095    ComplexValue LV;
5096    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5097      return false;
5098    if (!LV.isComplexInt())
5099      return Error(E);
5100    return Success(LV.getComplexIntImag(), E);
5101  }
5102
5103  VisitIgnoredValue(E->getSubExpr());
5104  return Success(0, E);
5105}
5106
5107bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5108  return Success(E->getPackLength(), E);
5109}
5110
5111bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5112  return Success(E->getValue(), E);
5113}
5114
5115//===----------------------------------------------------------------------===//
5116// Float Evaluation
5117//===----------------------------------------------------------------------===//
5118
5119namespace {
5120class FloatExprEvaluator
5121  : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
5122  APFloat &Result;
5123public:
5124  FloatExprEvaluator(EvalInfo &info, APFloat &result)
5125    : ExprEvaluatorBaseTy(info), Result(result) {}
5126
5127  bool Success(const CCValue &V, const Expr *e) {
5128    Result = V.getFloat();
5129    return true;
5130  }
5131
5132  bool ZeroInitialization(const Expr *E) {
5133    Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5134    return true;
5135  }
5136
5137  bool VisitCallExpr(const CallExpr *E);
5138
5139  bool VisitUnaryOperator(const UnaryOperator *E);
5140  bool VisitBinaryOperator(const BinaryOperator *E);
5141  bool VisitFloatingLiteral(const FloatingLiteral *E);
5142  bool VisitCastExpr(const CastExpr *E);
5143
5144  bool VisitUnaryReal(const UnaryOperator *E);
5145  bool VisitUnaryImag(const UnaryOperator *E);
5146
5147  // FIXME: Missing: array subscript of vector, member of vector
5148};
5149} // end anonymous namespace
5150
5151static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
5152  assert(E->isRValue() && E->getType()->isRealFloatingType());
5153  return FloatExprEvaluator(Info, Result).Visit(E);
5154}
5155
5156static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
5157                                  QualType ResultTy,
5158                                  const Expr *Arg,
5159                                  bool SNaN,
5160                                  llvm::APFloat &Result) {
5161  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5162  if (!S) return false;
5163
5164  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5165
5166  llvm::APInt fill;
5167
5168  // Treat empty strings as if they were zero.
5169  if (S->getString().empty())
5170    fill = llvm::APInt(32, 0);
5171  else if (S->getString().getAsInteger(0, fill))
5172    return false;
5173
5174  if (SNaN)
5175    Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5176  else
5177    Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5178  return true;
5179}
5180
5181bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
5182  switch (E->isBuiltinCall()) {
5183  default:
5184    return ExprEvaluatorBaseTy::VisitCallExpr(E);
5185
5186  case Builtin::BI__builtin_huge_val:
5187  case Builtin::BI__builtin_huge_valf:
5188  case Builtin::BI__builtin_huge_vall:
5189  case Builtin::BI__builtin_inf:
5190  case Builtin::BI__builtin_inff:
5191  case Builtin::BI__builtin_infl: {
5192    const llvm::fltSemantics &Sem =
5193      Info.Ctx.getFloatTypeSemantics(E->getType());
5194    Result = llvm::APFloat::getInf(Sem);
5195    return true;
5196  }
5197
5198  case Builtin::BI__builtin_nans:
5199  case Builtin::BI__builtin_nansf:
5200  case Builtin::BI__builtin_nansl:
5201    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5202                               true, Result))
5203      return Error(E);
5204    return true;
5205
5206  case Builtin::BI__builtin_nan:
5207  case Builtin::BI__builtin_nanf:
5208  case Builtin::BI__builtin_nanl:
5209    // If this is __builtin_nan() turn this into a nan, otherwise we
5210    // can't constant fold it.
5211    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5212                               false, Result))
5213      return Error(E);
5214    return true;
5215
5216  case Builtin::BI__builtin_fabs:
5217  case Builtin::BI__builtin_fabsf:
5218  case Builtin::BI__builtin_fabsl:
5219    if (!EvaluateFloat(E->getArg(0), Result, Info))
5220      return false;
5221
5222    if (Result.isNegative())
5223      Result.changeSign();
5224    return true;
5225
5226  case Builtin::BI__builtin_copysign:
5227  case Builtin::BI__builtin_copysignf:
5228  case Builtin::BI__builtin_copysignl: {
5229    APFloat RHS(0.);
5230    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5231        !EvaluateFloat(E->getArg(1), RHS, Info))
5232      return false;
5233    Result.copySign(RHS);
5234    return true;
5235  }
5236  }
5237}
5238
5239bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5240  if (E->getSubExpr()->getType()->isAnyComplexType()) {
5241    ComplexValue CV;
5242    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5243      return false;
5244    Result = CV.FloatReal;
5245    return true;
5246  }
5247
5248  return Visit(E->getSubExpr());
5249}
5250
5251bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5252  if (E->getSubExpr()->getType()->isAnyComplexType()) {
5253    ComplexValue CV;
5254    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5255      return false;
5256    Result = CV.FloatImag;
5257    return true;
5258  }
5259
5260  VisitIgnoredValue(E->getSubExpr());
5261  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5262  Result = llvm::APFloat::getZero(Sem);
5263  return true;
5264}
5265
5266bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5267  switch (E->getOpcode()) {
5268  default: return Error(E);
5269  case UO_Plus:
5270    return EvaluateFloat(E->getSubExpr(), Result, Info);
5271  case UO_Minus:
5272    if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5273      return false;
5274    Result.changeSign();
5275    return true;
5276  }
5277}
5278
5279bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5280  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5281    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5282
5283  APFloat RHS(0.0);
5284  bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5285  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5286    return false;
5287  if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
5288    return false;
5289
5290  switch (E->getOpcode()) {
5291  default: return Error(E);
5292  case BO_Mul:
5293    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
5294    break;
5295  case BO_Add:
5296    Result.add(RHS, APFloat::rmNearestTiesToEven);
5297    break;
5298  case BO_Sub:
5299    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
5300    break;
5301  case BO_Div:
5302    Result.divide(RHS, APFloat::rmNearestTiesToEven);
5303    break;
5304  }
5305
5306  if (Result.isInfinity() || Result.isNaN())
5307    CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5308  return true;
5309}
5310
5311bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5312  Result = E->getValue();
5313  return true;
5314}
5315
5316bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5317  const Expr* SubExpr = E->getSubExpr();
5318
5319  switch (E->getCastKind()) {
5320  default:
5321    return ExprEvaluatorBaseTy::VisitCastExpr(E);
5322
5323  case CK_IntegralToFloating: {
5324    APSInt IntResult;
5325    return EvaluateInteger(SubExpr, IntResult, Info) &&
5326           HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5327                                E->getType(), Result);
5328  }
5329
5330  case CK_FloatingCast: {
5331    if (!Visit(SubExpr))
5332      return false;
5333    return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5334                                  Result);
5335  }
5336
5337  case CK_FloatingComplexToReal: {
5338    ComplexValue V;
5339    if (!EvaluateComplex(SubExpr, V, Info))
5340      return false;
5341    Result = V.getComplexFloatReal();
5342    return true;
5343  }
5344  }
5345}
5346
5347//===----------------------------------------------------------------------===//
5348// Complex Evaluation (for float and integer)
5349//===----------------------------------------------------------------------===//
5350
5351namespace {
5352class ComplexExprEvaluator
5353  : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
5354  ComplexValue &Result;
5355
5356public:
5357  ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
5358    : ExprEvaluatorBaseTy(info), Result(Result) {}
5359
5360  bool Success(const CCValue &V, const Expr *e) {
5361    Result.setFrom(V);
5362    return true;
5363  }
5364
5365  bool ZeroInitialization(const Expr *E);
5366
5367  //===--------------------------------------------------------------------===//
5368  //                            Visitor Methods
5369  //===--------------------------------------------------------------------===//
5370
5371  bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
5372  bool VisitCastExpr(const CastExpr *E);
5373  bool VisitBinaryOperator(const BinaryOperator *E);
5374  bool VisitUnaryOperator(const UnaryOperator *E);
5375  bool VisitInitListExpr(const InitListExpr *E);
5376};
5377} // end anonymous namespace
5378
5379static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5380                            EvalInfo &Info) {
5381  assert(E->isRValue() && E->getType()->isAnyComplexType());
5382  return ComplexExprEvaluator(Info, Result).Visit(E);
5383}
5384
5385bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
5386  QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
5387  if (ElemTy->isRealFloatingType()) {
5388    Result.makeComplexFloat();
5389    APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5390    Result.FloatReal = Zero;
5391    Result.FloatImag = Zero;
5392  } else {
5393    Result.makeComplexInt();
5394    APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5395    Result.IntReal = Zero;
5396    Result.IntImag = Zero;
5397  }
5398  return true;
5399}
5400
5401bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5402  const Expr* SubExpr = E->getSubExpr();
5403
5404  if (SubExpr->getType()->isRealFloatingType()) {
5405    Result.makeComplexFloat();
5406    APFloat &Imag = Result.FloatImag;
5407    if (!EvaluateFloat(SubExpr, Imag, Info))
5408      return false;
5409
5410    Result.FloatReal = APFloat(Imag.getSemantics());
5411    return true;
5412  } else {
5413    assert(SubExpr->getType()->isIntegerType() &&
5414           "Unexpected imaginary literal.");
5415
5416    Result.makeComplexInt();
5417    APSInt &Imag = Result.IntImag;
5418    if (!EvaluateInteger(SubExpr, Imag, Info))
5419      return false;
5420
5421    Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5422    return true;
5423  }
5424}
5425
5426bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
5427
5428  switch (E->getCastKind()) {
5429  case CK_BitCast:
5430  case CK_BaseToDerived:
5431  case CK_DerivedToBase:
5432  case CK_UncheckedDerivedToBase:
5433  case CK_Dynamic:
5434  case CK_ToUnion:
5435  case CK_ArrayToPointerDecay:
5436  case CK_FunctionToPointerDecay:
5437  case CK_NullToPointer:
5438  case CK_NullToMemberPointer:
5439  case CK_BaseToDerivedMemberPointer:
5440  case CK_DerivedToBaseMemberPointer:
5441  case CK_MemberPointerToBoolean:
5442  case CK_ConstructorConversion:
5443  case CK_IntegralToPointer:
5444  case CK_PointerToIntegral:
5445  case CK_PointerToBoolean:
5446  case CK_ToVoid:
5447  case CK_VectorSplat:
5448  case CK_IntegralCast:
5449  case CK_IntegralToBoolean:
5450  case CK_IntegralToFloating:
5451  case CK_FloatingToIntegral:
5452  case CK_FloatingToBoolean:
5453  case CK_FloatingCast:
5454  case CK_CPointerToObjCPointerCast:
5455  case CK_BlockPointerToObjCPointerCast:
5456  case CK_AnyPointerToBlockPointerCast:
5457  case CK_ObjCObjectLValueCast:
5458  case CK_FloatingComplexToReal:
5459  case CK_FloatingComplexToBoolean:
5460  case CK_IntegralComplexToReal:
5461  case CK_IntegralComplexToBoolean:
5462  case CK_ARCProduceObject:
5463  case CK_ARCConsumeObject:
5464  case CK_ARCReclaimReturnedObject:
5465  case CK_ARCExtendBlockObject:
5466    llvm_unreachable("invalid cast kind for complex value");
5467
5468  case CK_LValueToRValue:
5469  case CK_AtomicToNonAtomic:
5470  case CK_NonAtomicToAtomic:
5471  case CK_NoOp:
5472    return ExprEvaluatorBaseTy::VisitCastExpr(E);
5473
5474  case CK_Dependent:
5475  case CK_LValueBitCast:
5476  case CK_UserDefinedConversion:
5477    return Error(E);
5478
5479  case CK_FloatingRealToComplex: {
5480    APFloat &Real = Result.FloatReal;
5481    if (!EvaluateFloat(E->getSubExpr(), Real, Info))
5482      return false;
5483
5484    Result.makeComplexFloat();
5485    Result.FloatImag = APFloat(Real.getSemantics());
5486    return true;
5487  }
5488
5489  case CK_FloatingComplexCast: {
5490    if (!Visit(E->getSubExpr()))
5491      return false;
5492
5493    QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5494    QualType From
5495      = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5496
5497    return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5498           HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
5499  }
5500
5501  case CK_FloatingComplexToIntegralComplex: {
5502    if (!Visit(E->getSubExpr()))
5503      return false;
5504
5505    QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5506    QualType From
5507      = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5508    Result.makeComplexInt();
5509    return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5510                                To, Result.IntReal) &&
5511           HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5512                                To, Result.IntImag);
5513  }
5514
5515  case CK_IntegralRealToComplex: {
5516    APSInt &Real = Result.IntReal;
5517    if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5518      return false;
5519
5520    Result.makeComplexInt();
5521    Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5522    return true;
5523  }
5524
5525  case CK_IntegralComplexCast: {
5526    if (!Visit(E->getSubExpr()))
5527      return false;
5528
5529    QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5530    QualType From
5531      = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5532
5533    Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5534    Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
5535    return true;
5536  }
5537
5538  case CK_IntegralComplexToFloatingComplex: {
5539    if (!Visit(E->getSubExpr()))
5540      return false;
5541
5542    QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5543    QualType From
5544      = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5545    Result.makeComplexFloat();
5546    return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5547                                To, Result.FloatReal) &&
5548           HandleIntToFloatCast(Info, E, From, Result.IntImag,
5549                                To, Result.FloatImag);
5550  }
5551  }
5552
5553  llvm_unreachable("unknown cast resulting in complex value");
5554}
5555
5556bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5557  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5558    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5559
5560  bool LHSOK = Visit(E->getLHS());
5561  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5562    return false;
5563
5564  ComplexValue RHS;
5565  if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
5566    return false;
5567
5568  assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5569         "Invalid operands to binary operator.");
5570  switch (E->getOpcode()) {
5571  default: return Error(E);
5572  case BO_Add:
5573    if (Result.isComplexFloat()) {
5574      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5575                                       APFloat::rmNearestTiesToEven);
5576      Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5577                                       APFloat::rmNearestTiesToEven);
5578    } else {
5579      Result.getComplexIntReal() += RHS.getComplexIntReal();
5580      Result.getComplexIntImag() += RHS.getComplexIntImag();
5581    }
5582    break;
5583  case BO_Sub:
5584    if (Result.isComplexFloat()) {
5585      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5586                                            APFloat::rmNearestTiesToEven);
5587      Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5588                                            APFloat::rmNearestTiesToEven);
5589    } else {
5590      Result.getComplexIntReal() -= RHS.getComplexIntReal();
5591      Result.getComplexIntImag() -= RHS.getComplexIntImag();
5592    }
5593    break;
5594  case BO_Mul:
5595    if (Result.isComplexFloat()) {
5596      ComplexValue LHS = Result;
5597      APFloat &LHS_r = LHS.getComplexFloatReal();
5598      APFloat &LHS_i = LHS.getComplexFloatImag();
5599      APFloat &RHS_r = RHS.getComplexFloatReal();
5600      APFloat &RHS_i = RHS.getComplexFloatImag();
5601
5602      APFloat Tmp = LHS_r;
5603      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5604      Result.getComplexFloatReal() = Tmp;
5605      Tmp = LHS_i;
5606      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5607      Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5608
5609      Tmp = LHS_r;
5610      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5611      Result.getComplexFloatImag() = Tmp;
5612      Tmp = LHS_i;
5613      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5614      Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5615    } else {
5616      ComplexValue LHS = Result;
5617      Result.getComplexIntReal() =
5618        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5619         LHS.getComplexIntImag() * RHS.getComplexIntImag());
5620      Result.getComplexIntImag() =
5621        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5622         LHS.getComplexIntImag() * RHS.getComplexIntReal());
5623    }
5624    break;
5625  case BO_Div:
5626    if (Result.isComplexFloat()) {
5627      ComplexValue LHS = Result;
5628      APFloat &LHS_r = LHS.getComplexFloatReal();
5629      APFloat &LHS_i = LHS.getComplexFloatImag();
5630      APFloat &RHS_r = RHS.getComplexFloatReal();
5631      APFloat &RHS_i = RHS.getComplexFloatImag();
5632      APFloat &Res_r = Result.getComplexFloatReal();
5633      APFloat &Res_i = Result.getComplexFloatImag();
5634
5635      APFloat Den = RHS_r;
5636      Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5637      APFloat Tmp = RHS_i;
5638      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5639      Den.add(Tmp, APFloat::rmNearestTiesToEven);
5640
5641      Res_r = LHS_r;
5642      Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5643      Tmp = LHS_i;
5644      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5645      Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5646      Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5647
5648      Res_i = LHS_i;
5649      Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5650      Tmp = LHS_r;
5651      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5652      Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5653      Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5654    } else {
5655      if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5656        return Error(E, diag::note_expr_divide_by_zero);
5657
5658      ComplexValue LHS = Result;
5659      APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5660        RHS.getComplexIntImag() * RHS.getComplexIntImag();
5661      Result.getComplexIntReal() =
5662        (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5663         LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5664      Result.getComplexIntImag() =
5665        (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5666         LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5667    }
5668    break;
5669  }
5670
5671  return true;
5672}
5673
5674bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5675  // Get the operand value into 'Result'.
5676  if (!Visit(E->getSubExpr()))
5677    return false;
5678
5679  switch (E->getOpcode()) {
5680  default:
5681    return Error(E);
5682  case UO_Extension:
5683    return true;
5684  case UO_Plus:
5685    // The result is always just the subexpr.
5686    return true;
5687  case UO_Minus:
5688    if (Result.isComplexFloat()) {
5689      Result.getComplexFloatReal().changeSign();
5690      Result.getComplexFloatImag().changeSign();
5691    }
5692    else {
5693      Result.getComplexIntReal() = -Result.getComplexIntReal();
5694      Result.getComplexIntImag() = -Result.getComplexIntImag();
5695    }
5696    return true;
5697  case UO_Not:
5698    if (Result.isComplexFloat())
5699      Result.getComplexFloatImag().changeSign();
5700    else
5701      Result.getComplexIntImag() = -Result.getComplexIntImag();
5702    return true;
5703  }
5704}
5705
5706bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5707  if (E->getNumInits() == 2) {
5708    if (E->getType()->isComplexType()) {
5709      Result.makeComplexFloat();
5710      if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5711        return false;
5712      if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5713        return false;
5714    } else {
5715      Result.makeComplexInt();
5716      if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5717        return false;
5718      if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5719        return false;
5720    }
5721    return true;
5722  }
5723  return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5724}
5725
5726//===----------------------------------------------------------------------===//
5727// Void expression evaluation, primarily for a cast to void on the LHS of a
5728// comma operator
5729//===----------------------------------------------------------------------===//
5730
5731namespace {
5732class VoidExprEvaluator
5733  : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5734public:
5735  VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5736
5737  bool Success(const CCValue &V, const Expr *e) { return true; }
5738
5739  bool VisitCastExpr(const CastExpr *E) {
5740    switch (E->getCastKind()) {
5741    default:
5742      return ExprEvaluatorBaseTy::VisitCastExpr(E);
5743    case CK_ToVoid:
5744      VisitIgnoredValue(E->getSubExpr());
5745      return true;
5746    }
5747  }
5748};
5749} // end anonymous namespace
5750
5751static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5752  assert(E->isRValue() && E->getType()->isVoidType());
5753  return VoidExprEvaluator(Info).Visit(E);
5754}
5755
5756//===----------------------------------------------------------------------===//
5757// Top level Expr::EvaluateAsRValue method.
5758//===----------------------------------------------------------------------===//
5759
5760static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
5761  // In C, function designators are not lvalues, but we evaluate them as if they
5762  // are.
5763  if (E->isGLValue() || E->getType()->isFunctionType()) {
5764    LValue LV;
5765    if (!EvaluateLValue(E, LV, Info))
5766      return false;
5767    LV.moveInto(Result);
5768  } else if (E->getType()->isVectorType()) {
5769    if (!EvaluateVector(E, Result, Info))
5770      return false;
5771  } else if (E->getType()->isIntegralOrEnumerationType()) {
5772    if (!IntExprEvaluator(Info, Result).Visit(E))
5773      return false;
5774  } else if (E->getType()->hasPointerRepresentation()) {
5775    LValue LV;
5776    if (!EvaluatePointer(E, LV, Info))
5777      return false;
5778    LV.moveInto(Result);
5779  } else if (E->getType()->isRealFloatingType()) {
5780    llvm::APFloat F(0.0);
5781    if (!EvaluateFloat(E, F, Info))
5782      return false;
5783    Result = CCValue(F);
5784  } else if (E->getType()->isAnyComplexType()) {
5785    ComplexValue C;
5786    if (!EvaluateComplex(E, C, Info))
5787      return false;
5788    C.moveInto(Result);
5789  } else if (E->getType()->isMemberPointerType()) {
5790    MemberPtr P;
5791    if (!EvaluateMemberPointer(E, P, Info))
5792      return false;
5793    P.moveInto(Result);
5794    return true;
5795  } else if (E->getType()->isArrayType()) {
5796    LValue LV;
5797    LV.set(E, Info.CurrentCall);
5798    if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
5799      return false;
5800    Result = Info.CurrentCall->Temporaries[E];
5801  } else if (E->getType()->isRecordType()) {
5802    LValue LV;
5803    LV.set(E, Info.CurrentCall);
5804    if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5805      return false;
5806    Result = Info.CurrentCall->Temporaries[E];
5807  } else if (E->getType()->isVoidType()) {
5808    if (Info.getLangOpts().CPlusPlus0x)
5809      Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5810        << E->getType();
5811    else
5812      Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
5813    if (!EvaluateVoid(E, Info))
5814      return false;
5815  } else if (Info.getLangOpts().CPlusPlus0x) {
5816    Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5817    return false;
5818  } else {
5819    Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
5820    return false;
5821  }
5822
5823  return true;
5824}
5825
5826/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5827/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5828/// since later initializers for an object can indirectly refer to subobjects
5829/// which were initialized earlier.
5830static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
5831                                       const LValue &This, const Expr *E,
5832                                       CheckConstantExpressionKind CCEK) {
5833  if (!CheckLiteralType(Info, E))
5834    return false;
5835
5836  if (E->isRValue()) {
5837    // Evaluate arrays and record types in-place, so that later initializers can
5838    // refer to earlier-initialized members of the object.
5839    if (E->getType()->isArrayType())
5840      return EvaluateArray(E, This, Result, Info);
5841    else if (E->getType()->isRecordType())
5842      return EvaluateRecord(E, This, Result, Info);
5843  }
5844
5845  // For any other type, in-place evaluation is unimportant.
5846  CCValue CoreConstResult;
5847  return Evaluate(CoreConstResult, Info, E) &&
5848         CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
5849}
5850
5851/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5852/// lvalue-to-rvalue cast if it is an lvalue.
5853static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
5854  if (!CheckLiteralType(Info, E))
5855    return false;
5856
5857  CCValue Value;
5858  if (!::Evaluate(Value, Info, E))
5859    return false;
5860
5861  if (E->isGLValue()) {
5862    LValue LV;
5863    LV.setFrom(Value);
5864    if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5865      return false;
5866  }
5867
5868  // Check this core constant expression is a constant expression, and if so,
5869  // convert it to one.
5870  return CheckConstantExpression(Info, E, Value, Result);
5871}
5872
5873/// EvaluateAsRValue - Return true if this is a constant which we can fold using
5874/// any crazy technique (that has nothing to do with language standards) that
5875/// we want to.  If this function returns true, it returns the folded constant
5876/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5877/// will be applied to the result.
5878bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
5879  // Fast-path evaluations of integer literals, since we sometimes see files
5880  // containing vast quantities of these.
5881  if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5882    Result.Val = APValue(APSInt(L->getValue(),
5883                                L->getType()->isUnsignedIntegerType()));
5884    return true;
5885  }
5886
5887  // FIXME: Evaluating values of large array and record types can cause
5888  // performance problems. Only do so in C++11 for now.
5889  if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5890      !Ctx.getLangOptions().CPlusPlus0x)
5891    return false;
5892
5893  EvalInfo Info(Ctx, Result);
5894  return ::EvaluateAsRValue(Info, this, Result.Val);
5895}
5896
5897bool Expr::EvaluateAsBooleanCondition(bool &Result,
5898                                      const ASTContext &Ctx) const {
5899  EvalResult Scratch;
5900  return EvaluateAsRValue(Scratch, Ctx) &&
5901         HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5902                                        Scratch.Val, CCValue::GlobalValue()),
5903                                Result);
5904}
5905
5906bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5907                         SideEffectsKind AllowSideEffects) const {
5908  if (!getType()->isIntegralOrEnumerationType())
5909    return false;
5910
5911  EvalResult ExprResult;
5912  if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5913      (!AllowSideEffects && ExprResult.HasSideEffects))
5914    return false;
5915
5916  Result = ExprResult.Val.getInt();
5917  return true;
5918}
5919
5920bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
5921  EvalInfo Info(Ctx, Result);
5922
5923  LValue LV;
5924  return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
5925         CheckLValueConstantExpression(Info, this, LV, Result.Val,
5926                                       CCEK_Constant);
5927}
5928
5929bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5930                                 const VarDecl *VD,
5931                      llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5932  // FIXME: Evaluating initializers for large array and record types can cause
5933  // performance problems. Only do so in C++11 for now.
5934  if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5935      !Ctx.getLangOptions().CPlusPlus0x)
5936    return false;
5937
5938  Expr::EvalStatus EStatus;
5939  EStatus.Diag = &Notes;
5940
5941  EvalInfo InitInfo(Ctx, EStatus);
5942  InitInfo.setEvaluatingDecl(VD, Value);
5943
5944  if (!CheckLiteralType(InitInfo, this))
5945    return false;
5946
5947  LValue LVal;
5948  LVal.set(VD);
5949
5950  // C++11 [basic.start.init]p2:
5951  //  Variables with static storage duration or thread storage duration shall be
5952  //  zero-initialized before any other initialization takes place.
5953  // This behavior is not present in C.
5954  if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5955      !VD->getType()->isReferenceType()) {
5956    ImplicitValueInitExpr VIE(VD->getType());
5957    if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5958      return false;
5959  }
5960
5961  return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5962         !EStatus.HasSideEffects;
5963}
5964
5965/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5966/// constant folded, but discard the result.
5967bool Expr::isEvaluatable(const ASTContext &Ctx) const {
5968  EvalResult Result;
5969  return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
5970}
5971
5972bool Expr::HasSideEffects(const ASTContext &Ctx) const {
5973  return HasSideEffect(Ctx).Visit(this);
5974}
5975
5976APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
5977  EvalResult EvalResult;
5978  bool Result = EvaluateAsRValue(EvalResult, Ctx);
5979  (void)Result;
5980  assert(Result && "Could not evaluate expression");
5981  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
5982
5983  return EvalResult.Val.getInt();
5984}
5985
5986 bool Expr::EvalResult::isGlobalLValue() const {
5987   assert(Val.isLValue());
5988   return IsGlobalLValue(Val.getLValueBase());
5989 }
5990
5991
5992/// isIntegerConstantExpr - this recursive routine will test if an expression is
5993/// an integer constant expression.
5994
5995/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5996/// comma, etc
5997///
5998/// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
5999/// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
6000/// cast+dereference.
6001
6002// CheckICE - This function does the fundamental ICE checking: the returned
6003// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6004// Note that to reduce code duplication, this helper does no evaluation
6005// itself; the caller checks whether the expression is evaluatable, and
6006// in the rare cases where CheckICE actually cares about the evaluated
6007// value, it calls into Evalute.
6008//
6009// Meanings of Val:
6010// 0: This expression is an ICE.
6011// 1: This expression is not an ICE, but if it isn't evaluated, it's
6012//    a legal subexpression for an ICE. This return value is used to handle
6013//    the comma operator in C99 mode.
6014// 2: This expression is not an ICE, and is not a legal subexpression for one.
6015
6016namespace {
6017
6018struct ICEDiag {
6019  unsigned Val;
6020  SourceLocation Loc;
6021
6022  public:
6023  ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6024  ICEDiag() : Val(0) {}
6025};
6026
6027}
6028
6029static ICEDiag NoDiag() { return ICEDiag(); }
6030
6031static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6032  Expr::EvalResult EVResult;
6033  if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
6034      !EVResult.Val.isInt()) {
6035    return ICEDiag(2, E->getLocStart());
6036  }
6037  return NoDiag();
6038}
6039
6040static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6041  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
6042  if (!E->getType()->isIntegralOrEnumerationType()) {
6043    return ICEDiag(2, E->getLocStart());
6044  }
6045
6046  switch (E->getStmtClass()) {
6047#define ABSTRACT_STMT(Node)
6048#define STMT(Node, Base) case Expr::Node##Class:
6049#define EXPR(Node, Base)
6050#include "clang/AST/StmtNodes.inc"
6051  case Expr::PredefinedExprClass:
6052  case Expr::FloatingLiteralClass:
6053  case Expr::ImaginaryLiteralClass:
6054  case Expr::StringLiteralClass:
6055  case Expr::ArraySubscriptExprClass:
6056  case Expr::MemberExprClass:
6057  case Expr::CompoundAssignOperatorClass:
6058  case Expr::CompoundLiteralExprClass:
6059  case Expr::ExtVectorElementExprClass:
6060  case Expr::DesignatedInitExprClass:
6061  case Expr::ImplicitValueInitExprClass:
6062  case Expr::ParenListExprClass:
6063  case Expr::VAArgExprClass:
6064  case Expr::AddrLabelExprClass:
6065  case Expr::StmtExprClass:
6066  case Expr::CXXMemberCallExprClass:
6067  case Expr::CUDAKernelCallExprClass:
6068  case Expr::CXXDynamicCastExprClass:
6069  case Expr::CXXTypeidExprClass:
6070  case Expr::CXXUuidofExprClass:
6071  case Expr::CXXNullPtrLiteralExprClass:
6072  case Expr::CXXThisExprClass:
6073  case Expr::CXXThrowExprClass:
6074  case Expr::CXXNewExprClass:
6075  case Expr::CXXDeleteExprClass:
6076  case Expr::CXXPseudoDestructorExprClass:
6077  case Expr::UnresolvedLookupExprClass:
6078  case Expr::DependentScopeDeclRefExprClass:
6079  case Expr::CXXConstructExprClass:
6080  case Expr::CXXBindTemporaryExprClass:
6081  case Expr::ExprWithCleanupsClass:
6082  case Expr::CXXTemporaryObjectExprClass:
6083  case Expr::CXXUnresolvedConstructExprClass:
6084  case Expr::CXXDependentScopeMemberExprClass:
6085  case Expr::UnresolvedMemberExprClass:
6086  case Expr::ObjCStringLiteralClass:
6087  case Expr::ObjCEncodeExprClass:
6088  case Expr::ObjCMessageExprClass:
6089  case Expr::ObjCSelectorExprClass:
6090  case Expr::ObjCProtocolExprClass:
6091  case Expr::ObjCIvarRefExprClass:
6092  case Expr::ObjCPropertyRefExprClass:
6093  case Expr::ObjCIsaExprClass:
6094  case Expr::ShuffleVectorExprClass:
6095  case Expr::BlockExprClass:
6096  case Expr::BlockDeclRefExprClass:
6097  case Expr::NoStmtClass:
6098  case Expr::OpaqueValueExprClass:
6099  case Expr::PackExpansionExprClass:
6100  case Expr::SubstNonTypeTemplateParmPackExprClass:
6101  case Expr::AsTypeExprClass:
6102  case Expr::ObjCIndirectCopyRestoreExprClass:
6103  case Expr::MaterializeTemporaryExprClass:
6104  case Expr::PseudoObjectExprClass:
6105  case Expr::AtomicExprClass:
6106  case Expr::InitListExprClass:
6107  case Expr::LambdaExprClass:
6108    return ICEDiag(2, E->getLocStart());
6109
6110  case Expr::SizeOfPackExprClass:
6111  case Expr::GNUNullExprClass:
6112    // GCC considers the GNU __null value to be an integral constant expression.
6113    return NoDiag();
6114
6115  case Expr::SubstNonTypeTemplateParmExprClass:
6116    return
6117      CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6118
6119  case Expr::ParenExprClass:
6120    return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
6121  case Expr::GenericSelectionExprClass:
6122    return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
6123  case Expr::IntegerLiteralClass:
6124  case Expr::CharacterLiteralClass:
6125  case Expr::CXXBoolLiteralExprClass:
6126  case Expr::CXXScalarValueInitExprClass:
6127  case Expr::UnaryTypeTraitExprClass:
6128  case Expr::BinaryTypeTraitExprClass:
6129  case Expr::ArrayTypeTraitExprClass:
6130  case Expr::ExpressionTraitExprClass:
6131  case Expr::CXXNoexceptExprClass:
6132    return NoDiag();
6133  case Expr::CallExprClass:
6134  case Expr::CXXOperatorCallExprClass: {
6135    // C99 6.6/3 allows function calls within unevaluated subexpressions of
6136    // constant expressions, but they can never be ICEs because an ICE cannot
6137    // contain an operand of (pointer to) function type.
6138    const CallExpr *CE = cast<CallExpr>(E);
6139    if (CE->isBuiltinCall())
6140      return CheckEvalInICE(E, Ctx);
6141    return ICEDiag(2, E->getLocStart());
6142  }
6143  case Expr::DeclRefExprClass:
6144    if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6145      return NoDiag();
6146    if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
6147      const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6148
6149      // Parameter variables are never constants.  Without this check,
6150      // getAnyInitializer() can find a default argument, which leads
6151      // to chaos.
6152      if (isa<ParmVarDecl>(D))
6153        return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6154
6155      // C++ 7.1.5.1p2
6156      //   A variable of non-volatile const-qualified integral or enumeration
6157      //   type initialized by an ICE can be used in ICEs.
6158      if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
6159        if (!Dcl->getType()->isIntegralOrEnumerationType())
6160          return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6161
6162        const VarDecl *VD;
6163        // Look for a declaration of this variable that has an initializer, and
6164        // check whether it is an ICE.
6165        if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6166          return NoDiag();
6167        else
6168          return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6169      }
6170    }
6171    return ICEDiag(2, E->getLocStart());
6172  case Expr::UnaryOperatorClass: {
6173    const UnaryOperator *Exp = cast<UnaryOperator>(E);
6174    switch (Exp->getOpcode()) {
6175    case UO_PostInc:
6176    case UO_PostDec:
6177    case UO_PreInc:
6178    case UO_PreDec:
6179    case UO_AddrOf:
6180    case UO_Deref:
6181      // C99 6.6/3 allows increment and decrement within unevaluated
6182      // subexpressions of constant expressions, but they can never be ICEs
6183      // because an ICE cannot contain an lvalue operand.
6184      return ICEDiag(2, E->getLocStart());
6185    case UO_Extension:
6186    case UO_LNot:
6187    case UO_Plus:
6188    case UO_Minus:
6189    case UO_Not:
6190    case UO_Real:
6191    case UO_Imag:
6192      return CheckICE(Exp->getSubExpr(), Ctx);
6193    }
6194
6195    // OffsetOf falls through here.
6196  }
6197  case Expr::OffsetOfExprClass: {
6198      // Note that per C99, offsetof must be an ICE. And AFAIK, using
6199      // EvaluateAsRValue matches the proposed gcc behavior for cases like
6200      // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
6201      // compliance: we should warn earlier for offsetof expressions with
6202      // array subscripts that aren't ICEs, and if the array subscripts
6203      // are ICEs, the value of the offsetof must be an integer constant.
6204      return CheckEvalInICE(E, Ctx);
6205  }
6206  case Expr::UnaryExprOrTypeTraitExprClass: {
6207    const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6208    if ((Exp->getKind() ==  UETT_SizeOf) &&
6209        Exp->getTypeOfArgument()->isVariableArrayType())
6210      return ICEDiag(2, E->getLocStart());
6211    return NoDiag();
6212  }
6213  case Expr::BinaryOperatorClass: {
6214    const BinaryOperator *Exp = cast<BinaryOperator>(E);
6215    switch (Exp->getOpcode()) {
6216    case BO_PtrMemD:
6217    case BO_PtrMemI:
6218    case BO_Assign:
6219    case BO_MulAssign:
6220    case BO_DivAssign:
6221    case BO_RemAssign:
6222    case BO_AddAssign:
6223    case BO_SubAssign:
6224    case BO_ShlAssign:
6225    case BO_ShrAssign:
6226    case BO_AndAssign:
6227    case BO_XorAssign:
6228    case BO_OrAssign:
6229      // C99 6.6/3 allows assignments within unevaluated subexpressions of
6230      // constant expressions, but they can never be ICEs because an ICE cannot
6231      // contain an lvalue operand.
6232      return ICEDiag(2, E->getLocStart());
6233
6234    case BO_Mul:
6235    case BO_Div:
6236    case BO_Rem:
6237    case BO_Add:
6238    case BO_Sub:
6239    case BO_Shl:
6240    case BO_Shr:
6241    case BO_LT:
6242    case BO_GT:
6243    case BO_LE:
6244    case BO_GE:
6245    case BO_EQ:
6246    case BO_NE:
6247    case BO_And:
6248    case BO_Xor:
6249    case BO_Or:
6250    case BO_Comma: {
6251      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6252      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6253      if (Exp->getOpcode() == BO_Div ||
6254          Exp->getOpcode() == BO_Rem) {
6255        // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
6256        // we don't evaluate one.
6257        if (LHSResult.Val == 0 && RHSResult.Val == 0) {
6258          llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
6259          if (REval == 0)
6260            return ICEDiag(1, E->getLocStart());
6261          if (REval.isSigned() && REval.isAllOnesValue()) {
6262            llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
6263            if (LEval.isMinSignedValue())
6264              return ICEDiag(1, E->getLocStart());
6265          }
6266        }
6267      }
6268      if (Exp->getOpcode() == BO_Comma) {
6269        if (Ctx.getLangOptions().C99) {
6270          // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6271          // if it isn't evaluated.
6272          if (LHSResult.Val == 0 && RHSResult.Val == 0)
6273            return ICEDiag(1, E->getLocStart());
6274        } else {
6275          // In both C89 and C++, commas in ICEs are illegal.
6276          return ICEDiag(2, E->getLocStart());
6277        }
6278      }
6279      if (LHSResult.Val >= RHSResult.Val)
6280        return LHSResult;
6281      return RHSResult;
6282    }
6283    case BO_LAnd:
6284    case BO_LOr: {
6285      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6286      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6287      if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6288        // Rare case where the RHS has a comma "side-effect"; we need
6289        // to actually check the condition to see whether the side
6290        // with the comma is evaluated.
6291        if ((Exp->getOpcode() == BO_LAnd) !=
6292            (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
6293          return RHSResult;
6294        return NoDiag();
6295      }
6296
6297      if (LHSResult.Val >= RHSResult.Val)
6298        return LHSResult;
6299      return RHSResult;
6300    }
6301    }
6302  }
6303  case Expr::ImplicitCastExprClass:
6304  case Expr::CStyleCastExprClass:
6305  case Expr::CXXFunctionalCastExprClass:
6306  case Expr::CXXStaticCastExprClass:
6307  case Expr::CXXReinterpretCastExprClass:
6308  case Expr::CXXConstCastExprClass:
6309  case Expr::ObjCBridgedCastExprClass: {
6310    const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
6311    if (isa<ExplicitCastExpr>(E)) {
6312      if (const FloatingLiteral *FL
6313            = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6314        unsigned DestWidth = Ctx.getIntWidth(E->getType());
6315        bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6316        APSInt IgnoredVal(DestWidth, !DestSigned);
6317        bool Ignored;
6318        // If the value does not fit in the destination type, the behavior is
6319        // undefined, so we are not required to treat it as a constant
6320        // expression.
6321        if (FL->getValue().convertToInteger(IgnoredVal,
6322                                            llvm::APFloat::rmTowardZero,
6323                                            &Ignored) & APFloat::opInvalidOp)
6324          return ICEDiag(2, E->getLocStart());
6325        return NoDiag();
6326      }
6327    }
6328    switch (cast<CastExpr>(E)->getCastKind()) {
6329    case CK_LValueToRValue:
6330    case CK_AtomicToNonAtomic:
6331    case CK_NonAtomicToAtomic:
6332    case CK_NoOp:
6333    case CK_IntegralToBoolean:
6334    case CK_IntegralCast:
6335      return CheckICE(SubExpr, Ctx);
6336    default:
6337      return ICEDiag(2, E->getLocStart());
6338    }
6339  }
6340  case Expr::BinaryConditionalOperatorClass: {
6341    const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6342    ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6343    if (CommonResult.Val == 2) return CommonResult;
6344    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6345    if (FalseResult.Val == 2) return FalseResult;
6346    if (CommonResult.Val == 1) return CommonResult;
6347    if (FalseResult.Val == 1 &&
6348        Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
6349    return FalseResult;
6350  }
6351  case Expr::ConditionalOperatorClass: {
6352    const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6353    // If the condition (ignoring parens) is a __builtin_constant_p call,
6354    // then only the true side is actually considered in an integer constant
6355    // expression, and it is fully evaluated.  This is an important GNU
6356    // extension.  See GCC PR38377 for discussion.
6357    if (const CallExpr *CallCE
6358        = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
6359      if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6360        return CheckEvalInICE(E, Ctx);
6361    ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
6362    if (CondResult.Val == 2)
6363      return CondResult;
6364
6365    ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6366    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6367
6368    if (TrueResult.Val == 2)
6369      return TrueResult;
6370    if (FalseResult.Val == 2)
6371      return FalseResult;
6372    if (CondResult.Val == 1)
6373      return CondResult;
6374    if (TrueResult.Val == 0 && FalseResult.Val == 0)
6375      return NoDiag();
6376    // Rare case where the diagnostics depend on which side is evaluated
6377    // Note that if we get here, CondResult is 0, and at least one of
6378    // TrueResult and FalseResult is non-zero.
6379    if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
6380      return FalseResult;
6381    }
6382    return TrueResult;
6383  }
6384  case Expr::CXXDefaultArgExprClass:
6385    return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6386  case Expr::ChooseExprClass: {
6387    return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6388  }
6389  }
6390
6391  llvm_unreachable("Invalid StmtClass!");
6392}
6393
6394/// Evaluate an expression as a C++11 integral constant expression.
6395static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6396                                                    const Expr *E,
6397                                                    llvm::APSInt *Value,
6398                                                    SourceLocation *Loc) {
6399  if (!E->getType()->isIntegralOrEnumerationType()) {
6400    if (Loc) *Loc = E->getExprLoc();
6401    return false;
6402  }
6403
6404  APValue Result;
6405  if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
6406    return false;
6407
6408  assert(Result.isInt() && "pointer cast to int is not an ICE");
6409  if (Value) *Value = Result.getInt();
6410  return true;
6411}
6412
6413bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
6414  if (Ctx.getLangOptions().CPlusPlus0x)
6415    return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6416
6417  ICEDiag d = CheckICE(this, Ctx);
6418  if (d.Val != 0) {
6419    if (Loc) *Loc = d.Loc;
6420    return false;
6421  }
6422  return true;
6423}
6424
6425bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6426                                 SourceLocation *Loc, bool isEvaluated) const {
6427  if (Ctx.getLangOptions().CPlusPlus0x)
6428    return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6429
6430  if (!isIntegerConstantExpr(Ctx, Loc))
6431    return false;
6432  if (!EvaluateAsInt(Value, Ctx))
6433    llvm_unreachable("ICE cannot be evaluated!");
6434  return true;
6435}
6436
6437bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6438                               SourceLocation *Loc) const {
6439  // We support this checking in C++98 mode in order to diagnose compatibility
6440  // issues.
6441  assert(Ctx.getLangOptions().CPlusPlus);
6442
6443  Expr::EvalStatus Status;
6444  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6445  Status.Diag = &Diags;
6446  EvalInfo Info(Ctx, Status);
6447
6448  APValue Scratch;
6449  bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6450
6451  if (!Diags.empty()) {
6452    IsConstExpr = false;
6453    if (Loc) *Loc = Diags[0].first;
6454  } else if (!IsConstExpr) {
6455    // FIXME: This shouldn't happen.
6456    if (Loc) *Loc = getExprLoc();
6457  }
6458
6459  return IsConstExpr;
6460}
6461
6462bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6463                                   llvm::SmallVectorImpl<
6464                                     PartialDiagnosticAt> &Diags) {
6465  // FIXME: It would be useful to check constexpr function templates, but at the
6466  // moment the constant expression evaluator cannot cope with the non-rigorous
6467  // ASTs which we build for dependent expressions.
6468  if (FD->isDependentContext())
6469    return true;
6470
6471  Expr::EvalStatus Status;
6472  Status.Diag = &Diags;
6473
6474  EvalInfo Info(FD->getASTContext(), Status);
6475  Info.CheckingPotentialConstantExpression = true;
6476
6477  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6478  const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6479
6480  // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6481  // is a temporary being used as the 'this' pointer.
6482  LValue This;
6483  ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6484  This.set(&VIE, Info.CurrentCall);
6485
6486  APValue Scratch;
6487  ArrayRef<const Expr*> Args;
6488
6489  SourceLocation Loc = FD->getLocation();
6490
6491  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6492    HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6493  } else
6494    HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6495                       Args, FD->getBody(), Info, Scratch);
6496
6497  return Diags.empty();
6498}
6499