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