blob: 2a7e8a7d3b2f50250c1cdd1a356d828d51c94a03 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
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//
Richard Smith253c2a32012-01-27 01:14:48 +000012// 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//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 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
Richard Smithd62306a2011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000070 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000071 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +000092 }
93
Richard Smitha8105bc2012-01-06 16:39:00 +000094 /// 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;
Richard Smith80815602011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000103 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;
Richard Smith66c96992012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith80815602011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith80815602011-11-07 05:07:52 +0000122 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000124 }
125
Richard Smitha8105bc2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000130 };
131
Richard Smith96e0c102011-11-04 02:25:55 +0000132 /// 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
Richard Smitha8105bc2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000141
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 /// 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;
Richard Smith96e0c102011-11-04 02:25:55 +0000152
Richard Smith80815602011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smitha8105bc2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 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) {
Richard Smith80815602011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith96e0c102011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000183
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) {
Richard Smith96e0c102011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000222
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 }
Richard Smith96e0c102011-11-04 02:25:55 +0000229 }
Richard Smith66c96992012-02-18 22:04:06 +0000230 /// 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 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith96e0c102011-11-04 02:25:55 +0000252 return;
253 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 // [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);
Richard Smith96e0c102011-11-04 02:25:55 +0000263 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smith254a73d2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000274
Richard Smithf6f003a2011-12-16 19:06:07 +0000275 /// 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
Richard Smithb228a862012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smithd62306a2011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith2e312c82012-03-03 22:46:17 +0000289 const APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000290
Eli Friedman4830ec82012-06-25 21:21:08 +0000291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000293 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
296 MapTy Temporaries;
297
Richard Smithf6f003a2011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith2e312c82012-03-03 22:46:17 +0000300 const APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000302 };
303
Richard Smith852c9db2013-04-20 22:23:05 +0000304 /// Temporarily override 'this'.
305 class ThisOverrideRAII {
306 public:
307 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
308 : Frame(Frame), OldThis(Frame.This) {
309 if (Enable)
310 Frame.This = NewThis;
311 }
312 ~ThisOverrideRAII() {
313 Frame.This = OldThis;
314 }
315 private:
316 CallStackFrame &Frame;
317 const LValue *OldThis;
318 };
319
Richard Smith92b1ce02011-12-12 09:28:41 +0000320 /// A partial diagnostic which we might know in advance that we are not going
321 /// to emit.
322 class OptionalDiagnostic {
323 PartialDiagnostic *Diag;
324
325 public:
326 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
327
328 template<typename T>
329 OptionalDiagnostic &operator<<(const T &v) {
330 if (Diag)
331 *Diag << v;
332 return *this;
333 }
Richard Smithfe800032012-01-31 04:08:20 +0000334
335 OptionalDiagnostic &operator<<(const APSInt &I) {
336 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000337 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000338 I.toString(Buffer);
339 *Diag << StringRef(Buffer.data(), Buffer.size());
340 }
341 return *this;
342 }
343
344 OptionalDiagnostic &operator<<(const APFloat &F) {
345 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000346 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000347 F.toString(Buffer);
348 *Diag << StringRef(Buffer.data(), Buffer.size());
349 }
350 return *this;
351 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000352 };
353
Richard Smithb228a862012-02-15 02:18:13 +0000354 /// EvalInfo - This is a private struct used by the evaluator to capture
355 /// information about a subexpression as it is folded. It retains information
356 /// about the AST context, but also maintains information about the folded
357 /// expression.
358 ///
359 /// If an expression could be evaluated, it is still possible it is not a C
360 /// "integer constant expression" or constant expression. If not, this struct
361 /// captures information about how and why not.
362 ///
363 /// One bit of information passed *into* the request for constant folding
364 /// indicates whether the subexpression is "evaluated" or not according to C
365 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
366 /// evaluate the expression regardless of what the RHS is, but C only allows
367 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000368 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000369 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000370
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000371 /// EvalStatus - Contains information about the evaluation.
372 Expr::EvalStatus &EvalStatus;
373
374 /// CurrentCall - The top of the constexpr call stack.
375 CallStackFrame *CurrentCall;
376
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000377 /// CallStackDepth - The number of calls in the call stack right now.
378 unsigned CallStackDepth;
379
Richard Smithb228a862012-02-15 02:18:13 +0000380 /// NextCallIndex - The next call index to assign.
381 unsigned NextCallIndex;
382
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000383 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000384 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000385 CallStackFrame BottomFrame;
386
Richard Smithd62306a2011-11-10 06:34:14 +0000387 /// EvaluatingDecl - This is the declaration whose initializer is being
388 /// evaluated, if any.
389 const VarDecl *EvaluatingDecl;
390
391 /// EvaluatingDeclValue - This is the value being constructed for the
392 /// declaration whose initializer is being evaluated, if any.
393 APValue *EvaluatingDeclValue;
394
Richard Smith357362d2011-12-13 06:39:58 +0000395 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
396 /// notes attached to it will also be stored, otherwise they will not be.
397 bool HasActiveDiagnostic;
398
Richard Smith253c2a32012-01-27 01:14:48 +0000399 /// CheckingPotentialConstantExpression - Are we checking whether the
400 /// expression is a potential constant expression? If so, some diagnostics
401 /// are suppressed.
402 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000403
404 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000405
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000406 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
407 bool OverflowCheckMode=false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000408 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000409 CallStackDepth(0), NextCallIndex(1),
410 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith253c2a32012-01-27 01:14:48 +0000411 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000412 CheckingPotentialConstantExpression(false),
413 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000414
Richard Smithd62306a2011-11-10 06:34:14 +0000415 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
416 EvaluatingDecl = VD;
417 EvaluatingDeclValue = &Value;
418 }
419
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000421
Richard Smith357362d2011-12-13 06:39:58 +0000422 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000423 // Don't perform any constexpr calls (other than the call we're checking)
424 // when checking a potential constant expression.
425 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
426 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000427 if (NextCallIndex == 0) {
428 // NextCallIndex has wrapped around.
429 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
430 return false;
431 }
Richard Smith357362d2011-12-13 06:39:58 +0000432 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
433 return true;
434 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
435 << getLangOpts().ConstexprCallDepth;
436 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000437 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000438
Richard Smithb228a862012-02-15 02:18:13 +0000439 CallStackFrame *getCallFrame(unsigned CallIndex) {
440 assert(CallIndex && "no call index in getCallFrame");
441 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
442 // be null in this loop.
443 CallStackFrame *Frame = CurrentCall;
444 while (Frame->Index > CallIndex)
445 Frame = Frame->Caller;
446 return (Frame->Index == CallIndex) ? Frame : 0;
447 }
448
Richard Smith357362d2011-12-13 06:39:58 +0000449 private:
450 /// Add a diagnostic to the diagnostics list.
451 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
452 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
453 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
454 return EvalStatus.Diag->back().second;
455 }
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 /// Add notes containing a call stack to the current point of evaluation.
458 void addCallStack(unsigned Limit);
459
Richard Smith357362d2011-12-13 06:39:58 +0000460 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000461 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000462 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
463 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000464 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000465 // If we have a prior diagnostic, it will be noting that the expression
466 // isn't a constant expression. This diagnostic is more important.
467 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000468 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000469 unsigned CallStackNotes = CallStackDepth - 1;
470 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
471 if (Limit)
472 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000473 if (CheckingPotentialConstantExpression)
474 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000475
Richard Smith357362d2011-12-13 06:39:58 +0000476 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000477 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000478 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
479 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000480 if (!CheckingPotentialConstantExpression)
481 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000482 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 }
Richard Smith357362d2011-12-13 06:39:58 +0000484 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
486 }
487
Richard Smithce1ec5e2012-03-15 04:53:45 +0000488 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
489 = diag::note_invalid_subexpr_in_const_expr,
490 unsigned ExtraNotes = 0) {
491 if (EvalStatus.Diag)
492 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
493 HasActiveDiagnostic = false;
494 return OptionalDiagnostic();
495 }
496
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000497 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
498
Richard Smith92b1ce02011-12-12 09:28:41 +0000499 /// Diagnose that the evaluation does not produce a C++11 core constant
500 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000501 template<typename LocArg>
502 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000503 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000504 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000505 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000506 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
507 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000508 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000509 }
Richard Smith357362d2011-12-13 06:39:58 +0000510 return Diag(Loc, DiagId, ExtraNotes);
511 }
512
513 /// Add a note to a prior diagnostic.
514 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
515 if (!HasActiveDiagnostic)
516 return OptionalDiagnostic();
517 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000518 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000519
520 /// Add a stack of notes to a prior diagnostic.
521 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
522 if (HasActiveDiagnostic) {
523 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
524 Diags.begin(), Diags.end());
525 }
526 }
Richard Smith253c2a32012-01-27 01:14:48 +0000527
528 /// Should we continue evaluation as much as possible after encountering a
529 /// construct which can't be folded?
530 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000531 // Should return true in IntOverflowCheckMode, so that we check for
532 // overflow even if some subexpressions can't be evaluated as constants.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000533 return IntOverflowCheckMode ||
534 (CheckingPotentialConstantExpression &&
535 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith253c2a32012-01-27 01:14:48 +0000536 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000538
539 /// Object used to treat all foldable expressions as constant expressions.
540 struct FoldConstant {
541 bool Enabled;
542
543 explicit FoldConstant(EvalInfo &Info)
544 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
545 !Info.EvalStatus.HasSideEffects) {
546 }
547 // Treat the value we've computed since this object was created as constant.
548 void Fold(EvalInfo &Info) {
549 if (Enabled && !Info.EvalStatus.Diag->empty() &&
550 !Info.EvalStatus.HasSideEffects)
551 Info.EvalStatus.Diag->clear();
552 }
553 };
Richard Smith17100ba2012-02-16 02:46:34 +0000554
555 /// RAII object used to suppress diagnostics and side-effects from a
556 /// speculative evaluation.
557 class SpeculativeEvaluationRAII {
558 EvalInfo &Info;
559 Expr::EvalStatus Old;
560
561 public:
562 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000563 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000564 : Info(Info), Old(Info.EvalStatus) {
565 Info.EvalStatus.Diag = NewDiag;
566 }
567 ~SpeculativeEvaluationRAII() {
568 Info.EvalStatus = Old;
569 }
570 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000571}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572
Richard Smitha8105bc2012-01-06 16:39:00 +0000573bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
574 CheckSubobjectKind CSK) {
575 if (Invalid)
576 return false;
577 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000578 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000579 << CSK;
580 setInvalid();
581 return false;
582 }
583 return true;
584}
585
586void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
587 const Expr *E, uint64_t N) {
588 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000589 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000590 << static_cast<int>(N) << /*array*/ 0
591 << static_cast<unsigned>(MostDerivedArraySize);
592 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << static_cast<int>(N) << /*non-array*/ 1;
595 setInvalid();
596}
597
Richard Smithf6f003a2011-12-16 19:06:07 +0000598CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
599 const FunctionDecl *Callee, const LValue *This,
Richard Smith2e312c82012-03-03 22:46:17 +0000600 const APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000601 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000602 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 Info.CurrentCall = this;
604 ++Info.CallStackDepth;
605}
606
607CallStackFrame::~CallStackFrame() {
608 assert(Info.CurrentCall == this && "calls retired out of order");
609 --Info.CallStackDepth;
610 Info.CurrentCall = Caller;
611}
612
613/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000614static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000615 unsigned ArgIndex = 0;
616 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000617 !isa<CXXConstructorDecl>(Frame->Callee) &&
618 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000619
620 if (!IsMemberCall)
621 Out << *Frame->Callee << '(';
622
623 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
624 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000625 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000626 Out << ", ";
627
628 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000629 const APValue &Arg = Frame->Arguments[ArgIndex];
630 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000631
632 if (ArgIndex == 0 && IsMemberCall)
633 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000634 }
635
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 Out << ')';
637}
638
639void EvalInfo::addCallStack(unsigned Limit) {
640 // Determine which calls to skip, if any.
641 unsigned ActiveCalls = CallStackDepth - 1;
642 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
643 if (Limit && Limit < ActiveCalls) {
644 SkipStart = Limit / 2 + Limit % 2;
645 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000646 }
647
Richard Smithf6f003a2011-12-16 19:06:07 +0000648 // Walk the call stack and add the diagnostics.
649 unsigned CallIdx = 0;
650 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
651 Frame = Frame->Caller, ++CallIdx) {
652 // Skip this call?
653 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
654 if (CallIdx == SkipStart) {
655 // Note that we're skipping calls.
656 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
657 << unsigned(ActiveCalls - Limit);
658 }
659 continue;
660 }
661
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000662 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 llvm::raw_svector_ostream Out(Buffer);
664 describeCall(Frame, Out);
665 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
666 }
667}
668
669namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000670 struct ComplexValue {
671 private:
672 bool IsInt;
673
674 public:
675 APSInt IntReal, IntImag;
676 APFloat FloatReal, FloatImag;
677
678 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
679
680 void makeComplexFloat() { IsInt = false; }
681 bool isComplexFloat() const { return !IsInt; }
682 APFloat &getComplexFloatReal() { return FloatReal; }
683 APFloat &getComplexFloatImag() { return FloatImag; }
684
685 void makeComplexInt() { IsInt = true; }
686 bool isComplexInt() const { return IsInt; }
687 APSInt &getComplexIntReal() { return IntReal; }
688 APSInt &getComplexIntImag() { return IntImag; }
689
Richard Smith2e312c82012-03-03 22:46:17 +0000690 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000691 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000692 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000693 else
Richard Smith2e312c82012-03-03 22:46:17 +0000694 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000695 }
Richard Smith2e312c82012-03-03 22:46:17 +0000696 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000697 assert(v.isComplexFloat() || v.isComplexInt());
698 if (v.isComplexFloat()) {
699 makeComplexFloat();
700 FloatReal = v.getComplexFloatReal();
701 FloatImag = v.getComplexFloatImag();
702 } else {
703 makeComplexInt();
704 IntReal = v.getComplexIntReal();
705 IntImag = v.getComplexIntImag();
706 }
707 }
John McCall93d91dc2010-05-07 17:22:02 +0000708 };
John McCall45d55e42010-05-07 21:00:08 +0000709
710 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000711 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000712 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000713 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000714 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000715
Richard Smithce40ad62011-11-12 22:28:03 +0000716 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000717 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000718 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000719 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000720 SubobjectDesignator &getLValueDesignator() { return Designator; }
721 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000722
Richard Smith2e312c82012-03-03 22:46:17 +0000723 void moveInto(APValue &V) const {
724 if (Designator.Invalid)
725 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
726 else
727 V = APValue(Base, Offset, Designator.Entries,
728 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000729 }
Richard Smith2e312c82012-03-03 22:46:17 +0000730 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000731 assert(V.isLValue());
732 Base = V.getLValueBase();
733 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000734 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000735 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000736 }
737
Richard Smithb228a862012-02-15 02:18:13 +0000738 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000739 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000740 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000741 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000742 Designator = SubobjectDesignator(getType(B));
743 }
744
745 // Check that this LValue is not based on a null pointer. If it is, produce
746 // a diagnostic and mark the designator as invalid.
747 bool checkNullPointer(EvalInfo &Info, const Expr *E,
748 CheckSubobjectKind CSK) {
749 if (Designator.Invalid)
750 return false;
751 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000752 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000753 << CSK;
754 Designator.setInvalid();
755 return false;
756 }
757 return true;
758 }
759
760 // Check this LValue refers to an object. If not, set the designator to be
761 // invalid and emit a diagnostic.
762 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000763 // Outside C++11, do not build a designator referring to a subobject of
764 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000765 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000767 return checkNullPointer(Info, E, CSK) &&
768 Designator.checkSubobject(Info, E, CSK);
769 }
770
771 void addDecl(EvalInfo &Info, const Expr *E,
772 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000773 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
774 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000775 }
776 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000777 if (checkSubobject(Info, E, CSK_ArrayToPointer))
778 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000779 }
Richard Smith66c96992012-02-18 22:04:06 +0000780 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
782 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000783 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000784 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000785 if (checkNullPointer(Info, E, CSK_ArrayIndex))
786 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000787 }
John McCall45d55e42010-05-07 21:00:08 +0000788 };
Richard Smith027bf112011-11-17 22:56:20 +0000789
790 struct MemberPtr {
791 MemberPtr() {}
792 explicit MemberPtr(const ValueDecl *Decl) :
793 DeclAndIsDerivedMember(Decl, false), Path() {}
794
795 /// The member or (direct or indirect) field referred to by this member
796 /// pointer, or 0 if this is a null member pointer.
797 const ValueDecl *getDecl() const {
798 return DeclAndIsDerivedMember.getPointer();
799 }
800 /// Is this actually a member of some type derived from the relevant class?
801 bool isDerivedMember() const {
802 return DeclAndIsDerivedMember.getInt();
803 }
804 /// Get the class which the declaration actually lives in.
805 const CXXRecordDecl *getContainingRecord() const {
806 return cast<CXXRecordDecl>(
807 DeclAndIsDerivedMember.getPointer()->getDeclContext());
808 }
809
Richard Smith2e312c82012-03-03 22:46:17 +0000810 void moveInto(APValue &V) const {
811 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000812 }
Richard Smith2e312c82012-03-03 22:46:17 +0000813 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000814 assert(V.isMemberPointer());
815 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
816 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
817 Path.clear();
818 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
819 Path.insert(Path.end(), P.begin(), P.end());
820 }
821
822 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
823 /// whether the member is a member of some class derived from the class type
824 /// of the member pointer.
825 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
826 /// Path - The path of base/derived classes from the member declaration's
827 /// class (exclusive) to the class type of the member pointer (inclusive).
828 SmallVector<const CXXRecordDecl*, 4> Path;
829
830 /// Perform a cast towards the class of the Decl (either up or down the
831 /// hierarchy).
832 bool castBack(const CXXRecordDecl *Class) {
833 assert(!Path.empty());
834 const CXXRecordDecl *Expected;
835 if (Path.size() >= 2)
836 Expected = Path[Path.size() - 2];
837 else
838 Expected = getContainingRecord();
839 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
840 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
841 // if B does not contain the original member and is not a base or
842 // derived class of the class containing the original member, the result
843 // of the cast is undefined.
844 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
845 // (D::*). We consider that to be a language defect.
846 return false;
847 }
848 Path.pop_back();
849 return true;
850 }
851 /// Perform a base-to-derived member pointer cast.
852 bool castToDerived(const CXXRecordDecl *Derived) {
853 if (!getDecl())
854 return true;
855 if (!isDerivedMember()) {
856 Path.push_back(Derived);
857 return true;
858 }
859 if (!castBack(Derived))
860 return false;
861 if (Path.empty())
862 DeclAndIsDerivedMember.setInt(false);
863 return true;
864 }
865 /// Perform a derived-to-base member pointer cast.
866 bool castToBase(const CXXRecordDecl *Base) {
867 if (!getDecl())
868 return true;
869 if (Path.empty())
870 DeclAndIsDerivedMember.setInt(true);
871 if (isDerivedMember()) {
872 Path.push_back(Base);
873 return true;
874 }
875 return castBack(Base);
876 }
877 };
Richard Smith357362d2011-12-13 06:39:58 +0000878
Richard Smith7bb00672012-02-01 01:42:44 +0000879 /// Compare two member pointers, which are assumed to be of the same type.
880 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
881 if (!LHS.getDecl() || !RHS.getDecl())
882 return !LHS.getDecl() && !RHS.getDecl();
883 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
884 return false;
885 return LHS.Path == RHS.Path;
886 }
887
Richard Smith357362d2011-12-13 06:39:58 +0000888 /// Kinds of constant expression checking, for diagnostics.
889 enum CheckConstantExpressionKind {
890 CCEK_Constant, ///< A normal constant.
891 CCEK_ReturnValue, ///< A constexpr function return value.
892 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
893 };
John McCall93d91dc2010-05-07 17:22:02 +0000894}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000895
Richard Smith2e312c82012-03-03 22:46:17 +0000896static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000897static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
898 const LValue &This, const Expr *E,
899 CheckConstantExpressionKind CCEK = CCEK_Constant,
900 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000901static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
902static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000903static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
904 EvalInfo &Info);
905static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000906static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000907static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000908 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000909static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000910static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000911
912//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000913// Misc utilities
914//===----------------------------------------------------------------------===//
915
Richard Smithd9f663b2013-04-22 15:31:51 +0000916/// Evaluate an expression to see if it had side-effects, and discard its
917/// result.
918static void EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
919 APValue Scratch;
920 if (!Evaluate(Scratch, Info, E))
921 Info.EvalStatus.HasSideEffects = true;
922}
923
Richard Smithd62306a2011-11-10 06:34:14 +0000924/// Should this call expression be treated as a string literal?
925static bool IsStringLiteralCall(const CallExpr *E) {
926 unsigned Builtin = E->isBuiltinCall();
927 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
928 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
929}
930
Richard Smithce40ad62011-11-12 22:28:03 +0000931static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000932 // C++11 [expr.const]p3 An address constant expression is a prvalue core
933 // constant expression of pointer type that evaluates to...
934
935 // ... a null pointer value, or a prvalue core constant expression of type
936 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000937 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000938
Richard Smithce40ad62011-11-12 22:28:03 +0000939 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
940 // ... the address of an object with static storage duration,
941 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
942 return VD->hasGlobalStorage();
943 // ... the address of a function,
944 return isa<FunctionDecl>(D);
945 }
946
947 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000948 switch (E->getStmtClass()) {
949 default:
950 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000951 case Expr::CompoundLiteralExprClass: {
952 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
953 return CLE->isFileScope() && CLE->isLValue();
954 }
Richard Smithd62306a2011-11-10 06:34:14 +0000955 // A string literal has static storage duration.
956 case Expr::StringLiteralClass:
957 case Expr::PredefinedExprClass:
958 case Expr::ObjCStringLiteralClass:
959 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000960 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000961 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000962 return true;
963 case Expr::CallExprClass:
964 return IsStringLiteralCall(cast<CallExpr>(E));
965 // For GCC compatibility, &&label has static storage duration.
966 case Expr::AddrLabelExprClass:
967 return true;
968 // A Block literal expression may be used as the initialization value for
969 // Block variables at global or local static scope.
970 case Expr::BlockExprClass:
971 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000972 case Expr::ImplicitValueInitExprClass:
973 // FIXME:
974 // We can never form an lvalue with an implicit value initialization as its
975 // base through expression evaluation, so these only appear in one case: the
976 // implicit variable declaration we invent when checking whether a constexpr
977 // constructor can produce a constant expression. We must assume that such
978 // an expression might be a global lvalue.
979 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000980 }
John McCall95007602010-05-10 23:27:23 +0000981}
982
Richard Smithb228a862012-02-15 02:18:13 +0000983static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
984 assert(Base && "no location for a null lvalue");
985 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
986 if (VD)
987 Info.Note(VD->getLocation(), diag::note_declared_at);
988 else
Ted Kremenek28831752012-08-23 20:46:57 +0000989 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000990 diag::note_constexpr_temporary_here);
991}
992
Richard Smith80815602011-11-07 05:07:52 +0000993/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000994/// value for an address or reference constant expression. Return true if we
995/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +0000996static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
997 QualType Type, const LValue &LVal) {
998 bool IsReferenceType = Type->isReferenceType();
999
Richard Smith357362d2011-12-13 06:39:58 +00001000 APValue::LValueBase Base = LVal.getLValueBase();
1001 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1002
Richard Smith0dea49e2012-02-18 04:58:18 +00001003 // Check that the object is a global. Note that the fake 'this' object we
1004 // manufacture when checking potential constant expressions is conservatively
1005 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001006 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001007 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001008 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001009 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1010 << IsReferenceType << !Designator.Entries.empty()
1011 << !!VD << VD;
1012 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001013 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001014 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001015 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001016 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001017 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001018 }
Richard Smithb228a862012-02-15 02:18:13 +00001019 assert((Info.CheckingPotentialConstantExpression ||
1020 LVal.getLValueCallIndex() == 0) &&
1021 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001022
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001023 // Check if this is a thread-local variable.
1024 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1025 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001026 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001027 return false;
1028 }
1029 }
1030
Richard Smitha8105bc2012-01-06 16:39:00 +00001031 // Allow address constant expressions to be past-the-end pointers. This is
1032 // an extension: the standard requires them to point to an object.
1033 if (!IsReferenceType)
1034 return true;
1035
1036 // A reference constant expression must refer to an object.
1037 if (!Base) {
1038 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001039 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001040 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001041 }
1042
Richard Smith357362d2011-12-13 06:39:58 +00001043 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001044 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001045 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001046 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001047 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001048 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001049 }
1050
Richard Smith80815602011-11-07 05:07:52 +00001051 return true;
1052}
1053
Richard Smithfddd3842011-12-30 21:15:51 +00001054/// Check that this core constant expression is of literal type, and if not,
1055/// produce an appropriate diagnostic.
1056static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001057 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001058 return true;
1059
1060 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001061 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001062 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001063 << E->getType();
1064 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001065 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001066 return false;
1067}
1068
Richard Smith0b0a0b62011-10-29 20:57:55 +00001069/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001070/// constant expression. If not, report an appropriate diagnostic. Does not
1071/// check that the expression is of literal type.
1072static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1073 QualType Type, const APValue &Value) {
1074 // Core issue 1454: For a literal constant expression of array or class type,
1075 // each subobject of its value shall have been initialized by a constant
1076 // expression.
1077 if (Value.isArray()) {
1078 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1079 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1080 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1081 Value.getArrayInitializedElt(I)))
1082 return false;
1083 }
1084 if (!Value.hasArrayFiller())
1085 return true;
1086 return CheckConstantExpression(Info, DiagLoc, EltTy,
1087 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001088 }
Richard Smithb228a862012-02-15 02:18:13 +00001089 if (Value.isUnion() && Value.getUnionField()) {
1090 return CheckConstantExpression(Info, DiagLoc,
1091 Value.getUnionField()->getType(),
1092 Value.getUnionValue());
1093 }
1094 if (Value.isStruct()) {
1095 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1096 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1097 unsigned BaseIndex = 0;
1098 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1099 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1100 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1101 Value.getStructBase(BaseIndex)))
1102 return false;
1103 }
1104 }
1105 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1106 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001107 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1108 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001109 return false;
1110 }
1111 }
1112
1113 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001114 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001115 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001116 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1117 }
1118
1119 // Everything else is fine.
1120 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001121}
1122
Richard Smith83c68212011-10-31 05:11:32 +00001123const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001124 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001125}
1126
1127static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001128 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001129}
1130
Richard Smithcecf1842011-11-01 21:06:14 +00001131static bool IsWeakLValue(const LValue &Value) {
1132 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001133 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001134}
1135
Richard Smith2e312c82012-03-03 22:46:17 +00001136static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001137 // A null base expression indicates a null pointer. These are always
1138 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001139 if (!Value.getLValueBase()) {
1140 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001141 return true;
1142 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001143
Richard Smith027bf112011-11-17 22:56:20 +00001144 // We have a non-null base. These are generally known to be true, but if it's
1145 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001146 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001147 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001148 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001149}
1150
Richard Smith2e312c82012-03-03 22:46:17 +00001151static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001152 switch (Val.getKind()) {
1153 case APValue::Uninitialized:
1154 return false;
1155 case APValue::Int:
1156 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001157 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001158 case APValue::Float:
1159 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001160 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001161 case APValue::ComplexInt:
1162 Result = Val.getComplexIntReal().getBoolValue() ||
1163 Val.getComplexIntImag().getBoolValue();
1164 return true;
1165 case APValue::ComplexFloat:
1166 Result = !Val.getComplexFloatReal().isZero() ||
1167 !Val.getComplexFloatImag().isZero();
1168 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001169 case APValue::LValue:
1170 return EvalPointerValueAsBool(Val, Result);
1171 case APValue::MemberPointer:
1172 Result = Val.getMemberPointerDecl();
1173 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001174 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001175 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001176 case APValue::Struct:
1177 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001178 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001179 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001180 }
1181
Richard Smith11562c52011-10-28 17:51:58 +00001182 llvm_unreachable("unknown APValue kind");
1183}
1184
1185static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1186 EvalInfo &Info) {
1187 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001188 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001189 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001190 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001191 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001192}
1193
Richard Smith357362d2011-12-13 06:39:58 +00001194template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001195static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001196 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001197 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001198 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001199}
1200
1201static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1202 QualType SrcType, const APFloat &Value,
1203 QualType DestType, APSInt &Result) {
1204 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001205 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001206 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001207
Richard Smith357362d2011-12-13 06:39:58 +00001208 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001209 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001210 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1211 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001212 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001213 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001214}
1215
Richard Smith357362d2011-12-13 06:39:58 +00001216static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1217 QualType SrcType, QualType DestType,
1218 APFloat &Result) {
1219 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001220 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001221 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1222 APFloat::rmNearestTiesToEven, &ignored)
1223 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001224 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001225 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001226}
1227
Richard Smith911e1422012-01-30 22:27:01 +00001228static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1229 QualType DestType, QualType SrcType,
1230 APSInt &Value) {
1231 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001232 APSInt Result = Value;
1233 // Figure out if this is a truncate, extend or noop cast.
1234 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001235 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001236 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001237 return Result;
1238}
1239
Richard Smith357362d2011-12-13 06:39:58 +00001240static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1241 QualType SrcType, const APSInt &Value,
1242 QualType DestType, APFloat &Result) {
1243 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1244 if (Result.convertFromAPInt(Value, Value.isSigned(),
1245 APFloat::rmNearestTiesToEven)
1246 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001247 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001248 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001249}
1250
Eli Friedman803acb32011-12-22 03:51:45 +00001251static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1252 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001253 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001254 if (!Evaluate(SVal, Info, E))
1255 return false;
1256 if (SVal.isInt()) {
1257 Res = SVal.getInt();
1258 return true;
1259 }
1260 if (SVal.isFloat()) {
1261 Res = SVal.getFloat().bitcastToAPInt();
1262 return true;
1263 }
1264 if (SVal.isVector()) {
1265 QualType VecTy = E->getType();
1266 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1267 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1268 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1269 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1270 Res = llvm::APInt::getNullValue(VecSize);
1271 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1272 APValue &Elt = SVal.getVectorElt(i);
1273 llvm::APInt EltAsInt;
1274 if (Elt.isInt()) {
1275 EltAsInt = Elt.getInt();
1276 } else if (Elt.isFloat()) {
1277 EltAsInt = Elt.getFloat().bitcastToAPInt();
1278 } else {
1279 // Don't try to handle vectors of anything other than int or float
1280 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001281 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001282 return false;
1283 }
1284 unsigned BaseEltSize = EltAsInt.getBitWidth();
1285 if (BigEndian)
1286 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1287 else
1288 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1289 }
1290 return true;
1291 }
1292 // Give up if the input isn't an int, float, or vector. For example, we
1293 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001294 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001295 return false;
1296}
1297
Richard Smitha8105bc2012-01-06 16:39:00 +00001298/// Cast an lvalue referring to a base subobject to a derived class, by
1299/// truncating the lvalue's path to the given length.
1300static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1301 const RecordDecl *TruncatedType,
1302 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001303 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001304
1305 // Check we actually point to a derived class object.
1306 if (TruncatedElements == D.Entries.size())
1307 return true;
1308 assert(TruncatedElements >= D.MostDerivedPathLength &&
1309 "not casting to a derived class");
1310 if (!Result.checkSubobject(Info, E, CSK_Derived))
1311 return false;
1312
1313 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001314 const RecordDecl *RD = TruncatedType;
1315 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001316 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001317 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1318 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001319 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001320 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001321 else
Richard Smithd62306a2011-11-10 06:34:14 +00001322 Result.Offset -= Layout.getBaseClassOffset(Base);
1323 RD = Base;
1324 }
Richard Smith027bf112011-11-17 22:56:20 +00001325 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001326 return true;
1327}
1328
John McCalld7bca762012-05-01 00:38:49 +00001329static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001330 const CXXRecordDecl *Derived,
1331 const CXXRecordDecl *Base,
1332 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001333 if (!RL) {
1334 if (Derived->isInvalidDecl()) return false;
1335 RL = &Info.Ctx.getASTRecordLayout(Derived);
1336 }
1337
Richard Smithd62306a2011-11-10 06:34:14 +00001338 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001339 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001340 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001341}
1342
Richard Smitha8105bc2012-01-06 16:39:00 +00001343static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001344 const CXXRecordDecl *DerivedDecl,
1345 const CXXBaseSpecifier *Base) {
1346 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1347
John McCalld7bca762012-05-01 00:38:49 +00001348 if (!Base->isVirtual())
1349 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001350
Richard Smitha8105bc2012-01-06 16:39:00 +00001351 SubobjectDesignator &D = Obj.Designator;
1352 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001353 return false;
1354
Richard Smitha8105bc2012-01-06 16:39:00 +00001355 // Extract most-derived object and corresponding type.
1356 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1357 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1358 return false;
1359
1360 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001361 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001362 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1363 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001364 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001365 return true;
1366}
1367
1368/// Update LVal to refer to the given field, which must be a member of the type
1369/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001370static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001371 const FieldDecl *FD,
1372 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001373 if (!RL) {
1374 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001375 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001376 }
Richard Smithd62306a2011-11-10 06:34:14 +00001377
1378 unsigned I = FD->getFieldIndex();
1379 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001380 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001381 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001382}
1383
Richard Smith1b78b3d2012-01-25 22:15:11 +00001384/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001385static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001386 LValue &LVal,
1387 const IndirectFieldDecl *IFD) {
1388 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1389 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001390 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1391 return false;
1392 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001393}
1394
Richard Smithd62306a2011-11-10 06:34:14 +00001395/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001396static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1397 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001398 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1399 // extension.
1400 if (Type->isVoidType() || Type->isFunctionType()) {
1401 Size = CharUnits::One();
1402 return true;
1403 }
1404
1405 if (!Type->isConstantSizeType()) {
1406 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001407 // FIXME: Better diagnostic.
1408 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001409 return false;
1410 }
1411
1412 Size = Info.Ctx.getTypeSizeInChars(Type);
1413 return true;
1414}
1415
1416/// Update a pointer value to model pointer arithmetic.
1417/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001418/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001419/// \param LVal - The pointer value to be updated.
1420/// \param EltTy - The pointee type represented by LVal.
1421/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001422static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1423 LValue &LVal, QualType EltTy,
1424 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001425 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001426 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001427 return false;
1428
1429 // Compute the new offset in the appropriate width.
1430 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001431 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001432 return true;
1433}
1434
Richard Smith66c96992012-02-18 22:04:06 +00001435/// Update an lvalue to refer to a component of a complex number.
1436/// \param Info - Information about the ongoing evaluation.
1437/// \param LVal - The lvalue to be updated.
1438/// \param EltTy - The complex number's component type.
1439/// \param Imag - False for the real component, true for the imaginary.
1440static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1441 LValue &LVal, QualType EltTy,
1442 bool Imag) {
1443 if (Imag) {
1444 CharUnits SizeOfComponent;
1445 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1446 return false;
1447 LVal.Offset += SizeOfComponent;
1448 }
1449 LVal.addComplex(Info, E, EltTy, Imag);
1450 return true;
1451}
1452
Richard Smith27908702011-10-24 17:54:18 +00001453/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001454static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1455 const VarDecl *VD,
Richard Smith2e312c82012-03-03 22:46:17 +00001456 CallStackFrame *Frame, APValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001457 // If this is a parameter to an active constexpr function call, perform
1458 // argument substitution.
1459 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001460 // Assume arguments of a potential constant expression are unknown
1461 // constant expressions.
1462 if (Info.CheckingPotentialConstantExpression)
1463 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001464 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001465 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001466 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001467 }
Richard Smithfec09922011-11-01 16:57:24 +00001468 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1469 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001470 }
Richard Smith27908702011-10-24 17:54:18 +00001471
Richard Smithd9f663b2013-04-22 15:31:51 +00001472 // If this is a local variable, dig out its value.
1473 if (VD->hasLocalStorage() && Frame && Frame->Index > 1) {
1474 Result = Frame->Temporaries[VD];
1475 // If we've carried on past an unevaluatable local variable initializer,
1476 // we can't go any further. This can happen during potential constant
1477 // expression checking.
1478 return !Result.isUninit();
1479 }
1480
Richard Smithd0b4dd62011-12-19 06:19:21 +00001481 // Dig out the initializer, and use the declaration which it's attached to.
1482 const Expr *Init = VD->getAnyInitializer(VD);
1483 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001484 // If we're checking a potential constant expression, the variable could be
1485 // initialized later.
1486 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001487 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001488 return false;
1489 }
1490
Richard Smithd62306a2011-11-10 06:34:14 +00001491 // If we're currently evaluating the initializer of this declaration, use that
1492 // in-flight value.
1493 if (Info.EvaluatingDecl == VD) {
Richard Smith2e312c82012-03-03 22:46:17 +00001494 Result = *Info.EvaluatingDeclValue;
Richard Smithd62306a2011-11-10 06:34:14 +00001495 return !Result.isUninit();
1496 }
1497
Richard Smithcecf1842011-11-01 21:06:14 +00001498 // Never evaluate the initializer of a weak variable. We can't be sure that
1499 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001500 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001501 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001502 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001503 }
Richard Smithcecf1842011-11-01 21:06:14 +00001504
Richard Smithd0b4dd62011-12-19 06:19:21 +00001505 // Check that we can fold the initializer. In C++, we will have already done
1506 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001507 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001508 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001509 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001510 Notes.size() + 1) << VD;
1511 Info.Note(VD->getLocation(), diag::note_declared_at);
1512 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001513 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001514 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001515 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001516 Notes.size() + 1) << VD;
1517 Info.Note(VD->getLocation(), diag::note_declared_at);
1518 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001519 }
Richard Smith27908702011-10-24 17:54:18 +00001520
Richard Smith2e312c82012-03-03 22:46:17 +00001521 Result = *VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001522 return true;
Richard Smith27908702011-10-24 17:54:18 +00001523}
1524
Richard Smith11562c52011-10-28 17:51:58 +00001525static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001526 Qualifiers Quals = T.getQualifiers();
1527 return Quals.hasConst() && !Quals.hasVolatile();
1528}
1529
Richard Smithe97cbd72011-11-11 04:05:33 +00001530/// Get the base index of the given base class within an APValue representing
1531/// the given derived class.
1532static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1533 const CXXRecordDecl *Base) {
1534 Base = Base->getCanonicalDecl();
1535 unsigned Index = 0;
1536 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1537 E = Derived->bases_end(); I != E; ++I, ++Index) {
1538 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1539 return Index;
1540 }
1541
1542 llvm_unreachable("base class missing from derived class's bases list");
1543}
1544
Richard Smith9ec1e482012-04-15 02:50:59 +00001545/// Extract the value of a character from a string literal. CharType is used to
1546/// determine the expected signedness of the result -- a string literal used to
1547/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1548/// of the wrong signedness.
Richard Smith14a94132012-02-17 03:35:37 +00001549static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smith9ec1e482012-04-15 02:50:59 +00001550 uint64_t Index, QualType CharType) {
Richard Smith14a94132012-02-17 03:35:37 +00001551 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1552 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1553 assert(S && "unexpected string literal expression kind");
Richard Smith9ec1e482012-04-15 02:50:59 +00001554 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001555
1556 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001557 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001558 if (Index < S->getLength())
1559 Value = S->getCodeUnit(Index);
1560 return Value;
1561}
1562
Richard Smithf3e9e432011-11-07 09:22:26 +00001563/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001564static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith2e312c82012-03-03 22:46:17 +00001565 APValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001566 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001567 if (Sub.Invalid)
1568 // A diagnostic will have already been produced.
Richard Smithf3e9e432011-11-07 09:22:26 +00001569 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001570 if (Sub.isOnePastTheEnd()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001571 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001572 (unsigned)diag::note_constexpr_read_past_end :
1573 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001574 return false;
1575 }
Richard Smith6804be52011-11-11 08:28:03 +00001576 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001577 return true;
Richard Smith253c2a32012-01-27 01:14:48 +00001578 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1579 // This object might be initialized later.
1580 return false;
Richard Smithf3e9e432011-11-07 09:22:26 +00001581
Richard Smith4e9e5232012-03-10 00:28:11 +00001582 APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001583 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001584 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001585 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001586 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001587 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001588 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001589 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001590 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001591 // Note, it should not be possible to form a pointer with a valid
1592 // designator which points more than one past the end of the array.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001593 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001594 (unsigned)diag::note_constexpr_read_past_end :
1595 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001596 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001597 }
Richard Smith14a94132012-02-17 03:35:37 +00001598 // An array object is represented as either an Array APValue or as an
1599 // LValue which refers to a string literal.
1600 if (O->isLValue()) {
1601 assert(I == N - 1 && "extracting subobject of character?");
1602 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith2e312c82012-03-03 22:46:17 +00001603 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smith9ec1e482012-04-15 02:50:59 +00001604 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smith14a94132012-02-17 03:35:37 +00001605 return true;
1606 } else if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001607 O = &O->getArrayInitializedElt(Index);
1608 else
1609 O = &O->getArrayFiller();
1610 ObjType = CAT->getElementType();
Richard Smith66c96992012-02-18 22:04:06 +00001611 } else if (ObjType->isAnyComplexType()) {
1612 // Next subobject is a complex number.
1613 uint64_t Index = Sub.Entries[I].ArrayIndex;
1614 if (Index > 1) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001615 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Richard Smith66c96992012-02-18 22:04:06 +00001616 (unsigned)diag::note_constexpr_read_past_end :
1617 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1618 return false;
1619 }
1620 assert(I == N - 1 && "extracting subobject of scalar?");
1621 if (O->isComplexInt()) {
Richard Smith2e312c82012-03-03 22:46:17 +00001622 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith66c96992012-02-18 22:04:06 +00001623 : O->getComplexIntReal());
1624 } else {
1625 assert(O->isComplexFloat());
Richard Smith2e312c82012-03-03 22:46:17 +00001626 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith66c96992012-02-18 22:04:06 +00001627 : O->getComplexFloatReal());
1628 }
1629 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001630 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith5a294e62012-02-09 03:29:58 +00001631 if (Field->isMutable()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001632 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001633 << Field;
1634 Info.Note(Field->getLocation(), diag::note_declared_at);
1635 return false;
1636 }
1637
Richard Smithd62306a2011-11-10 06:34:14 +00001638 // Next subobject is a class, struct or union field.
1639 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1640 if (RD->isUnion()) {
1641 const FieldDecl *UnionField = O->getUnionField();
1642 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001643 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001644 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smithf2b681b2011-12-21 05:04:46 +00001645 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001646 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001647 }
Richard Smithd62306a2011-11-10 06:34:14 +00001648 O = &O->getUnionValue();
1649 } else
1650 O = &O->getStructField(Field->getFieldIndex());
1651 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001652
1653 if (ObjType.isVolatileQualified()) {
1654 if (Info.getLangOpts().CPlusPlus) {
1655 // FIXME: Include a description of the path to the volatile subobject.
Richard Smithce1ec5e2012-03-15 04:53:45 +00001656 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smithf2b681b2011-12-21 05:04:46 +00001657 << 2 << Field;
1658 Info.Note(Field->getLocation(), diag::note_declared_at);
1659 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001660 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001661 }
1662 return false;
1663 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001664 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001665 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001666 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1667 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1668 O = &O->getStructBase(getBaseIndex(Derived, Base));
1669 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001670 }
Richard Smithd62306a2011-11-10 06:34:14 +00001671
Richard Smithf57d8cb2011-12-09 22:58:01 +00001672 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001673 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001674 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001675 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001676 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001677 }
1678
Richard Smith4e9e5232012-03-10 00:28:11 +00001679 // This may look super-stupid, but it serves an important purpose: if we just
1680 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1681 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1682 // object, which is destroyed by Tmp's destructor.
1683 APValue Tmp;
1684 O->swap(Tmp);
1685 Obj.swap(Tmp);
Richard Smithf3e9e432011-11-07 09:22:26 +00001686 return true;
1687}
1688
Richard Smith84f6dcf2012-02-02 01:16:57 +00001689/// Find the position where two subobject designators diverge, or equivalently
1690/// the length of the common initial subsequence.
1691static unsigned FindDesignatorMismatch(QualType ObjType,
1692 const SubobjectDesignator &A,
1693 const SubobjectDesignator &B,
1694 bool &WasArrayIndex) {
1695 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1696 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001697 if (!ObjType.isNull() &&
1698 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001699 // Next subobject is an array element.
1700 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1701 WasArrayIndex = true;
1702 return I;
1703 }
Richard Smith66c96992012-02-18 22:04:06 +00001704 if (ObjType->isAnyComplexType())
1705 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1706 else
1707 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001708 } else {
1709 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1710 WasArrayIndex = false;
1711 return I;
1712 }
1713 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1714 // Next subobject is a field.
1715 ObjType = FD->getType();
1716 else
1717 // Next subobject is a base class.
1718 ObjType = QualType();
1719 }
1720 }
1721 WasArrayIndex = false;
1722 return I;
1723}
1724
1725/// Determine whether the given subobject designators refer to elements of the
1726/// same array object.
1727static bool AreElementsOfSameArray(QualType ObjType,
1728 const SubobjectDesignator &A,
1729 const SubobjectDesignator &B) {
1730 if (A.Entries.size() != B.Entries.size())
1731 return false;
1732
1733 bool IsArray = A.MostDerivedArraySize != 0;
1734 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1735 // A is a subobject of the array element.
1736 return false;
1737
1738 // If A (and B) designates an array element, the last entry will be the array
1739 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1740 // of length 1' case, and the entire path must match.
1741 bool WasArrayIndex;
1742 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1743 return CommonLength >= A.Entries.size() - IsArray;
1744}
1745
Richard Smithd62306a2011-11-10 06:34:14 +00001746/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1747/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1748/// for looking up the glvalue referred to by an entity of reference type.
1749///
1750/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001751/// \param Conv - The expression for which we are performing the conversion.
1752/// Used for diagnostics.
Richard Smithc82fae62012-02-05 01:23:16 +00001753/// \param Type - The type we expect this conversion to produce, before
1754/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smithd62306a2011-11-10 06:34:14 +00001755/// \param LVal - The glvalue on which we are attempting to perform this action.
1756/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001757static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1758 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00001759 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001760 if (LVal.Designator.Invalid)
1761 // A diagnostic will have already been produced.
1762 return false;
1763
Richard Smithce40ad62011-11-12 22:28:03 +00001764 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith11562c52011-10-28 17:51:58 +00001765
Richard Smithf57d8cb2011-12-09 22:58:01 +00001766 if (!LVal.Base) {
1767 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithce1ec5e2012-03-15 04:53:45 +00001768 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001769 return false;
1770 }
1771
Richard Smithb228a862012-02-15 02:18:13 +00001772 CallStackFrame *Frame = 0;
1773 if (LVal.CallIndex) {
1774 Frame = Info.getCallFrame(LVal.CallIndex);
1775 if (!Frame) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001776 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001777 NoteLValueLocation(Info, LVal.Base);
1778 return false;
1779 }
1780 }
1781
Richard Smithf2b681b2011-12-21 05:04:46 +00001782 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1783 // is not a constant expression (even if the object is non-volatile). We also
1784 // apply this rule to C++98, in order to conform to the expected 'volatile'
1785 // semantics.
1786 if (Type.isVolatileQualified()) {
1787 if (Info.getLangOpts().CPlusPlus)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001788 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smithf2b681b2011-12-21 05:04:46 +00001789 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001790 Info.Diag(Conv);
Richard Smith11562c52011-10-28 17:51:58 +00001791 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001792 }
Richard Smith11562c52011-10-28 17:51:58 +00001793
Richard Smithce40ad62011-11-12 22:28:03 +00001794 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001795 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1796 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001797 // expressions are constant expressions too. Inside constexpr functions,
1798 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001799 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001800 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001801 if (VD) {
1802 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1803 VD = VDef;
1804 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001805 if (!VD || VD->isInvalidDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001806 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00001807 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001808 }
1809
Richard Smithf2b681b2011-12-21 05:04:46 +00001810 // DR1313: If the object is volatile-qualified but the glvalue was not,
1811 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001812 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001813 if (VT.isVolatileQualified()) {
1814 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001815 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001816 Info.Note(VD->getLocation(), diag::note_declared_at);
1817 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001818 Info.Diag(Conv);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001819 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001820 return false;
1821 }
1822
Richard Smithd9f663b2013-04-22 15:31:51 +00001823 // Unless we're looking at a local variable or argument in a constexpr call,
1824 // the variable we're reading must be const.
1825 if (LVal.CallIndex <= 1 || !VD->hasLocalStorage()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001826 if (VD->isConstexpr()) {
1827 // OK, we can read this variable.
1828 } else if (VT->isIntegralOrEnumerationType()) {
1829 if (!VT.isConstQualified()) {
1830 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001831 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001832 Info.Note(VD->getLocation(), diag::note_declared_at);
1833 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001834 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001835 }
1836 return false;
1837 }
1838 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1839 // We support folding of const floating-point types, in order to make
1840 // static const data members of such types (supported as an extension)
1841 // more useful.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001842 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001843 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001844 Info.Note(VD->getLocation(), diag::note_declared_at);
1845 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001846 Info.CCEDiag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001847 }
1848 } else {
1849 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001850 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001851 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001852 Info.Note(VD->getLocation(), diag::note_declared_at);
1853 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001854 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001855 }
Richard Smith96e0c102011-11-04 02:25:55 +00001856 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001857 }
Richard Smith96e0c102011-11-04 02:25:55 +00001858 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001859
Richard Smithf57d8cb2011-12-09 22:58:01 +00001860 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001861 return false;
1862
Richard Smith0b0a0b62011-10-29 20:57:55 +00001863 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001864 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001865
1866 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1867 // conversion. This happens when the declaration and the lvalue should be
1868 // considered synonymous, for instance when initializing an array of char
1869 // from a string literal. Continue as if the initializer lvalue was the
1870 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001871 assert(RVal.getLValueOffset().isZero() &&
1872 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001873 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithb228a862012-02-15 02:18:13 +00001874
1875 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1876 Frame = Info.getCallFrame(CallIndex);
1877 if (!Frame) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001878 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001879 NoteLValueLocation(Info, RVal.getLValueBase());
1880 return false;
1881 }
1882 } else {
1883 Frame = 0;
1884 }
Richard Smith11562c52011-10-28 17:51:58 +00001885 }
1886
Richard Smithf2b681b2011-12-21 05:04:46 +00001887 // Volatile temporary objects cannot be read in constant expressions.
1888 if (Base->getType().isVolatileQualified()) {
1889 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001890 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smithf2b681b2011-12-21 05:04:46 +00001891 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1892 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001893 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001894 }
1895 return false;
1896 }
1897
Richard Smithf3e9e432011-11-07 09:22:26 +00001898 if (Frame) {
1899 // If this is a temporary expression with a nontrivial initializer, grab the
1900 // value from the relevant stack frame.
1901 RVal = Frame->Temporaries[Base];
1902 } else if (const CompoundLiteralExpr *CLE
1903 = dyn_cast<CompoundLiteralExpr>(Base)) {
1904 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1905 // initializer until now for such expressions. Such an expression can't be
1906 // an ICE in C, so this only matters for fold.
1907 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1908 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1909 return false;
Richard Smith14a94132012-02-17 03:35:37 +00001910 } else if (isa<StringLiteral>(Base)) {
1911 // We represent a string literal array as an lvalue pointing at the
1912 // corresponding expression, rather than building an array of chars.
1913 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith2e312c82012-03-03 22:46:17 +00001914 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001915 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001916 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001917 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001918 }
Richard Smith96e0c102011-11-04 02:25:55 +00001919
Richard Smithf57d8cb2011-12-09 22:58:01 +00001920 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1921 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001922}
1923
Richard Smithe97cbd72011-11-11 04:05:33 +00001924/// Build an lvalue for the object argument of a member function call.
1925static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1926 LValue &This) {
1927 if (Object->getType()->isPointerType())
1928 return EvaluatePointer(Object, This, Info);
1929
1930 if (Object->isGLValue())
1931 return EvaluateLValue(Object, This, Info);
1932
Richard Smithd9f663b2013-04-22 15:31:51 +00001933 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00001934 return EvaluateTemporary(Object, This, Info);
1935
1936 return false;
1937}
1938
1939/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1940/// lvalue referring to the result.
1941///
1942/// \param Info - Information about the ongoing evaluation.
1943/// \param BO - The member pointer access operation.
1944/// \param LV - Filled in with a reference to the resulting object.
1945/// \param IncludeMember - Specifies whether the member itself is included in
1946/// the resulting LValue subobject designator. This is not possible when
1947/// creating a bound member function.
1948/// \return The field or method declaration to which the member pointer refers,
1949/// or 0 if evaluation fails.
1950static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1951 const BinaryOperator *BO,
1952 LValue &LV,
1953 bool IncludeMember = true) {
1954 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1955
Richard Smith253c2a32012-01-27 01:14:48 +00001956 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1957 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00001958 return 0;
1959
1960 MemberPtr MemPtr;
1961 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1962 return 0;
1963
1964 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1965 // member value, the behavior is undefined.
1966 if (!MemPtr.getDecl())
1967 return 0;
1968
Richard Smith253c2a32012-01-27 01:14:48 +00001969 if (!EvalObjOK)
1970 return 0;
1971
Richard Smith027bf112011-11-17 22:56:20 +00001972 if (MemPtr.isDerivedMember()) {
1973 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00001974 // The end of the derived-to-base path for the base object must match the
1975 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00001976 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00001977 LV.Designator.Entries.size())
1978 return 0;
1979 unsigned PathLengthToMember =
1980 LV.Designator.Entries.size() - MemPtr.Path.size();
1981 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1982 const CXXRecordDecl *LVDecl = getAsBaseClass(
1983 LV.Designator.Entries[PathLengthToMember + I]);
1984 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1985 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1986 return 0;
1987 }
1988
1989 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001990 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1991 PathLengthToMember))
1992 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001993 } else if (!MemPtr.Path.empty()) {
1994 // Extend the LValue path with the member pointer's path.
1995 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1996 MemPtr.Path.size() + IncludeMember);
1997
1998 // Walk down to the appropriate base class.
1999 QualType LVType = BO->getLHS()->getType();
2000 if (const PointerType *PT = LVType->getAs<PointerType>())
2001 LVType = PT->getPointeeType();
2002 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2003 assert(RD && "member pointer access on non-class-type expression");
2004 // The first class in the path is that of the lvalue.
2005 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2006 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002007 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2008 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002009 RD = Base;
2010 }
2011 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002012 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2013 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002014 }
2015
2016 // Add the member. Note that we cannot build bound member functions here.
2017 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002018 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2019 if (!HandleLValueMember(Info, BO, LV, FD))
2020 return 0;
2021 } else if (const IndirectFieldDecl *IFD =
2022 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2023 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2024 return 0;
2025 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002026 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002027 }
Richard Smith027bf112011-11-17 22:56:20 +00002028 }
2029
2030 return MemPtr.getDecl();
2031}
2032
2033/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2034/// the provided lvalue, which currently refers to the base object.
2035static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2036 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002037 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002038 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002039 return false;
2040
Richard Smitha8105bc2012-01-06 16:39:00 +00002041 QualType TargetQT = E->getType();
2042 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2043 TargetQT = PT->getPointeeType();
2044
2045 // Check this cast lands within the final derived-to-base subobject path.
2046 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002047 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002048 << D.MostDerivedType << TargetQT;
2049 return false;
2050 }
2051
Richard Smith027bf112011-11-17 22:56:20 +00002052 // Check the type of the final cast. We don't need to check the path,
2053 // since a cast can only be formed if the path is unique.
2054 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002055 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2056 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002057 if (NewEntriesSize == D.MostDerivedPathLength)
2058 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2059 else
Richard Smith027bf112011-11-17 22:56:20 +00002060 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002061 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002062 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002063 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002064 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002065 }
Richard Smith027bf112011-11-17 22:56:20 +00002066
2067 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002068 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002069}
2070
Mike Stump876387b2009-10-27 22:09:17 +00002071namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002072enum EvalStmtResult {
2073 /// Evaluation failed.
2074 ESR_Failed,
2075 /// Hit a 'return' statement.
2076 ESR_Returned,
2077 /// Evaluation succeeded.
2078 ESR_Succeeded
2079};
2080}
2081
Richard Smithd9f663b2013-04-22 15:31:51 +00002082static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2083 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2084 // We don't need to evaluate the initializer for a static local.
2085 if (!VD->hasLocalStorage())
2086 return true;
2087
2088 LValue Result;
2089 Result.set(VD, Info.CurrentCall->Index);
2090 APValue &Val = Info.CurrentCall->Temporaries[VD];
2091
2092 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2093 // Wipe out any partially-computed value, to allow tracking that this
2094 // evaluation failed.
2095 Val = APValue();
2096 return false;
2097 }
2098 }
2099
2100 return true;
2101}
2102
Richard Smith254a73d2011-10-28 22:34:42 +00002103// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002104static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002105 const Stmt *S) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002106 // FIXME: Mark all temporaries in the current frame as destroyed at
2107 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002108 switch (S->getStmtClass()) {
2109 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002110 if (const Expr *E = dyn_cast<Expr>(S)) {
2111 EvaluateIgnoredValue(Info, E);
2112 // Don't bother evaluating beyond an expression-statement which couldn't
2113 // be evaluated.
2114 if (Info.EvalStatus.HasSideEffects && !Info.keepEvaluatingAfterFailure())
2115 return ESR_Failed;
2116 return ESR_Succeeded;
2117 }
2118
2119 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002120 return ESR_Failed;
2121
2122 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002123 return ESR_Succeeded;
2124
Richard Smithd9f663b2013-04-22 15:31:51 +00002125 case Stmt::DeclStmtClass: {
2126 const DeclStmt *DS = cast<DeclStmt>(S);
2127 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2128 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2129 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2130 return ESR_Failed;
2131 return ESR_Succeeded;
2132 }
2133
Richard Smith357362d2011-12-13 06:39:58 +00002134 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002135 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002136 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002137 return ESR_Failed;
2138 return ESR_Returned;
2139 }
Richard Smith254a73d2011-10-28 22:34:42 +00002140
2141 case Stmt::CompoundStmtClass: {
2142 const CompoundStmt *CS = cast<CompoundStmt>(S);
2143 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2144 BE = CS->body_end(); BI != BE; ++BI) {
2145 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2146 if (ESR != ESR_Succeeded)
2147 return ESR;
2148 }
2149 return ESR_Succeeded;
2150 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002151
2152 case Stmt::IfStmtClass: {
2153 const IfStmt *IS = cast<IfStmt>(S);
2154
2155 // Evaluate the condition, as either a var decl or as an expression.
2156 bool Cond;
2157 if (VarDecl *CondDecl = IS->getConditionVariable()) {
2158 if (!EvaluateDecl(Info, CondDecl))
2159 return ESR_Failed;
2160 if (!HandleConversionToBool(Info.CurrentCall->Temporaries[CondDecl],
2161 Cond))
2162 return ESR_Failed;
2163 } else if (!EvaluateAsBooleanCondition(IS->getCond(), Cond, Info))
2164 return ESR_Failed;
2165
2166 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2167 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2168 if (ESR != ESR_Succeeded)
2169 return ESR;
2170 }
2171 return ESR_Succeeded;
2172 }
Richard Smith254a73d2011-10-28 22:34:42 +00002173 }
2174}
2175
Richard Smithcc36f692011-12-22 02:22:31 +00002176/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2177/// default constructor. If so, we'll fold it whether or not it's marked as
2178/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2179/// so we need special handling.
2180static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002181 const CXXConstructorDecl *CD,
2182 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002183 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2184 return false;
2185
Richard Smith66e05fe2012-01-18 05:21:49 +00002186 // Value-initialization does not call a trivial default constructor, so such a
2187 // call is a core constant expression whether or not the constructor is
2188 // constexpr.
2189 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002190 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002191 // FIXME: If DiagDecl is an implicitly-declared special member function,
2192 // we should be much more explicit about why it's not constexpr.
2193 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2194 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2195 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002196 } else {
2197 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2198 }
2199 }
2200 return true;
2201}
2202
Richard Smith357362d2011-12-13 06:39:58 +00002203/// CheckConstexprFunction - Check that a function can be called in a constant
2204/// expression.
2205static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2206 const FunctionDecl *Declaration,
2207 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002208 // Potential constant expressions can contain calls to declared, but not yet
2209 // defined, constexpr functions.
2210 if (Info.CheckingPotentialConstantExpression && !Definition &&
2211 Declaration->isConstexpr())
2212 return false;
2213
Richard Smith357362d2011-12-13 06:39:58 +00002214 // Can we evaluate this function call?
2215 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2216 return true;
2217
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002218 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002219 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002220 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2221 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002222 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2223 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2224 << DiagDecl;
2225 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2226 } else {
2227 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2228 }
2229 return false;
2230}
2231
Richard Smithd62306a2011-11-10 06:34:14 +00002232namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002233typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002234}
2235
2236/// EvaluateArgs - Evaluate the arguments to a function call.
2237static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2238 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002239 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002240 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002241 I != E; ++I) {
2242 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2243 // If we're checking for a potential constant expression, evaluate all
2244 // initializers even if some of them fail.
2245 if (!Info.keepEvaluatingAfterFailure())
2246 return false;
2247 Success = false;
2248 }
2249 }
2250 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002251}
2252
Richard Smith254a73d2011-10-28 22:34:42 +00002253/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002254static bool HandleFunctionCall(SourceLocation CallLoc,
2255 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002256 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002257 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002258 ArgVector ArgValues(Args.size());
2259 if (!EvaluateArgs(Args, ArgValues, Info))
2260 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002261
Richard Smith253c2a32012-01-27 01:14:48 +00002262 if (!Info.CheckCallLimit(CallLoc))
2263 return false;
2264
2265 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd9f663b2013-04-22 15:31:51 +00002266 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
2267 if (ESR == ESR_Succeeded)
2268 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
2269 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00002270}
2271
Richard Smithd62306a2011-11-10 06:34:14 +00002272/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002273static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002274 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002275 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002276 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002277 ArgVector ArgValues(Args.size());
2278 if (!EvaluateArgs(Args, ArgValues, Info))
2279 return false;
2280
Richard Smith253c2a32012-01-27 01:14:48 +00002281 if (!Info.CheckCallLimit(CallLoc))
2282 return false;
2283
Richard Smith3607ffe2012-02-13 03:54:03 +00002284 const CXXRecordDecl *RD = Definition->getParent();
2285 if (RD->getNumVBases()) {
2286 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2287 return false;
2288 }
2289
Richard Smith253c2a32012-01-27 01:14:48 +00002290 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002291
2292 // If it's a delegating constructor, just delegate.
2293 if (Definition->isDelegatingConstructor()) {
2294 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00002295 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
2296 return false;
2297 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002298 }
2299
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002300 // For a trivial copy or move constructor, perform an APValue copy. This is
2301 // essential for unions, where the operations performed by the constructor
2302 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002303 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002304 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2305 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002306 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002307 RHS.setFrom(Info.Ctx, ArgValues[0]);
2308 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2309 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002310 }
2311
2312 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002313 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002314 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2315 std::distance(RD->field_begin(), RD->field_end()));
2316
John McCalld7bca762012-05-01 00:38:49 +00002317 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002318 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2319
Richard Smith253c2a32012-01-27 01:14:48 +00002320 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002321 unsigned BasesSeen = 0;
2322#ifndef NDEBUG
2323 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2324#endif
2325 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2326 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002327 LValue Subobject = This;
2328 APValue *Value = &Result;
2329
2330 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002331 if ((*I)->isBaseInitializer()) {
2332 QualType BaseType((*I)->getBaseClass(), 0);
2333#ifndef NDEBUG
2334 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002335 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002336 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2337 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2338 "base class initializers not in expected order");
2339 ++BaseIt;
2340#endif
John McCalld7bca762012-05-01 00:38:49 +00002341 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2342 BaseType->getAsCXXRecordDecl(), &Layout))
2343 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002344 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002345 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002346 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2347 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002348 if (RD->isUnion()) {
2349 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002350 Value = &Result.getUnionValue();
2351 } else {
2352 Value = &Result.getStructField(FD->getFieldIndex());
2353 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002354 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002355 // Walk the indirect field decl's chain to find the object to initialize,
2356 // and make sure we've initialized every step along it.
2357 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2358 CE = IFD->chain_end();
2359 C != CE; ++C) {
2360 FieldDecl *FD = cast<FieldDecl>(*C);
2361 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2362 // Switch the union field if it differs. This happens if we had
2363 // preceding zero-initialization, and we're now initializing a union
2364 // subobject other than the first.
2365 // FIXME: In this case, the values of the other subobjects are
2366 // specified, since zero-initialization sets all padding bits to zero.
2367 if (Value->isUninit() ||
2368 (Value->isUnion() && Value->getUnionField() != FD)) {
2369 if (CD->isUnion())
2370 *Value = APValue(FD);
2371 else
2372 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2373 std::distance(CD->field_begin(), CD->field_end()));
2374 }
John McCalld7bca762012-05-01 00:38:49 +00002375 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2376 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002377 if (CD->isUnion())
2378 Value = &Value->getUnionValue();
2379 else
2380 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002381 }
Richard Smithd62306a2011-11-10 06:34:14 +00002382 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002383 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002384 }
Richard Smith253c2a32012-01-27 01:14:48 +00002385
Richard Smithb228a862012-02-15 02:18:13 +00002386 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2387 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002388 ? CCEK_Constant : CCEK_MemberInit)) {
2389 // If we're checking for a potential constant expression, evaluate all
2390 // initializers even if some of them fail.
2391 if (!Info.keepEvaluatingAfterFailure())
2392 return false;
2393 Success = false;
2394 }
Richard Smithd62306a2011-11-10 06:34:14 +00002395 }
2396
Richard Smithd9f663b2013-04-22 15:31:51 +00002397 return Success &&
2398 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002399}
2400
Eli Friedman9a156e52008-11-12 09:44:48 +00002401//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002402// Generic Evaluation
2403//===----------------------------------------------------------------------===//
2404namespace {
2405
Richard Smithf57d8cb2011-12-09 22:58:01 +00002406// FIXME: RetTy is always bool. Remove it.
2407template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002408class ExprEvaluatorBase
2409 : public ConstStmtVisitor<Derived, RetTy> {
2410private:
Richard Smith2e312c82012-03-03 22:46:17 +00002411 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002412 return static_cast<Derived*>(this)->Success(V, E);
2413 }
Richard Smithfddd3842011-12-30 21:15:51 +00002414 RetTy DerivedZeroInitialization(const Expr *E) {
2415 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002416 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002417
Richard Smith17100ba2012-02-16 02:46:34 +00002418 // Check whether a conditional operator with a non-constant condition is a
2419 // potential constant expression. If neither arm is a potential constant
2420 // expression, then the conditional operator is not either.
2421 template<typename ConditionalOperator>
2422 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2423 assert(Info.CheckingPotentialConstantExpression);
2424
2425 // Speculatively evaluate both arms.
2426 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002427 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002428 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2429
2430 StmtVisitorTy::Visit(E->getFalseExpr());
2431 if (Diag.empty())
2432 return;
2433
2434 Diag.clear();
2435 StmtVisitorTy::Visit(E->getTrueExpr());
2436 if (Diag.empty())
2437 return;
2438 }
2439
2440 Error(E, diag::note_constexpr_conditional_never_const);
2441 }
2442
2443
2444 template<typename ConditionalOperator>
2445 bool HandleConditionalOperator(const ConditionalOperator *E) {
2446 bool BoolResult;
2447 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2448 if (Info.CheckingPotentialConstantExpression)
2449 CheckPotentialConstantConditional(E);
2450 return false;
2451 }
2452
2453 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2454 return StmtVisitorTy::Visit(EvalExpr);
2455 }
2456
Peter Collingbournee9200682011-05-13 03:29:01 +00002457protected:
2458 EvalInfo &Info;
2459 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2460 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2461
Richard Smith92b1ce02011-12-12 09:28:41 +00002462 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002463 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002464 }
2465
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002466 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2467
2468public:
2469 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2470
2471 EvalInfo &getEvalInfo() { return Info; }
2472
Richard Smithf57d8cb2011-12-09 22:58:01 +00002473 /// Report an evaluation error. This should only be called when an error is
2474 /// first discovered. When propagating an error, just return false.
2475 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002476 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002477 return false;
2478 }
2479 bool Error(const Expr *E) {
2480 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2481 }
2482
Peter Collingbournee9200682011-05-13 03:29:01 +00002483 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002484 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002485 }
2486 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002487 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002488 }
2489
2490 RetTy VisitParenExpr(const ParenExpr *E)
2491 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2492 RetTy VisitUnaryExtension(const UnaryOperator *E)
2493 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2494 RetTy VisitUnaryPlus(const UnaryOperator *E)
2495 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2496 RetTy VisitChooseExpr(const ChooseExpr *E)
2497 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2498 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2499 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002500 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2501 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002502 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2503 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00002504 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
2505 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002506 // We cannot create any objects for which cleanups are required, so there is
2507 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2508 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2509 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002510
Richard Smith6d6ecc32011-12-12 12:46:16 +00002511 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2512 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2513 return static_cast<Derived*>(this)->VisitCastExpr(E);
2514 }
2515 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2516 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2517 return static_cast<Derived*>(this)->VisitCastExpr(E);
2518 }
2519
Richard Smith027bf112011-11-17 22:56:20 +00002520 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2521 switch (E->getOpcode()) {
2522 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002523 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002524
2525 case BO_Comma:
2526 VisitIgnoredValue(E->getLHS());
2527 return StmtVisitorTy::Visit(E->getRHS());
2528
2529 case BO_PtrMemD:
2530 case BO_PtrMemI: {
2531 LValue Obj;
2532 if (!HandleMemberPointerAccess(Info, E, Obj))
2533 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002534 APValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002535 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002536 return false;
2537 return DerivedSuccess(Result, E);
2538 }
2539 }
2540 }
2541
Peter Collingbournee9200682011-05-13 03:29:01 +00002542 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002543 // Evaluate and cache the common expression. We treat it as a temporary,
2544 // even though it's not quite the same thing.
2545 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2546 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002547 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002548
Richard Smith17100ba2012-02-16 02:46:34 +00002549 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002550 }
2551
2552 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002553 bool IsBcpCall = false;
2554 // If the condition (ignoring parens) is a __builtin_constant_p call,
2555 // the result is a constant expression if it can be folded without
2556 // side-effects. This is an important GNU extension. See GCC PR38377
2557 // for discussion.
2558 if (const CallExpr *CallCE =
2559 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2560 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2561 IsBcpCall = true;
2562
2563 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2564 // constant expression; we can't check whether it's potentially foldable.
2565 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2566 return false;
2567
2568 FoldConstant Fold(Info);
2569
Richard Smith17100ba2012-02-16 02:46:34 +00002570 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00002571 return false;
2572
2573 if (IsBcpCall)
2574 Fold.Fold(Info);
2575
2576 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00002577 }
2578
2579 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002580 APValue &Value = Info.CurrentCall->Temporaries[E];
2581 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002582 const Expr *Source = E->getSourceExpr();
2583 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002584 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002585 if (Source == E) { // sanity checking.
2586 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002587 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002588 }
2589 return StmtVisitorTy::Visit(Source);
2590 }
Richard Smith26d4cc12012-06-26 08:12:11 +00002591 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002592 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002593
Richard Smith254a73d2011-10-28 22:34:42 +00002594 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002595 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002596 QualType CalleeType = Callee->getType();
2597
Richard Smith254a73d2011-10-28 22:34:42 +00002598 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002599 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002600 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00002601 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00002602
Richard Smithe97cbd72011-11-11 04:05:33 +00002603 // Extract function decl and 'this' pointer from the callee.
2604 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002605 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002606 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2607 // Explicit bound member calls, such as x.f() or p->g();
2608 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002609 return false;
2610 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002611 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00002612 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00002613 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2614 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002615 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2616 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002617 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002618 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002619 return Error(Callee);
2620
2621 FD = dyn_cast<FunctionDecl>(Member);
2622 if (!FD)
2623 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002624 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002625 LValue Call;
2626 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002627 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002628
Richard Smitha8105bc2012-01-06 16:39:00 +00002629 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002630 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002631 FD = dyn_cast_or_null<FunctionDecl>(
2632 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002633 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002634 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002635
2636 // Overloaded operator calls to member functions are represented as normal
2637 // calls with '*this' as the first argument.
2638 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2639 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002640 // FIXME: When selecting an implicit conversion for an overloaded
2641 // operator delete, we sometimes try to evaluate calls to conversion
2642 // operators without a 'this' parameter!
2643 if (Args.empty())
2644 return Error(E);
2645
Richard Smithe97cbd72011-11-11 04:05:33 +00002646 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2647 return false;
2648 This = &ThisVal;
2649 Args = Args.slice(1);
2650 }
2651
2652 // Don't call function pointers which have been cast to some other type.
2653 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002654 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002655 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002656 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002657
Richard Smith47b34932012-02-01 02:39:43 +00002658 if (This && !This->checkSubobject(Info, E, CSK_This))
2659 return false;
2660
Richard Smith3607ffe2012-02-13 03:54:03 +00002661 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2662 // calls to such functions in constant expressions.
2663 if (This && !HasQualifier &&
2664 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2665 return Error(E, diag::note_constexpr_virtual_call);
2666
Richard Smith357362d2011-12-13 06:39:58 +00002667 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002668 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00002669 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002670
Richard Smith357362d2011-12-13 06:39:58 +00002671 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00002672 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2673 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002674 return false;
2675
Richard Smithb228a862012-02-15 02:18:13 +00002676 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00002677 }
2678
Richard Smith11562c52011-10-28 17:51:58 +00002679 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2680 return StmtVisitorTy::Visit(E->getInitializer());
2681 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002682 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002683 if (E->getNumInits() == 0)
2684 return DerivedZeroInitialization(E);
2685 if (E->getNumInits() == 1)
2686 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002687 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002688 }
2689 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002690 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002691 }
2692 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002693 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002694 }
Richard Smith027bf112011-11-17 22:56:20 +00002695 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002696 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002697 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002698
Richard Smithd62306a2011-11-10 06:34:14 +00002699 /// A member expression where the object is a prvalue is itself a prvalue.
2700 RetTy VisitMemberExpr(const MemberExpr *E) {
2701 assert(!E->isArrow() && "missing call to bound member function?");
2702
Richard Smith2e312c82012-03-03 22:46:17 +00002703 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00002704 if (!Evaluate(Val, Info, E->getBase()))
2705 return false;
2706
2707 QualType BaseTy = E->getBase()->getType();
2708
2709 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002710 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002711 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00002712 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00002713 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2714
Richard Smitha8105bc2012-01-06 16:39:00 +00002715 SubobjectDesignator Designator(BaseTy);
2716 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002717
Richard Smithf57d8cb2011-12-09 22:58:01 +00002718 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002719 DerivedSuccess(Val, E);
2720 }
2721
Richard Smith11562c52011-10-28 17:51:58 +00002722 RetTy VisitCastExpr(const CastExpr *E) {
2723 switch (E->getCastKind()) {
2724 default:
2725 break;
2726
David Chisnallfa35df62012-01-16 17:27:18 +00002727 case CK_AtomicToNonAtomic:
2728 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00002729 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00002730 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00002731 return StmtVisitorTy::Visit(E->getSubExpr());
2732
2733 case CK_LValueToRValue: {
2734 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002735 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2736 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002737 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00002738 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2739 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2740 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002741 return false;
2742 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002743 }
2744 }
2745
Richard Smithf57d8cb2011-12-09 22:58:01 +00002746 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002747 }
2748
Richard Smith4a678122011-10-24 18:44:57 +00002749 /// Visit a value which is evaluated, but whose value is ignored.
2750 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002751 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00002752 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002753};
2754
2755}
2756
2757//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002758// Common base class for lvalue and temporary evaluation.
2759//===----------------------------------------------------------------------===//
2760namespace {
2761template<class Derived>
2762class LValueExprEvaluatorBase
2763 : public ExprEvaluatorBase<Derived, bool> {
2764protected:
2765 LValue &Result;
2766 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2767 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2768
2769 bool Success(APValue::LValueBase B) {
2770 Result.set(B);
2771 return true;
2772 }
2773
2774public:
2775 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2776 ExprEvaluatorBaseTy(Info), Result(Result) {}
2777
Richard Smith2e312c82012-03-03 22:46:17 +00002778 bool Success(const APValue &V, const Expr *E) {
2779 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00002780 return true;
2781 }
Richard Smith027bf112011-11-17 22:56:20 +00002782
Richard Smith027bf112011-11-17 22:56:20 +00002783 bool VisitMemberExpr(const MemberExpr *E) {
2784 // Handle non-static data members.
2785 QualType BaseTy;
2786 if (E->isArrow()) {
2787 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2788 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00002789 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002790 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002791 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002792 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2793 return false;
2794 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002795 } else {
2796 if (!this->Visit(E->getBase()))
2797 return false;
2798 BaseTy = E->getBase()->getType();
2799 }
Richard Smith027bf112011-11-17 22:56:20 +00002800
Richard Smith1b78b3d2012-01-25 22:15:11 +00002801 const ValueDecl *MD = E->getMemberDecl();
2802 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2803 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2804 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2805 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00002806 if (!HandleLValueMember(this->Info, E, Result, FD))
2807 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002808 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00002809 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2810 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002811 } else
2812 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002813
Richard Smith1b78b3d2012-01-25 22:15:11 +00002814 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00002815 APValue RefValue;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002816 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002817 RefValue))
2818 return false;
2819 return Success(RefValue, E);
2820 }
2821 return true;
2822 }
2823
2824 bool VisitBinaryOperator(const BinaryOperator *E) {
2825 switch (E->getOpcode()) {
2826 default:
2827 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2828
2829 case BO_PtrMemD:
2830 case BO_PtrMemI:
2831 return HandleMemberPointerAccess(this->Info, E, Result);
2832 }
2833 }
2834
2835 bool VisitCastExpr(const CastExpr *E) {
2836 switch (E->getCastKind()) {
2837 default:
2838 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2839
2840 case CK_DerivedToBase:
2841 case CK_UncheckedDerivedToBase: {
2842 if (!this->Visit(E->getSubExpr()))
2843 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002844
2845 // Now figure out the necessary offset to add to the base LV to get from
2846 // the derived class to the base class.
2847 QualType Type = E->getSubExpr()->getType();
2848
2849 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2850 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002851 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00002852 *PathI))
2853 return false;
2854 Type = (*PathI)->getType();
2855 }
2856
2857 return true;
2858 }
2859 }
2860 }
2861};
2862}
2863
2864//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002865// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002866//
2867// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2868// function designators (in C), decl references to void objects (in C), and
2869// temporaries (if building with -Wno-address-of-temporary).
2870//
2871// LValue evaluation produces values comprising a base expression of one of the
2872// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002873// - Declarations
2874// * VarDecl
2875// * FunctionDecl
2876// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002877// * CompoundLiteralExpr in C
2878// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002879// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002880// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002881// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002882// * ObjCEncodeExpr
2883// * AddrLabelExpr
2884// * BlockExpr
2885// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002886// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00002887// * Any Expr, with a CallIndex indicating the function in which the temporary
2888// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00002889// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002890//===----------------------------------------------------------------------===//
2891namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002892class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002893 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002894public:
Richard Smith027bf112011-11-17 22:56:20 +00002895 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2896 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002897
Richard Smith11562c52011-10-28 17:51:58 +00002898 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2899
Peter Collingbournee9200682011-05-13 03:29:01 +00002900 bool VisitDeclRefExpr(const DeclRefExpr *E);
2901 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002902 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002903 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2904 bool VisitMemberExpr(const MemberExpr *E);
2905 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2906 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002907 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00002908 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002909 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2910 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00002911 bool VisitUnaryReal(const UnaryOperator *E);
2912 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002913
Peter Collingbournee9200682011-05-13 03:29:01 +00002914 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002915 switch (E->getCastKind()) {
2916 default:
Richard Smith027bf112011-11-17 22:56:20 +00002917 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002918
Eli Friedmance3e02a2011-10-11 00:13:24 +00002919 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002920 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002921 if (!Visit(E->getSubExpr()))
2922 return false;
2923 Result.Designator.setInvalid();
2924 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002925
Richard Smith027bf112011-11-17 22:56:20 +00002926 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002927 if (!Visit(E->getSubExpr()))
2928 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002929 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002930 }
2931 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002932};
2933} // end anonymous namespace
2934
Richard Smith11562c52011-10-28 17:51:58 +00002935/// Evaluate an expression as an lvalue. This can be legitimately called on
2936/// expressions which are not glvalues, in a few cases:
2937/// * function designators in C,
2938/// * "extern void" objects,
2939/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002940static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002941 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2942 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2943 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002944 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002945}
2946
Peter Collingbournee9200682011-05-13 03:29:01 +00002947bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002948 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2949 return Success(FD);
2950 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002951 return VisitVarDecl(E, VD);
2952 return Error(E);
2953}
Richard Smith733237d2011-10-24 23:14:33 +00002954
Richard Smith11562c52011-10-28 17:51:58 +00002955bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002956 if (!VD->getType()->isReferenceType()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002957 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
Richard Smithb228a862012-02-15 02:18:13 +00002958 Result.set(VD, Info.CurrentCall->Index);
Richard Smithfec09922011-11-01 16:57:24 +00002959 return true;
2960 }
Richard Smithce40ad62011-11-12 22:28:03 +00002961 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002962 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002963
Richard Smith2e312c82012-03-03 22:46:17 +00002964 APValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002965 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2966 return false;
2967 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002968}
2969
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002970bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2971 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00002972 if (E->getType()->isRecordType())
2973 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00002974
Richard Smithb228a862012-02-15 02:18:13 +00002975 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00002976 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2977 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002978}
2979
Peter Collingbournee9200682011-05-13 03:29:01 +00002980bool
2981LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002982 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2983 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2984 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002985 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002986}
2987
Richard Smith6e525142011-12-27 12:18:28 +00002988bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00002989 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00002990 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00002991
2992 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2993 << E->getExprOperand()->getType()
2994 << E->getExprOperand()->getSourceRange();
2995 return false;
Richard Smith6e525142011-12-27 12:18:28 +00002996}
2997
Francois Pichet0066db92012-04-16 04:08:35 +00002998bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2999 return Success(E);
3000}
3001
Peter Collingbournee9200682011-05-13 03:29:01 +00003002bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003003 // Handle static data members.
3004 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3005 VisitIgnoredValue(E->getBase());
3006 return VisitVarDecl(E, VD);
3007 }
3008
Richard Smith254a73d2011-10-28 22:34:42 +00003009 // Handle static member functions.
3010 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3011 if (MD->isStatic()) {
3012 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003013 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003014 }
3015 }
3016
Richard Smithd62306a2011-11-10 06:34:14 +00003017 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003018 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003019}
3020
Peter Collingbournee9200682011-05-13 03:29:01 +00003021bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003022 // FIXME: Deal with vectors as array subscript bases.
3023 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003024 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003025
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003026 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003027 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003028
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003029 APSInt Index;
3030 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003031 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003032 int64_t IndexValue
3033 = Index.isSigned() ? Index.getSExtValue()
3034 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003035
Richard Smitha8105bc2012-01-06 16:39:00 +00003036 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003037}
Eli Friedman9a156e52008-11-12 09:44:48 +00003038
Peter Collingbournee9200682011-05-13 03:29:01 +00003039bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003040 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003041}
3042
Richard Smith66c96992012-02-18 22:04:06 +00003043bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3044 if (!Visit(E->getSubExpr()))
3045 return false;
3046 // __real is a no-op on scalar lvalues.
3047 if (E->getSubExpr()->getType()->isAnyComplexType())
3048 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3049 return true;
3050}
3051
3052bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3053 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3054 "lvalue __imag__ on scalar?");
3055 if (!Visit(E->getSubExpr()))
3056 return false;
3057 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3058 return true;
3059}
3060
Eli Friedman9a156e52008-11-12 09:44:48 +00003061//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003062// Pointer Evaluation
3063//===----------------------------------------------------------------------===//
3064
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003065namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003066class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003067 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003068 LValue &Result;
3069
Peter Collingbournee9200682011-05-13 03:29:01 +00003070 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003071 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003072 return true;
3073 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003074public:
Mike Stump11289f42009-09-09 15:08:12 +00003075
John McCall45d55e42010-05-07 21:00:08 +00003076 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003077 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003078
Richard Smith2e312c82012-03-03 22:46:17 +00003079 bool Success(const APValue &V, const Expr *E) {
3080 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00003081 return true;
3082 }
Richard Smithfddd3842011-12-30 21:15:51 +00003083 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003084 return Success((Expr*)0);
3085 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003086
John McCall45d55e42010-05-07 21:00:08 +00003087 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003088 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003089 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003090 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003091 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003092 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003093 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003094 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003095 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003096 bool VisitCallExpr(const CallExpr *E);
3097 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003098 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003099 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003100 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003101 }
Richard Smithd62306a2011-11-10 06:34:14 +00003102 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3103 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003104 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003105 Result = *Info.CurrentCall->This;
3106 return true;
3107 }
John McCallc07a0c72011-02-17 10:25:35 +00003108
Eli Friedman449fe542009-03-23 04:56:01 +00003109 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003110};
Chris Lattner05706e882008-07-11 18:11:29 +00003111} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003112
John McCall45d55e42010-05-07 21:00:08 +00003113static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003114 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003115 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003116}
3117
John McCall45d55e42010-05-07 21:00:08 +00003118bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003119 if (E->getOpcode() != BO_Add &&
3120 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003121 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003122
Chris Lattner05706e882008-07-11 18:11:29 +00003123 const Expr *PExp = E->getLHS();
3124 const Expr *IExp = E->getRHS();
3125 if (IExp->getType()->isPointerType())
3126 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003127
Richard Smith253c2a32012-01-27 01:14:48 +00003128 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3129 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003130 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003131
John McCall45d55e42010-05-07 21:00:08 +00003132 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003133 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003134 return false;
3135 int64_t AdditionalOffset
3136 = Offset.isSigned() ? Offset.getSExtValue()
3137 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003138 if (E->getOpcode() == BO_Sub)
3139 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003140
Ted Kremenek28831752012-08-23 20:46:57 +00003141 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003142 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3143 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003144}
Eli Friedman9a156e52008-11-12 09:44:48 +00003145
John McCall45d55e42010-05-07 21:00:08 +00003146bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3147 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003148}
Mike Stump11289f42009-09-09 15:08:12 +00003149
Peter Collingbournee9200682011-05-13 03:29:01 +00003150bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3151 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003152
Eli Friedman847a2bc2009-12-27 05:43:15 +00003153 switch (E->getCastKind()) {
3154 default:
3155 break;
3156
John McCalle3027922010-08-25 11:45:40 +00003157 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003158 case CK_CPointerToObjCPointerCast:
3159 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003160 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003161 if (!Visit(SubExpr))
3162 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003163 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3164 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3165 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003166 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003167 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003168 if (SubExpr->getType()->isVoidPointerType())
3169 CCEDiag(E, diag::note_constexpr_invalid_cast)
3170 << 3 << SubExpr->getType();
3171 else
3172 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3173 }
Richard Smith96e0c102011-11-04 02:25:55 +00003174 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003175
Anders Carlsson18275092010-10-31 20:41:46 +00003176 case CK_DerivedToBase:
3177 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003178 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003179 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003180 if (!Result.Base && Result.Offset.isZero())
3181 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003182
Richard Smithd62306a2011-11-10 06:34:14 +00003183 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003184 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003185 QualType Type =
3186 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003187
Richard Smithd62306a2011-11-10 06:34:14 +00003188 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003189 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003190 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3191 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003192 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003193 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003194 }
3195
Anders Carlsson18275092010-10-31 20:41:46 +00003196 return true;
3197 }
3198
Richard Smith027bf112011-11-17 22:56:20 +00003199 case CK_BaseToDerived:
3200 if (!Visit(E->getSubExpr()))
3201 return false;
3202 if (!Result.Base && Result.Offset.isZero())
3203 return true;
3204 return HandleBaseToDerivedCast(Info, E, Result);
3205
Richard Smith0b0a0b62011-10-29 20:57:55 +00003206 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003207 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003208 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003209
John McCalle3027922010-08-25 11:45:40 +00003210 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003211 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3212
Richard Smith2e312c82012-03-03 22:46:17 +00003213 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003214 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003215 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003216
John McCall45d55e42010-05-07 21:00:08 +00003217 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003218 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3219 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003220 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003221 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003222 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003223 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003224 return true;
3225 } else {
3226 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003227 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003228 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003229 }
3230 }
John McCalle3027922010-08-25 11:45:40 +00003231 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003232 if (SubExpr->isGLValue()) {
3233 if (!EvaluateLValue(SubExpr, Result, Info))
3234 return false;
3235 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003236 Result.set(SubExpr, Info.CurrentCall->Index);
3237 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3238 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003239 return false;
3240 }
Richard Smith96e0c102011-11-04 02:25:55 +00003241 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003242 if (const ConstantArrayType *CAT
3243 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3244 Result.addArray(Info, E, CAT);
3245 else
3246 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003247 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003248
John McCalle3027922010-08-25 11:45:40 +00003249 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003250 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003251 }
3252
Richard Smith11562c52011-10-28 17:51:58 +00003253 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003254}
Chris Lattner05706e882008-07-11 18:11:29 +00003255
Peter Collingbournee9200682011-05-13 03:29:01 +00003256bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003257 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003258 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003259
Peter Collingbournee9200682011-05-13 03:29:01 +00003260 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003261}
Chris Lattner05706e882008-07-11 18:11:29 +00003262
3263//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003264// Member Pointer Evaluation
3265//===----------------------------------------------------------------------===//
3266
3267namespace {
3268class MemberPointerExprEvaluator
3269 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3270 MemberPtr &Result;
3271
3272 bool Success(const ValueDecl *D) {
3273 Result = MemberPtr(D);
3274 return true;
3275 }
3276public:
3277
3278 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3279 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3280
Richard Smith2e312c82012-03-03 22:46:17 +00003281 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003282 Result.setFrom(V);
3283 return true;
3284 }
Richard Smithfddd3842011-12-30 21:15:51 +00003285 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003286 return Success((const ValueDecl*)0);
3287 }
3288
3289 bool VisitCastExpr(const CastExpr *E);
3290 bool VisitUnaryAddrOf(const UnaryOperator *E);
3291};
3292} // end anonymous namespace
3293
3294static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3295 EvalInfo &Info) {
3296 assert(E->isRValue() && E->getType()->isMemberPointerType());
3297 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3298}
3299
3300bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3301 switch (E->getCastKind()) {
3302 default:
3303 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3304
3305 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003306 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003307 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003308
3309 case CK_BaseToDerivedMemberPointer: {
3310 if (!Visit(E->getSubExpr()))
3311 return false;
3312 if (E->path_empty())
3313 return true;
3314 // Base-to-derived member pointer casts store the path in derived-to-base
3315 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3316 // the wrong end of the derived->base arc, so stagger the path by one class.
3317 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3318 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3319 PathI != PathE; ++PathI) {
3320 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3321 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3322 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003323 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003324 }
3325 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3326 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003327 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003328 return true;
3329 }
3330
3331 case CK_DerivedToBaseMemberPointer:
3332 if (!Visit(E->getSubExpr()))
3333 return false;
3334 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3335 PathE = E->path_end(); PathI != PathE; ++PathI) {
3336 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3337 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3338 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003339 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003340 }
3341 return true;
3342 }
3343}
3344
3345bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3346 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3347 // member can be formed.
3348 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3349}
3350
3351//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003352// Record Evaluation
3353//===----------------------------------------------------------------------===//
3354
3355namespace {
3356 class RecordExprEvaluator
3357 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3358 const LValue &This;
3359 APValue &Result;
3360 public:
3361
3362 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3363 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3364
Richard Smith2e312c82012-03-03 22:46:17 +00003365 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003366 Result = V;
3367 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003368 }
Richard Smithfddd3842011-12-30 21:15:51 +00003369 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003370
Richard Smithe97cbd72011-11-11 04:05:33 +00003371 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003372 bool VisitInitListExpr(const InitListExpr *E);
3373 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3374 };
3375}
3376
Richard Smithfddd3842011-12-30 21:15:51 +00003377/// Perform zero-initialization on an object of non-union class type.
3378/// C++11 [dcl.init]p5:
3379/// To zero-initialize an object or reference of type T means:
3380/// [...]
3381/// -- if T is a (possibly cv-qualified) non-union class type,
3382/// each non-static data member and each base-class subobject is
3383/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003384static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3385 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003386 const LValue &This, APValue &Result) {
3387 assert(!RD->isUnion() && "Expected non-union class type");
3388 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3389 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3390 std::distance(RD->field_begin(), RD->field_end()));
3391
John McCalld7bca762012-05-01 00:38:49 +00003392 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003393 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3394
3395 if (CD) {
3396 unsigned Index = 0;
3397 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003398 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00003399 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3400 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003401 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3402 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003403 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00003404 Result.getStructBase(Index)))
3405 return false;
3406 }
3407 }
3408
Richard Smitha8105bc2012-01-06 16:39:00 +00003409 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3410 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00003411 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00003412 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00003413 continue;
3414
3415 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003416 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003417 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003418
David Blaikie2d7c57e2012-04-30 02:36:29 +00003419 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003420 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00003421 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003422 return false;
3423 }
3424
3425 return true;
3426}
3427
3428bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3429 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003430 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003431 if (RD->isUnion()) {
3432 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3433 // object's first non-static named data member is zero-initialized
3434 RecordDecl::field_iterator I = RD->field_begin();
3435 if (I == RD->field_end()) {
3436 Result = APValue((const FieldDecl*)0);
3437 return true;
3438 }
3439
3440 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003441 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00003442 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00003443 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003444 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003445 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003446 }
3447
Richard Smith5d108602012-02-17 00:44:16 +00003448 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003449 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00003450 return false;
3451 }
3452
Richard Smitha8105bc2012-01-06 16:39:00 +00003453 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00003454}
3455
Richard Smithe97cbd72011-11-11 04:05:33 +00003456bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3457 switch (E->getCastKind()) {
3458 default:
3459 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3460
3461 case CK_ConstructorConversion:
3462 return Visit(E->getSubExpr());
3463
3464 case CK_DerivedToBase:
3465 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00003466 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003467 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00003468 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003469 if (!DerivedObject.isStruct())
3470 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00003471
3472 // Derived-to-base rvalue conversion: just slice off the derived part.
3473 APValue *Value = &DerivedObject;
3474 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3475 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3476 PathE = E->path_end(); PathI != PathE; ++PathI) {
3477 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3478 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3479 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3480 RD = Base;
3481 }
3482 Result = *Value;
3483 return true;
3484 }
3485 }
3486}
3487
Richard Smithd62306a2011-11-10 06:34:14 +00003488bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00003489 // Cannot constant-evaluate std::initializer_list inits.
3490 if (E->initializesStdInitializerList())
3491 return false;
3492
Richard Smithd62306a2011-11-10 06:34:14 +00003493 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003494 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003495 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3496
3497 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00003498 const FieldDecl *Field = E->getInitializedFieldInUnion();
3499 Result = APValue(Field);
3500 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00003501 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00003502
3503 // If the initializer list for a union does not contain any elements, the
3504 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00003505 // FIXME: The element should be initialized from an initializer list.
3506 // Is this difference ever observable for initializer lists which
3507 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00003508 ImplicitValueInitExpr VIE(Field->getType());
3509 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3510
Richard Smithd62306a2011-11-10 06:34:14 +00003511 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003512 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3513 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00003514
3515 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3516 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3517 isa<CXXDefaultInitExpr>(InitExpr));
3518
Richard Smithb228a862012-02-15 02:18:13 +00003519 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00003520 }
3521
3522 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3523 "initializer list for class with base classes");
3524 Result = APValue(APValue::UninitStruct(), 0,
3525 std::distance(RD->field_begin(), RD->field_end()));
3526 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00003527 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003528 for (RecordDecl::field_iterator Field = RD->field_begin(),
3529 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3530 // Anonymous bit-fields are not considered members of the class for
3531 // purposes of aggregate initialization.
3532 if (Field->isUnnamedBitfield())
3533 continue;
3534
3535 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003536
Richard Smith253c2a32012-01-27 01:14:48 +00003537 bool HaveInit = ElementNo < E->getNumInits();
3538
3539 // FIXME: Diagnostics here should point to the end of the initializer
3540 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00003541 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00003542 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003543 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003544
3545 // Perform an implicit value-initialization for members beyond the end of
3546 // the initializer list.
3547 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00003548 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00003549
Richard Smith852c9db2013-04-20 22:23:05 +00003550 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3551 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3552 isa<CXXDefaultInitExpr>(Init));
3553
3554 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
3555 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00003556 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00003557 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003558 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00003559 }
3560 }
3561
Richard Smith253c2a32012-01-27 01:14:48 +00003562 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003563}
3564
3565bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3566 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00003567 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3568
Richard Smithfddd3842011-12-30 21:15:51 +00003569 bool ZeroInit = E->requiresZeroInitialization();
3570 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00003571 // If we've already performed zero-initialization, we're already done.
3572 if (!Result.isUninit())
3573 return true;
3574
Richard Smithfddd3842011-12-30 21:15:51 +00003575 if (ZeroInit)
3576 return ZeroInitialization(E);
3577
Richard Smithcc36f692011-12-22 02:22:31 +00003578 const CXXRecordDecl *RD = FD->getParent();
3579 if (RD->isUnion())
3580 Result = APValue((FieldDecl*)0);
3581 else
3582 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3583 std::distance(RD->field_begin(), RD->field_end()));
3584 return true;
3585 }
3586
Richard Smithd62306a2011-11-10 06:34:14 +00003587 const FunctionDecl *Definition = 0;
3588 FD->getBody(Definition);
3589
Richard Smith357362d2011-12-13 06:39:58 +00003590 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3591 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003592
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003593 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00003594 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003595 if (const MaterializeTemporaryExpr *ME
3596 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3597 return Visit(ME->GetTemporaryExpr());
3598
Richard Smithfddd3842011-12-30 21:15:51 +00003599 if (ZeroInit && !ZeroInitialization(E))
3600 return false;
3601
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003602 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00003603 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003604 cast<CXXConstructorDecl>(Definition), Info,
3605 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003606}
3607
3608static bool EvaluateRecord(const Expr *E, const LValue &This,
3609 APValue &Result, EvalInfo &Info) {
3610 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003611 "can't evaluate expression as a record rvalue");
3612 return RecordExprEvaluator(Info, This, Result).Visit(E);
3613}
3614
3615//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003616// Temporary Evaluation
3617//
3618// Temporaries are represented in the AST as rvalues, but generally behave like
3619// lvalues. The full-object of which the temporary is a subobject is implicitly
3620// materialized so that a reference can bind to it.
3621//===----------------------------------------------------------------------===//
3622namespace {
3623class TemporaryExprEvaluator
3624 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3625public:
3626 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3627 LValueExprEvaluatorBaseTy(Info, Result) {}
3628
3629 /// Visit an expression which constructs the value of this temporary.
3630 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003631 Result.set(E, Info.CurrentCall->Index);
3632 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00003633 }
3634
3635 bool VisitCastExpr(const CastExpr *E) {
3636 switch (E->getCastKind()) {
3637 default:
3638 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3639
3640 case CK_ConstructorConversion:
3641 return VisitConstructExpr(E->getSubExpr());
3642 }
3643 }
3644 bool VisitInitListExpr(const InitListExpr *E) {
3645 return VisitConstructExpr(E);
3646 }
3647 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3648 return VisitConstructExpr(E);
3649 }
3650 bool VisitCallExpr(const CallExpr *E) {
3651 return VisitConstructExpr(E);
3652 }
3653};
3654} // end anonymous namespace
3655
3656/// Evaluate an expression of record type as a temporary.
3657static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003658 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003659 return TemporaryExprEvaluator(Info, Result).Visit(E);
3660}
3661
3662//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003663// Vector Evaluation
3664//===----------------------------------------------------------------------===//
3665
3666namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003667 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003668 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3669 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003670 public:
Mike Stump11289f42009-09-09 15:08:12 +00003671
Richard Smith2d406342011-10-22 21:10:00 +00003672 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3673 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003674
Richard Smith2d406342011-10-22 21:10:00 +00003675 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3676 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3677 // FIXME: remove this APValue copy.
3678 Result = APValue(V.data(), V.size());
3679 return true;
3680 }
Richard Smith2e312c82012-03-03 22:46:17 +00003681 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00003682 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003683 Result = V;
3684 return true;
3685 }
Richard Smithfddd3842011-12-30 21:15:51 +00003686 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003687
Richard Smith2d406342011-10-22 21:10:00 +00003688 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003689 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003690 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003691 bool VisitInitListExpr(const InitListExpr *E);
3692 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003693 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003694 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003695 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003696 };
3697} // end anonymous namespace
3698
3699static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003700 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003701 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003702}
3703
Richard Smith2d406342011-10-22 21:10:00 +00003704bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3705 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003706 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003707
Richard Smith161f09a2011-12-06 22:44:34 +00003708 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003709 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003710
Eli Friedmanc757de22011-03-25 00:43:55 +00003711 switch (E->getCastKind()) {
3712 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003713 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003714 if (SETy->isIntegerType()) {
3715 APSInt IntResult;
3716 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003717 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003718 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003719 } else if (SETy->isRealFloatingType()) {
3720 APFloat F(0.0);
3721 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003722 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003723 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003724 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003725 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003726 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003727
3728 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003729 SmallVector<APValue, 4> Elts(NElts, Val);
3730 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003731 }
Eli Friedman803acb32011-12-22 03:51:45 +00003732 case CK_BitCast: {
3733 // Evaluate the operand into an APInt we can extract from.
3734 llvm::APInt SValInt;
3735 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3736 return false;
3737 // Extract the elements
3738 QualType EltTy = VTy->getElementType();
3739 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3740 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3741 SmallVector<APValue, 4> Elts;
3742 if (EltTy->isRealFloatingType()) {
3743 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00003744 unsigned FloatEltSize = EltSize;
3745 if (&Sem == &APFloat::x87DoubleExtended)
3746 FloatEltSize = 80;
3747 for (unsigned i = 0; i < NElts; i++) {
3748 llvm::APInt Elt;
3749 if (BigEndian)
3750 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3751 else
3752 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00003753 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00003754 }
3755 } else if (EltTy->isIntegerType()) {
3756 for (unsigned i = 0; i < NElts; i++) {
3757 llvm::APInt Elt;
3758 if (BigEndian)
3759 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3760 else
3761 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3762 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3763 }
3764 } else {
3765 return Error(E);
3766 }
3767 return Success(Elts, E);
3768 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003769 default:
Richard Smith11562c52011-10-28 17:51:58 +00003770 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003771 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003772}
3773
Richard Smith2d406342011-10-22 21:10:00 +00003774bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003775VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003776 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003777 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003778 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003779
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003780 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003781 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003782
Eli Friedmanb9c71292012-01-03 23:24:20 +00003783 // The number of initializers can be less than the number of
3784 // vector elements. For OpenCL, this can be due to nested vector
3785 // initialization. For GCC compatibility, missing trailing elements
3786 // should be initialized with zeroes.
3787 unsigned CountInits = 0, CountElts = 0;
3788 while (CountElts < NumElements) {
3789 // Handle nested vector initialization.
3790 if (CountInits < NumInits
3791 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3792 APValue v;
3793 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3794 return Error(E);
3795 unsigned vlen = v.getVectorLength();
3796 for (unsigned j = 0; j < vlen; j++)
3797 Elements.push_back(v.getVectorElt(j));
3798 CountElts += vlen;
3799 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003800 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003801 if (CountInits < NumInits) {
3802 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00003803 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00003804 } else // trailing integer zero.
3805 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3806 Elements.push_back(APValue(sInt));
3807 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003808 } else {
3809 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003810 if (CountInits < NumInits) {
3811 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00003812 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00003813 } else // trailing float zero.
3814 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3815 Elements.push_back(APValue(f));
3816 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003817 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003818 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003819 }
Richard Smith2d406342011-10-22 21:10:00 +00003820 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003821}
3822
Richard Smith2d406342011-10-22 21:10:00 +00003823bool
Richard Smithfddd3842011-12-30 21:15:51 +00003824VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003825 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003826 QualType EltTy = VT->getElementType();
3827 APValue ZeroElement;
3828 if (EltTy->isIntegerType())
3829 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3830 else
3831 ZeroElement =
3832 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3833
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003834 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003835 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003836}
3837
Richard Smith2d406342011-10-22 21:10:00 +00003838bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003839 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003840 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003841}
3842
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003843//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003844// Array Evaluation
3845//===----------------------------------------------------------------------===//
3846
3847namespace {
3848 class ArrayExprEvaluator
3849 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003850 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003851 APValue &Result;
3852 public:
3853
Richard Smithd62306a2011-11-10 06:34:14 +00003854 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3855 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003856
3857 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00003858 assert((V.isArray() || V.isLValue()) &&
3859 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00003860 Result = V;
3861 return true;
3862 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003863
Richard Smithfddd3842011-12-30 21:15:51 +00003864 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003865 const ConstantArrayType *CAT =
3866 Info.Ctx.getAsConstantArrayType(E->getType());
3867 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003868 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003869
3870 Result = APValue(APValue::UninitArray(), 0,
3871 CAT->getSize().getZExtValue());
3872 if (!Result.hasArrayFiller()) return true;
3873
Richard Smithfddd3842011-12-30 21:15:51 +00003874 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003875 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003876 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003877 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00003878 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00003879 }
3880
Richard Smithf3e9e432011-11-07 09:22:26 +00003881 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003882 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00003883 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
3884 const LValue &Subobject,
3885 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00003886 };
3887} // end anonymous namespace
3888
Richard Smithd62306a2011-11-10 06:34:14 +00003889static bool EvaluateArray(const Expr *E, const LValue &This,
3890 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003891 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003892 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003893}
3894
3895bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3896 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3897 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003898 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003899
Richard Smithca2cfbf2011-12-22 01:07:19 +00003900 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3901 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00003902 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00003903 LValue LV;
3904 if (!EvaluateLValue(E->getInit(0), LV, Info))
3905 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003906 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00003907 LV.moveInto(Val);
3908 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00003909 }
3910
Richard Smith253c2a32012-01-27 01:14:48 +00003911 bool Success = true;
3912
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003913 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3914 "zero-initialized array shouldn't have any initialized elts");
3915 APValue Filler;
3916 if (Result.isArray() && Result.hasArrayFiller())
3917 Filler = Result.getArrayFiller();
3918
Richard Smith9543c5e2013-04-22 14:44:29 +00003919 unsigned NumEltsToInit = E->getNumInits();
3920 unsigned NumElts = CAT->getSize().getZExtValue();
3921 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
3922
3923 // If the initializer might depend on the array index, run it for each
3924 // array element. For now, just whitelist non-class value-initialization.
3925 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
3926 NumEltsToInit = NumElts;
3927
3928 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003929
3930 // If the array was previously zero-initialized, preserve the
3931 // zero-initialized values.
3932 if (!Filler.isUninit()) {
3933 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3934 Result.getArrayInitializedElt(I) = Filler;
3935 if (Result.hasArrayFiller())
3936 Result.getArrayFiller() = Filler;
3937 }
3938
Richard Smithd62306a2011-11-10 06:34:14 +00003939 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003940 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00003941 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
3942 const Expr *Init =
3943 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00003944 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00003945 Info, Subobject, Init) ||
3946 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00003947 CAT->getElementType(), 1)) {
3948 if (!Info.keepEvaluatingAfterFailure())
3949 return false;
3950 Success = false;
3951 }
Richard Smithd62306a2011-11-10 06:34:14 +00003952 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003953
Richard Smith9543c5e2013-04-22 14:44:29 +00003954 if (!Result.hasArrayFiller())
3955 return Success;
3956
3957 // If we get here, we have a trivial filler, which we can just evaluate
3958 // once and splat over the rest of the array elements.
3959 assert(FillerExpr && "no array filler for incomplete init list");
3960 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
3961 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00003962}
3963
Richard Smith027bf112011-11-17 22:56:20 +00003964bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00003965 return VisitCXXConstructExpr(E, This, &Result, E->getType());
3966}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003967
Richard Smith9543c5e2013-04-22 14:44:29 +00003968bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
3969 const LValue &Subobject,
3970 APValue *Value,
3971 QualType Type) {
3972 bool HadZeroInit = !Value->isUninit();
3973
3974 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
3975 unsigned N = CAT->getSize().getZExtValue();
3976
3977 // Preserve the array filler if we had prior zero-initialization.
3978 APValue Filler =
3979 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
3980 : APValue();
3981
3982 *Value = APValue(APValue::UninitArray(), N, N);
3983
3984 if (HadZeroInit)
3985 for (unsigned I = 0; I != N; ++I)
3986 Value->getArrayInitializedElt(I) = Filler;
3987
3988 // Initialize the elements.
3989 LValue ArrayElt = Subobject;
3990 ArrayElt.addArray(Info, E, CAT);
3991 for (unsigned I = 0; I != N; ++I)
3992 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
3993 CAT->getElementType()) ||
3994 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
3995 CAT->getElementType(), 1))
3996 return false;
3997
3998 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003999 }
Richard Smith027bf112011-11-17 22:56:20 +00004000
Richard Smith9543c5e2013-04-22 14:44:29 +00004001 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004002 return Error(E);
4003
Richard Smith027bf112011-11-17 22:56:20 +00004004 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004005
Richard Smithfddd3842011-12-30 21:15:51 +00004006 bool ZeroInit = E->requiresZeroInitialization();
4007 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004008 if (HadZeroInit)
4009 return true;
4010
Richard Smithfddd3842011-12-30 21:15:51 +00004011 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004012 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004013 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004014 }
4015
Richard Smithcc36f692011-12-22 02:22:31 +00004016 const CXXRecordDecl *RD = FD->getParent();
4017 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004018 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004019 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004020 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004021 APValue(APValue::UninitStruct(), RD->getNumBases(),
4022 std::distance(RD->field_begin(), RD->field_end()));
4023 return true;
4024 }
4025
Richard Smith027bf112011-11-17 22:56:20 +00004026 const FunctionDecl *Definition = 0;
4027 FD->getBody(Definition);
4028
Richard Smith357362d2011-12-13 06:39:58 +00004029 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4030 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004031
Richard Smith9eae7232012-01-12 18:54:33 +00004032 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004033 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004034 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004035 return false;
4036 }
4037
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004038 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004039 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004040 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004041 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004042}
4043
Richard Smithf3e9e432011-11-07 09:22:26 +00004044//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004045// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004046//
4047// As a GNU extension, we support casting pointers to sufficiently-wide integer
4048// types and back in constant folding. Integer values are thus represented
4049// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004050//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004051
4052namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004053class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004054 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004055 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004056public:
Richard Smith2e312c82012-03-03 22:46:17 +00004057 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004058 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004059
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004060 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004061 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004062 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004063 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004064 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004065 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004066 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004067 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004068 return true;
4069 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004070 bool Success(const llvm::APSInt &SI, const Expr *E) {
4071 return Success(SI, E, Result);
4072 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004073
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004074 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004075 assert(E->getType()->isIntegralOrEnumerationType() &&
4076 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004077 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004078 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004079 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004080 Result.getInt().setIsUnsigned(
4081 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004082 return true;
4083 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004084 bool Success(const llvm::APInt &I, const Expr *E) {
4085 return Success(I, E, Result);
4086 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004087
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004088 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004089 assert(E->getType()->isIntegralOrEnumerationType() &&
4090 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004091 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004092 return true;
4093 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004094 bool Success(uint64_t Value, const Expr *E) {
4095 return Success(Value, E, Result);
4096 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004097
Ken Dyckdbc01912011-03-11 02:13:43 +00004098 bool Success(CharUnits Size, const Expr *E) {
4099 return Success(Size.getQuantity(), E);
4100 }
4101
Richard Smith2e312c82012-03-03 22:46:17 +00004102 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004103 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00004104 Result = V;
4105 return true;
4106 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004107 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004108 }
Mike Stump11289f42009-09-09 15:08:12 +00004109
Richard Smithfddd3842011-12-30 21:15:51 +00004110 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00004111
Peter Collingbournee9200682011-05-13 03:29:01 +00004112 //===--------------------------------------------------------------------===//
4113 // Visitor Methods
4114 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004115
Chris Lattner7174bf32008-07-12 00:38:25 +00004116 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004117 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004118 }
4119 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004120 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004121 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004122
4123 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4124 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004125 if (CheckReferencedDecl(E, E->getDecl()))
4126 return true;
4127
4128 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004129 }
4130 bool VisitMemberExpr(const MemberExpr *E) {
4131 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004132 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004133 return true;
4134 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004135
4136 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004137 }
4138
Peter Collingbournee9200682011-05-13 03:29:01 +00004139 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004140 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004141 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004142 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004143
Peter Collingbournee9200682011-05-13 03:29:01 +00004144 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004145 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004146
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004147 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004148 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004149 }
Mike Stump11289f42009-09-09 15:08:12 +00004150
Ted Kremeneke65b0862012-03-06 20:05:56 +00004151 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4152 return Success(E->getValue(), E);
4153 }
4154
Richard Smith4ce706a2011-10-11 21:43:33 +00004155 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004156 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004157 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004158 }
4159
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004160 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004161 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004162 }
4163
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004164 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4165 return Success(E->getValue(), E);
4166 }
4167
Douglas Gregor29c42f22012-02-24 07:38:34 +00004168 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4169 return Success(E->getValue(), E);
4170 }
4171
John Wiegley6242b6a2011-04-28 00:16:57 +00004172 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4173 return Success(E->getValue(), E);
4174 }
4175
John Wiegleyf9f65842011-04-25 06:54:41 +00004176 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4177 return Success(E->getValue(), E);
4178 }
4179
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004180 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004181 bool VisitUnaryImag(const UnaryOperator *E);
4182
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004183 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004184 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004185
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004186private:
Ken Dyck160146e2010-01-27 17:10:57 +00004187 CharUnits GetAlignOfExpr(const Expr *E);
4188 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004189 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004190 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004191 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004192};
Chris Lattner05706e882008-07-11 18:11:29 +00004193} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004194
Richard Smith11562c52011-10-28 17:51:58 +00004195/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4196/// produce either the integer value or a pointer.
4197///
4198/// GCC has a heinous extension which folds casts between pointer types and
4199/// pointer-sized integral types. We support this by allowing the evaluation of
4200/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4201/// Some simple arithmetic on such values is supported (they are treated much
4202/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004203static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004204 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004205 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004206 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004207}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004208
Richard Smithf57d8cb2011-12-09 22:58:01 +00004209static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004210 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004211 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004212 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004213 if (!Val.isInt()) {
4214 // FIXME: It would be better to produce the diagnostic for casting
4215 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004216 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004217 return false;
4218 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004219 Result = Val.getInt();
4220 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004221}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004222
Richard Smithf57d8cb2011-12-09 22:58:01 +00004223/// Check whether the given declaration can be directly converted to an integral
4224/// rvalue. If not, no diagnostic is produced; there are other things we can
4225/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004226bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004227 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004228 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004229 // Check for signedness/width mismatches between E type and ECD value.
4230 bool SameSign = (ECD->getInitVal().isSigned()
4231 == E->getType()->isSignedIntegerOrEnumerationType());
4232 bool SameWidth = (ECD->getInitVal().getBitWidth()
4233 == Info.Ctx.getIntWidth(E->getType()));
4234 if (SameSign && SameWidth)
4235 return Success(ECD->getInitVal(), E);
4236 else {
4237 // Get rid of mismatch (otherwise Success assertions will fail)
4238 // by computing a new value matching the type of E.
4239 llvm::APSInt Val = ECD->getInitVal();
4240 if (!SameSign)
4241 Val.setIsSigned(!ECD->getInitVal().isSigned());
4242 if (!SameWidth)
4243 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4244 return Success(Val, E);
4245 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004246 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004247 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004248}
4249
Chris Lattner86ee2862008-10-06 06:40:35 +00004250/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4251/// as GCC.
4252static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4253 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004254 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004255 enum gcc_type_class {
4256 no_type_class = -1,
4257 void_type_class, integer_type_class, char_type_class,
4258 enumeral_type_class, boolean_type_class,
4259 pointer_type_class, reference_type_class, offset_type_class,
4260 real_type_class, complex_type_class,
4261 function_type_class, method_type_class,
4262 record_type_class, union_type_class,
4263 array_type_class, string_type_class,
4264 lang_type_class
4265 };
Mike Stump11289f42009-09-09 15:08:12 +00004266
4267 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004268 // ideal, however it is what gcc does.
4269 if (E->getNumArgs() == 0)
4270 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004271
Chris Lattner86ee2862008-10-06 06:40:35 +00004272 QualType ArgTy = E->getArg(0)->getType();
4273 if (ArgTy->isVoidType())
4274 return void_type_class;
4275 else if (ArgTy->isEnumeralType())
4276 return enumeral_type_class;
4277 else if (ArgTy->isBooleanType())
4278 return boolean_type_class;
4279 else if (ArgTy->isCharType())
4280 return string_type_class; // gcc doesn't appear to use char_type_class
4281 else if (ArgTy->isIntegerType())
4282 return integer_type_class;
4283 else if (ArgTy->isPointerType())
4284 return pointer_type_class;
4285 else if (ArgTy->isReferenceType())
4286 return reference_type_class;
4287 else if (ArgTy->isRealType())
4288 return real_type_class;
4289 else if (ArgTy->isComplexType())
4290 return complex_type_class;
4291 else if (ArgTy->isFunctionType())
4292 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004293 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004294 return record_type_class;
4295 else if (ArgTy->isUnionType())
4296 return union_type_class;
4297 else if (ArgTy->isArrayType())
4298 return array_type_class;
4299 else if (ArgTy->isUnionType())
4300 return union_type_class;
4301 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004302 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004303}
4304
Richard Smith5fab0c92011-12-28 19:48:30 +00004305/// EvaluateBuiltinConstantPForLValue - Determine the result of
4306/// __builtin_constant_p when applied to the given lvalue.
4307///
4308/// An lvalue is only "constant" if it is a pointer or reference to the first
4309/// character of a string literal.
4310template<typename LValue>
4311static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004312 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004313 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4314}
4315
4316/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4317/// GCC as we can manage.
4318static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4319 QualType ArgType = Arg->getType();
4320
4321 // __builtin_constant_p always has one operand. The rules which gcc follows
4322 // are not precisely documented, but are as follows:
4323 //
4324 // - If the operand is of integral, floating, complex or enumeration type,
4325 // and can be folded to a known value of that type, it returns 1.
4326 // - If the operand and can be folded to a pointer to the first character
4327 // of a string literal (or such a pointer cast to an integral type), it
4328 // returns 1.
4329 //
4330 // Otherwise, it returns 0.
4331 //
4332 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4333 // its support for this does not currently work.
4334 if (ArgType->isIntegralOrEnumerationType()) {
4335 Expr::EvalResult Result;
4336 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4337 return false;
4338
4339 APValue &V = Result.Val;
4340 if (V.getKind() == APValue::Int)
4341 return true;
4342
4343 return EvaluateBuiltinConstantPForLValue(V);
4344 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4345 return Arg->isEvaluatable(Ctx);
4346 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4347 LValue LV;
4348 Expr::EvalStatus Status;
4349 EvalInfo Info(Ctx, Status);
4350 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4351 : EvaluatePointer(Arg, LV, Info)) &&
4352 !Status.HasSideEffects)
4353 return EvaluateBuiltinConstantPForLValue(LV);
4354 }
4355
4356 // Anything else isn't considered to be sufficiently constant.
4357 return false;
4358}
4359
John McCall95007602010-05-10 23:27:23 +00004360/// Retrieves the "underlying object type" of the given expression,
4361/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004362QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4363 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4364 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004365 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004366 } else if (const Expr *E = B.get<const Expr*>()) {
4367 if (isa<CompoundLiteralExpr>(E))
4368 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004369 }
4370
4371 return QualType();
4372}
4373
Peter Collingbournee9200682011-05-13 03:29:01 +00004374bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004375 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004376
4377 {
4378 // The operand of __builtin_object_size is never evaluated for side-effects.
4379 // If there are any, but we can determine the pointed-to object anyway, then
4380 // ignore the side-effects.
4381 SpeculativeEvaluationRAII SpeculativeEval(Info);
4382 if (!EvaluatePointer(E->getArg(0), Base, Info))
4383 return false;
4384 }
John McCall95007602010-05-10 23:27:23 +00004385
4386 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004387 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004388
Richard Smithce40ad62011-11-12 22:28:03 +00004389 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004390 if (T.isNull() ||
4391 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004392 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004393 T->isVariablyModifiedType() ||
4394 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004395 return Error(E);
John McCall95007602010-05-10 23:27:23 +00004396
4397 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4398 CharUnits Offset = Base.getLValueOffset();
4399
4400 if (!Offset.isNegative() && Offset <= Size)
4401 Size -= Offset;
4402 else
4403 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00004404 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00004405}
4406
Peter Collingbournee9200682011-05-13 03:29:01 +00004407bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00004408 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004409 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00004410 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004411
4412 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00004413 if (TryEvaluateBuiltinObjectSize(E))
4414 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00004415
Richard Smith0421ce72012-08-07 04:16:51 +00004416 // If evaluating the argument has side-effects, we can't determine the size
4417 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4418 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004419 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00004420 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00004421 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00004422 return Success(0, E);
4423 }
Mike Stump876387b2009-10-27 22:09:17 +00004424
Richard Smith01ade172012-05-23 04:13:20 +00004425 // Expression had no side effects, but we couldn't statically determine the
4426 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004427 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004428 }
4429
Benjamin Kramera801f4a2012-10-06 14:42:22 +00004430 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00004431 case Builtin::BI__builtin_bswap32:
4432 case Builtin::BI__builtin_bswap64: {
4433 APSInt Val;
4434 if (!EvaluateInteger(E->getArg(0), Val, Info))
4435 return false;
4436
4437 return Success(Val.byteSwap(), E);
4438 }
4439
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004440 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004441 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00004442
Richard Smith5fab0c92011-12-28 19:48:30 +00004443 case Builtin::BI__builtin_constant_p:
4444 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00004445
Chris Lattnerd545ad12009-09-23 06:06:36 +00004446 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00004447 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00004448 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00004449 return Success(Operand, E);
4450 }
Eli Friedmand5c93992010-02-13 00:10:10 +00004451
4452 case Builtin::BI__builtin_expect:
4453 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00004454
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004455 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00004456 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004457 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00004458 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00004459 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4460 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00004461 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00004462 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004463 case Builtin::BI__builtin_strlen:
4464 // As an extension, we support strlen() and __builtin_strlen() as constant
4465 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00004466 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004467 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4468 // The string literal may have embedded null characters. Find the first
4469 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004470 StringRef Str = S->getString();
4471 StringRef::size_type Pos = Str.find(0);
4472 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004473 Str = Str.substr(0, Pos);
4474
4475 return Success(Str.size(), E);
4476 }
4477
Richard Smithf57d8cb2011-12-09 22:58:01 +00004478 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004479
Richard Smith01ba47d2012-04-13 00:45:38 +00004480 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00004481 case Builtin::BI__atomic_is_lock_free:
4482 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00004483 APSInt SizeVal;
4484 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4485 return false;
4486
4487 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4488 // of two less than the maximum inline atomic width, we know it is
4489 // lock-free. If the size isn't a power of two, or greater than the
4490 // maximum alignment where we promote atomics, we know it is not lock-free
4491 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4492 // the answer can only be determined at runtime; for example, 16-byte
4493 // atomics have lock-free implementations on some, but not all,
4494 // x86-64 processors.
4495
4496 // Check power-of-two.
4497 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00004498 if (Size.isPowerOfTwo()) {
4499 // Check against inlining width.
4500 unsigned InlineWidthBits =
4501 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4502 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4503 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4504 Size == CharUnits::One() ||
4505 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4506 Expr::NPC_NeverValueDependent))
4507 // OK, we will inline appropriately-aligned operations of this size,
4508 // and _Atomic(T) is appropriately-aligned.
4509 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004510
Richard Smith01ba47d2012-04-13 00:45:38 +00004511 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4512 castAs<PointerType>()->getPointeeType();
4513 if (!PointeeType->isIncompleteType() &&
4514 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4515 // OK, we will inline operations on this object.
4516 return Success(1, E);
4517 }
4518 }
4519 }
Eli Friedmana4c26022011-10-17 21:44:23 +00004520
Richard Smith01ba47d2012-04-13 00:45:38 +00004521 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4522 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004523 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004524 }
Chris Lattner7174bf32008-07-12 00:38:25 +00004525}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004526
Richard Smith8b3497e2011-10-31 01:37:14 +00004527static bool HasSameBase(const LValue &A, const LValue &B) {
4528 if (!A.getLValueBase())
4529 return !B.getLValueBase();
4530 if (!B.getLValueBase())
4531 return false;
4532
Richard Smithce40ad62011-11-12 22:28:03 +00004533 if (A.getLValueBase().getOpaqueValue() !=
4534 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004535 const Decl *ADecl = GetLValueBaseDecl(A);
4536 if (!ADecl)
4537 return false;
4538 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00004539 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00004540 return false;
4541 }
4542
4543 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00004544 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00004545}
4546
Richard Smithc8042322012-02-01 05:53:12 +00004547/// Perform the given integer operation, which is known to need at most BitWidth
4548/// bits, and check for overflow in the original type (if that type was not an
4549/// unsigned type).
4550template<typename Operation>
4551static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4552 const APSInt &LHS, const APSInt &RHS,
4553 unsigned BitWidth, Operation Op) {
4554 if (LHS.isUnsigned())
4555 return Op(LHS, RHS);
4556
4557 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4558 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00004559 if (Result.extend(BitWidth) != Value) {
4560 if (Info.getIntOverflowCheckMode())
4561 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4562 diag::warn_integer_constant_overflow)
4563 << Result.toString(10) << E->getType();
4564 else
4565 HandleOverflow(Info, E, Value, E->getType());
4566 }
Richard Smithc8042322012-02-01 05:53:12 +00004567 return Result;
4568}
4569
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004570namespace {
Richard Smith11562c52011-10-28 17:51:58 +00004571
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004572/// \brief Data recursive integer evaluator of certain binary operators.
4573///
4574/// We use a data recursive algorithm for binary operators so that we are able
4575/// to handle extreme cases of chained binary operators without causing stack
4576/// overflow.
4577class DataRecursiveIntBinOpEvaluator {
4578 struct EvalResult {
4579 APValue Val;
4580 bool Failed;
4581
4582 EvalResult() : Failed(false) { }
4583
4584 void swap(EvalResult &RHS) {
4585 Val.swap(RHS.Val);
4586 Failed = RHS.Failed;
4587 RHS.Failed = false;
4588 }
4589 };
4590
4591 struct Job {
4592 const Expr *E;
4593 EvalResult LHSResult; // meaningful only for binary operator expression.
4594 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4595
4596 Job() : StoredInfo(0) { }
4597 void startSpeculativeEval(EvalInfo &Info) {
4598 OldEvalStatus = Info.EvalStatus;
4599 Info.EvalStatus.Diag = 0;
4600 StoredInfo = &Info;
4601 }
4602 ~Job() {
4603 if (StoredInfo) {
4604 StoredInfo->EvalStatus = OldEvalStatus;
4605 }
4606 }
4607 private:
4608 EvalInfo *StoredInfo; // non-null if status changed.
4609 Expr::EvalStatus OldEvalStatus;
4610 };
4611
4612 SmallVector<Job, 16> Queue;
4613
4614 IntExprEvaluator &IntEval;
4615 EvalInfo &Info;
4616 APValue &FinalResult;
4617
4618public:
4619 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4620 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4621
4622 /// \brief True if \param E is a binary operator that we are going to handle
4623 /// data recursively.
4624 /// We handle binary operators that are comma, logical, or that have operands
4625 /// with integral or enumeration type.
4626 static bool shouldEnqueue(const BinaryOperator *E) {
4627 return E->getOpcode() == BO_Comma ||
4628 E->isLogicalOp() ||
4629 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4630 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00004631 }
4632
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004633 bool Traverse(const BinaryOperator *E) {
4634 enqueue(E);
4635 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00004636 while (!Queue.empty())
4637 process(PrevResult);
4638
4639 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004640
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004641 FinalResult.swap(PrevResult.Val);
4642 return true;
4643 }
4644
4645private:
4646 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4647 return IntEval.Success(Value, E, Result);
4648 }
4649 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4650 return IntEval.Success(Value, E, Result);
4651 }
4652 bool Error(const Expr *E) {
4653 return IntEval.Error(E);
4654 }
4655 bool Error(const Expr *E, diag::kind D) {
4656 return IntEval.Error(E, D);
4657 }
4658
4659 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4660 return Info.CCEDiag(E, D);
4661 }
4662
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004663 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4664 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004665 bool &SuppressRHSDiags);
4666
4667 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4668 const BinaryOperator *E, APValue &Result);
4669
4670 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4671 Result.Failed = !Evaluate(Result.Val, Info, E);
4672 if (Result.Failed)
4673 Result.Val = APValue();
4674 }
4675
Richard Trieuba4d0872012-03-21 23:30:30 +00004676 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004677
4678 void enqueue(const Expr *E) {
4679 E = E->IgnoreParens();
4680 Queue.resize(Queue.size()+1);
4681 Queue.back().E = E;
4682 Queue.back().Kind = Job::AnyExprKind;
4683 }
4684};
4685
4686}
4687
4688bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004689 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004690 bool &SuppressRHSDiags) {
4691 if (E->getOpcode() == BO_Comma) {
4692 // Ignore LHS but note if we could not evaluate it.
4693 if (LHSResult.Failed)
4694 Info.EvalStatus.HasSideEffects = true;
4695 return true;
4696 }
4697
4698 if (E->isLogicalOp()) {
4699 bool lhsResult;
4700 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004701 // We were able to evaluate the LHS, see if we can get away with not
4702 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004703 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004704 Success(lhsResult, E, LHSResult.Val);
4705 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004706 }
4707 } else {
4708 // Since we weren't able to evaluate the left hand side, it
4709 // must have had side effects.
4710 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004711
4712 // We can't evaluate the LHS; however, sometimes the result
4713 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4714 // Don't ignore RHS and suppress diagnostics from this arm.
4715 SuppressRHSDiags = true;
4716 }
4717
4718 return true;
4719 }
4720
4721 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4722 E->getRHS()->getType()->isIntegralOrEnumerationType());
4723
4724 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004725 return false; // Ignore RHS;
4726
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004727 return true;
4728}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004729
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004730bool DataRecursiveIntBinOpEvaluator::
4731 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4732 const BinaryOperator *E, APValue &Result) {
4733 if (E->getOpcode() == BO_Comma) {
4734 if (RHSResult.Failed)
4735 return false;
4736 Result = RHSResult.Val;
4737 return true;
4738 }
4739
4740 if (E->isLogicalOp()) {
4741 bool lhsResult, rhsResult;
4742 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4743 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4744
4745 if (LHSIsOK) {
4746 if (RHSIsOK) {
4747 if (E->getOpcode() == BO_LOr)
4748 return Success(lhsResult || rhsResult, E, Result);
4749 else
4750 return Success(lhsResult && rhsResult, E, Result);
4751 }
4752 } else {
4753 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004754 // We can't evaluate the LHS; however, sometimes the result
4755 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4756 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004757 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004758 }
4759 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004760
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004761 return false;
4762 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004763
4764 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4765 E->getRHS()->getType()->isIntegralOrEnumerationType());
4766
4767 if (LHSResult.Failed || RHSResult.Failed)
4768 return false;
4769
4770 const APValue &LHSVal = LHSResult.Val;
4771 const APValue &RHSVal = RHSResult.Val;
4772
4773 // Handle cases like (unsigned long)&a + 4.
4774 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4775 Result = LHSVal;
4776 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4777 RHSVal.getInt().getZExtValue());
4778 if (E->getOpcode() == BO_Add)
4779 Result.getLValueOffset() += AdditionalOffset;
4780 else
4781 Result.getLValueOffset() -= AdditionalOffset;
4782 return true;
4783 }
4784
4785 // Handle cases like 4 + (unsigned long)&a
4786 if (E->getOpcode() == BO_Add &&
4787 RHSVal.isLValue() && LHSVal.isInt()) {
4788 Result = RHSVal;
4789 Result.getLValueOffset() += CharUnits::fromQuantity(
4790 LHSVal.getInt().getZExtValue());
4791 return true;
4792 }
4793
4794 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4795 // Handle (intptr_t)&&A - (intptr_t)&&B.
4796 if (!LHSVal.getLValueOffset().isZero() ||
4797 !RHSVal.getLValueOffset().isZero())
4798 return false;
4799 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4800 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4801 if (!LHSExpr || !RHSExpr)
4802 return false;
4803 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4804 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4805 if (!LHSAddrExpr || !RHSAddrExpr)
4806 return false;
4807 // Make sure both labels come from the same function.
4808 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4809 RHSAddrExpr->getLabel()->getDeclContext())
4810 return false;
4811 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4812 return true;
4813 }
4814
4815 // All the following cases expect both operands to be an integer
4816 if (!LHSVal.isInt() || !RHSVal.isInt())
4817 return Error(E);
4818
4819 const APSInt &LHS = LHSVal.getInt();
4820 APSInt RHS = RHSVal.getInt();
4821
4822 switch (E->getOpcode()) {
4823 default:
4824 return Error(E);
4825 case BO_Mul:
4826 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4827 LHS.getBitWidth() * 2,
4828 std::multiplies<APSInt>()), E,
4829 Result);
4830 case BO_Add:
4831 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4832 LHS.getBitWidth() + 1,
4833 std::plus<APSInt>()), E, Result);
4834 case BO_Sub:
4835 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4836 LHS.getBitWidth() + 1,
4837 std::minus<APSInt>()), E, Result);
4838 case BO_And: return Success(LHS & RHS, E, Result);
4839 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4840 case BO_Or: return Success(LHS | RHS, E, Result);
4841 case BO_Div:
4842 case BO_Rem:
4843 if (RHS == 0)
4844 return Error(E, diag::note_expr_divide_by_zero);
4845 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4846 // not actually undefined behavior in C++11 due to a language defect.
4847 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4848 LHS.isSigned() && LHS.isMinSignedValue())
4849 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4850 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4851 Result);
4852 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00004853 if (Info.getLangOpts().OpenCL)
4854 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00004855 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00004856 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4857 RHS.isUnsigned());
4858 else if (RHS.isSigned() && RHS.isNegative()) {
4859 // During constant-folding, a negative shift is an opposite shift. Such
4860 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004861 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4862 RHS = -RHS;
4863 goto shift_right;
4864 }
4865
4866 shift_left:
4867 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4868 // the shifted type.
4869 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4870 if (SA != RHS) {
4871 CCEDiag(E, diag::note_constexpr_large_shift)
4872 << RHS << E->getType() << LHS.getBitWidth();
4873 } else if (LHS.isSigned()) {
4874 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4875 // operand, and must not overflow the corresponding unsigned type.
4876 if (LHS.isNegative())
4877 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4878 else if (LHS.countLeadingZeros() < SA)
4879 CCEDiag(E, diag::note_constexpr_lshift_discards);
4880 }
4881
4882 return Success(LHS << SA, E, Result);
4883 }
4884 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00004885 if (Info.getLangOpts().OpenCL)
4886 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00004887 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00004888 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4889 RHS.isUnsigned());
4890 else if (RHS.isSigned() && RHS.isNegative()) {
4891 // During constant-folding, a negative shift is an opposite shift. Such a
4892 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004893 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4894 RHS = -RHS;
4895 goto shift_left;
4896 }
4897
4898 shift_right:
4899 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4900 // shifted type.
4901 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4902 if (SA != RHS)
4903 CCEDiag(E, diag::note_constexpr_large_shift)
4904 << RHS << E->getType() << LHS.getBitWidth();
4905
4906 return Success(LHS >> SA, E, Result);
4907 }
4908
4909 case BO_LT: return Success(LHS < RHS, E, Result);
4910 case BO_GT: return Success(LHS > RHS, E, Result);
4911 case BO_LE: return Success(LHS <= RHS, E, Result);
4912 case BO_GE: return Success(LHS >= RHS, E, Result);
4913 case BO_EQ: return Success(LHS == RHS, E, Result);
4914 case BO_NE: return Success(LHS != RHS, E, Result);
4915 }
4916}
4917
Richard Trieuba4d0872012-03-21 23:30:30 +00004918void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004919 Job &job = Queue.back();
4920
4921 switch (job.Kind) {
4922 case Job::AnyExprKind: {
4923 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4924 if (shouldEnqueue(Bop)) {
4925 job.Kind = Job::BinOpKind;
4926 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00004927 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004928 }
4929 }
4930
4931 EvaluateExpr(job.E, Result);
4932 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004933 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004934 }
4935
4936 case Job::BinOpKind: {
4937 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004938 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004939 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004940 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004941 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004942 }
4943 if (SuppressRHSDiags)
4944 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004945 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004946 job.Kind = Job::BinOpVisitedLHSKind;
4947 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00004948 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004949 }
4950
4951 case Job::BinOpVisitedLHSKind: {
4952 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4953 EvalResult RHS;
4954 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00004955 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004956 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004957 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004958 }
4959 }
4960
4961 llvm_unreachable("Invalid Job::Kind!");
4962}
4963
4964bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4965 if (E->isAssignmentOp())
4966 return Error(E);
4967
4968 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4969 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004970
Anders Carlssonacc79812008-11-16 07:17:21 +00004971 QualType LHSTy = E->getLHS()->getType();
4972 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004973
4974 if (LHSTy->isAnyComplexType()) {
4975 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00004976 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004977
Richard Smith253c2a32012-01-27 01:14:48 +00004978 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4979 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004980 return false;
4981
Richard Smith253c2a32012-01-27 01:14:48 +00004982 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004983 return false;
4984
4985 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00004986 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004987 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00004988 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004989 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4990
John McCalle3027922010-08-25 11:45:40 +00004991 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004992 return Success((CR_r == APFloat::cmpEqual &&
4993 CR_i == APFloat::cmpEqual), E);
4994 else {
John McCalle3027922010-08-25 11:45:40 +00004995 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004996 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00004997 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004998 CR_r == APFloat::cmpLessThan ||
4999 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005000 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005001 CR_i == APFloat::cmpLessThan ||
5002 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005003 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005004 } else {
John McCalle3027922010-08-25 11:45:40 +00005005 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005006 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5007 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5008 else {
John McCalle3027922010-08-25 11:45:40 +00005009 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005010 "Invalid compex comparison.");
5011 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5012 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5013 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005014 }
5015 }
Mike Stump11289f42009-09-09 15:08:12 +00005016
Anders Carlssonacc79812008-11-16 07:17:21 +00005017 if (LHSTy->isRealFloatingType() &&
5018 RHSTy->isRealFloatingType()) {
5019 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005020
Richard Smith253c2a32012-01-27 01:14:48 +00005021 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5022 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005023 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005024
Richard Smith253c2a32012-01-27 01:14:48 +00005025 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005026 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005027
Anders Carlssonacc79812008-11-16 07:17:21 +00005028 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005029
Anders Carlssonacc79812008-11-16 07:17:21 +00005030 switch (E->getOpcode()) {
5031 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005032 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005033 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005034 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005035 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005036 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005037 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005038 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005039 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005040 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005041 E);
John McCalle3027922010-08-25 11:45:40 +00005042 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005043 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005044 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005045 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005046 || CR == APFloat::cmpLessThan
5047 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005048 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005049 }
Mike Stump11289f42009-09-09 15:08:12 +00005050
Eli Friedmana38da572009-04-28 19:17:36 +00005051 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005052 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005053 LValue LHSValue, RHSValue;
5054
5055 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5056 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005057 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005058
Richard Smith253c2a32012-01-27 01:14:48 +00005059 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005060 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005061
Richard Smith8b3497e2011-10-31 01:37:14 +00005062 // Reject differing bases from the normal codepath; we special-case
5063 // comparisons to null.
5064 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005065 if (E->getOpcode() == BO_Sub) {
5066 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005067 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5068 return false;
5069 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005070 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005071 if (!LHSExpr || !RHSExpr)
5072 return false;
5073 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5074 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5075 if (!LHSAddrExpr || !RHSAddrExpr)
5076 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005077 // Make sure both labels come from the same function.
5078 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5079 RHSAddrExpr->getLabel()->getDeclContext())
5080 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005081 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005082 return true;
5083 }
Richard Smith83c68212011-10-31 05:11:32 +00005084 // Inequalities and subtractions between unrelated pointers have
5085 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005086 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005087 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005088 // A constant address may compare equal to the address of a symbol.
5089 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005090 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005091 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5092 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005093 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005094 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005095 // distinct addresses. In clang, the result of such a comparison is
5096 // unspecified, so it is not a constant expression. However, we do know
5097 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005098 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5099 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005100 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005101 // We can't tell whether weak symbols will end up pointing to the same
5102 // object.
5103 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005104 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005105 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005106 // (Note that clang defaults to -fmerge-all-constants, which can
5107 // lead to inconsistent results for comparisons involving the address
5108 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005109 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005110 }
Eli Friedman64004332009-03-23 04:38:34 +00005111
Richard Smith1b470412012-02-01 08:10:20 +00005112 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5113 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5114
Richard Smith84f6dcf2012-02-02 01:16:57 +00005115 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5116 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5117
John McCalle3027922010-08-25 11:45:40 +00005118 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005119 // C++11 [expr.add]p6:
5120 // Unless both pointers point to elements of the same array object, or
5121 // one past the last element of the array object, the behavior is
5122 // undefined.
5123 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5124 !AreElementsOfSameArray(getType(LHSValue.Base),
5125 LHSDesignator, RHSDesignator))
5126 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5127
Chris Lattner882bdf22010-04-20 17:13:14 +00005128 QualType Type = E->getLHS()->getType();
5129 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005130
Richard Smithd62306a2011-11-10 06:34:14 +00005131 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005132 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005133 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005134
Richard Smith1b470412012-02-01 08:10:20 +00005135 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5136 // and produce incorrect results when it overflows. Such behavior
5137 // appears to be non-conforming, but is common, so perhaps we should
5138 // assume the standard intended for such cases to be undefined behavior
5139 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005140
Richard Smith1b470412012-02-01 08:10:20 +00005141 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5142 // overflow in the final conversion to ptrdiff_t.
5143 APSInt LHS(
5144 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5145 APSInt RHS(
5146 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5147 APSInt ElemSize(
5148 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5149 APSInt TrueResult = (LHS - RHS) / ElemSize;
5150 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5151
5152 if (Result.extend(65) != TrueResult)
5153 HandleOverflow(Info, E, TrueResult, E->getType());
5154 return Success(Result, E);
5155 }
Richard Smithde21b242012-01-31 06:41:30 +00005156
5157 // C++11 [expr.rel]p3:
5158 // Pointers to void (after pointer conversions) can be compared, with a
5159 // result defined as follows: If both pointers represent the same
5160 // address or are both the null pointer value, the result is true if the
5161 // operator is <= or >= and false otherwise; otherwise the result is
5162 // unspecified.
5163 // We interpret this as applying to pointers to *cv* void.
5164 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005165 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005166 CCEDiag(E, diag::note_constexpr_void_comparison);
5167
Richard Smith84f6dcf2012-02-02 01:16:57 +00005168 // C++11 [expr.rel]p2:
5169 // - If two pointers point to non-static data members of the same object,
5170 // or to subobjects or array elements fo such members, recursively, the
5171 // pointer to the later declared member compares greater provided the
5172 // two members have the same access control and provided their class is
5173 // not a union.
5174 // [...]
5175 // - Otherwise pointer comparisons are unspecified.
5176 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5177 E->isRelationalOp()) {
5178 bool WasArrayIndex;
5179 unsigned Mismatch =
5180 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5181 RHSDesignator, WasArrayIndex);
5182 // At the point where the designators diverge, the comparison has a
5183 // specified value if:
5184 // - we are comparing array indices
5185 // - we are comparing fields of a union, or fields with the same access
5186 // Otherwise, the result is unspecified and thus the comparison is not a
5187 // constant expression.
5188 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5189 Mismatch < RHSDesignator.Entries.size()) {
5190 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5191 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5192 if (!LF && !RF)
5193 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5194 else if (!LF)
5195 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5196 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5197 << RF->getParent() << RF;
5198 else if (!RF)
5199 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5200 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5201 << LF->getParent() << LF;
5202 else if (!LF->getParent()->isUnion() &&
5203 LF->getAccess() != RF->getAccess())
5204 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5205 << LF << LF->getAccess() << RF << RF->getAccess()
5206 << LF->getParent();
5207 }
5208 }
5209
Eli Friedman6c31cb42012-04-16 04:30:08 +00005210 // The comparison here must be unsigned, and performed with the same
5211 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005212 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5213 uint64_t CompareLHS = LHSOffset.getQuantity();
5214 uint64_t CompareRHS = RHSOffset.getQuantity();
5215 assert(PtrSize <= 64 && "Unexpected pointer width");
5216 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5217 CompareLHS &= Mask;
5218 CompareRHS &= Mask;
5219
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005220 // If there is a base and this is a relational operator, we can only
5221 // compare pointers within the object in question; otherwise, the result
5222 // depends on where the object is located in memory.
5223 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5224 QualType BaseTy = getType(LHSValue.Base);
5225 if (BaseTy->isIncompleteType())
5226 return Error(E);
5227 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5228 uint64_t OffsetLimit = Size.getQuantity();
5229 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5230 return Error(E);
5231 }
5232
Richard Smith8b3497e2011-10-31 01:37:14 +00005233 switch (E->getOpcode()) {
5234 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005235 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5236 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5237 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5238 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5239 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5240 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005241 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005242 }
5243 }
Richard Smith7bb00672012-02-01 01:42:44 +00005244
5245 if (LHSTy->isMemberPointerType()) {
5246 assert(E->isEqualityOp() && "unexpected member pointer operation");
5247 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5248
5249 MemberPtr LHSValue, RHSValue;
5250
5251 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5252 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5253 return false;
5254
5255 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5256 return false;
5257
5258 // C++11 [expr.eq]p2:
5259 // If both operands are null, they compare equal. Otherwise if only one is
5260 // null, they compare unequal.
5261 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5262 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5263 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5264 }
5265
5266 // Otherwise if either is a pointer to a virtual member function, the
5267 // result is unspecified.
5268 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5269 if (MD->isVirtual())
5270 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5271 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5272 if (MD->isVirtual())
5273 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5274
5275 // Otherwise they compare equal if and only if they would refer to the
5276 // same member of the same most derived object or the same subobject if
5277 // they were dereferenced with a hypothetical object of the associated
5278 // class type.
5279 bool Equal = LHSValue == RHSValue;
5280 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5281 }
5282
Richard Smithab44d9b2012-02-14 22:35:28 +00005283 if (LHSTy->isNullPtrType()) {
5284 assert(E->isComparisonOp() && "unexpected nullptr operation");
5285 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5286 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5287 // are compared, the result is true of the operator is <=, >= or ==, and
5288 // false otherwise.
5289 BinaryOperator::Opcode Opcode = E->getOpcode();
5290 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5291 }
5292
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005293 assert((!LHSTy->isIntegralOrEnumerationType() ||
5294 !RHSTy->isIntegralOrEnumerationType()) &&
5295 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5296 // We can't continue from here for non-integral types.
5297 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005298}
5299
Ken Dyck160146e2010-01-27 17:10:57 +00005300CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005301 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5302 // result shall be the alignment of the referenced type."
5303 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5304 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005305
5306 // __alignof is defined to return the preferred alignment.
5307 return Info.Ctx.toCharUnitsFromBits(
5308 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005309}
5310
Ken Dyck160146e2010-01-27 17:10:57 +00005311CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005312 E = E->IgnoreParens();
5313
5314 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005315 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005316 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005317 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5318 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005319
Chris Lattner68061312009-01-24 21:53:27 +00005320 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005321 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5322 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005323
Chris Lattner24aeeab2009-01-24 21:09:06 +00005324 return GetAlignOfType(E->getType());
5325}
5326
5327
Peter Collingbournee190dee2011-03-11 19:24:49 +00005328/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5329/// a result as the expression's type.
5330bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5331 const UnaryExprOrTypeTraitExpr *E) {
5332 switch(E->getKind()) {
5333 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005334 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005335 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005336 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005337 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005338 }
Eli Friedman64004332009-03-23 04:38:34 +00005339
Peter Collingbournee190dee2011-03-11 19:24:49 +00005340 case UETT_VecStep: {
5341 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005342
Peter Collingbournee190dee2011-03-11 19:24:49 +00005343 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005344 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005345
Peter Collingbournee190dee2011-03-11 19:24:49 +00005346 // The vec_step built-in functions that take a 3-component
5347 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5348 if (n == 3)
5349 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005350
Peter Collingbournee190dee2011-03-11 19:24:49 +00005351 return Success(n, E);
5352 } else
5353 return Success(1, E);
5354 }
5355
5356 case UETT_SizeOf: {
5357 QualType SrcTy = E->getTypeOfArgument();
5358 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5359 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005360 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5361 SrcTy = Ref->getPointeeType();
5362
Richard Smithd62306a2011-11-10 06:34:14 +00005363 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005364 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005365 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005366 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005367 }
5368 }
5369
5370 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005371}
5372
Peter Collingbournee9200682011-05-13 03:29:01 +00005373bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005374 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005375 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005376 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005377 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005378 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005379 for (unsigned i = 0; i != n; ++i) {
5380 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5381 switch (ON.getKind()) {
5382 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005383 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005384 APSInt IdxResult;
5385 if (!EvaluateInteger(Idx, IdxResult, Info))
5386 return false;
5387 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5388 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005389 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005390 CurrentType = AT->getElementType();
5391 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5392 Result += IdxResult.getSExtValue() * ElementSize;
5393 break;
5394 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005395
Douglas Gregor882211c2010-04-28 22:16:22 +00005396 case OffsetOfExpr::OffsetOfNode::Field: {
5397 FieldDecl *MemberDecl = ON.getField();
5398 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005399 if (!RT)
5400 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005401 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005402 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00005403 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00005404 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00005405 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00005406 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00005407 CurrentType = MemberDecl->getType().getNonReferenceType();
5408 break;
5409 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005410
Douglas Gregor882211c2010-04-28 22:16:22 +00005411 case OffsetOfExpr::OffsetOfNode::Identifier:
5412 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005413
Douglas Gregord1702062010-04-29 00:18:15 +00005414 case OffsetOfExpr::OffsetOfNode::Base: {
5415 CXXBaseSpecifier *BaseSpec = ON.getBase();
5416 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005417 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005418
5419 // Find the layout of the class whose base we are looking into.
5420 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005421 if (!RT)
5422 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005423 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005424 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00005425 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5426
5427 // Find the base class itself.
5428 CurrentType = BaseSpec->getType();
5429 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5430 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005431 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005432
5433 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00005434 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00005435 break;
5436 }
Douglas Gregor882211c2010-04-28 22:16:22 +00005437 }
5438 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005439 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005440}
5441
Chris Lattnere13042c2008-07-11 19:10:17 +00005442bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005443 switch (E->getOpcode()) {
5444 default:
5445 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5446 // See C99 6.6p3.
5447 return Error(E);
5448 case UO_Extension:
5449 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5450 // If so, we could clear the diagnostic ID.
5451 return Visit(E->getSubExpr());
5452 case UO_Plus:
5453 // The result is just the value.
5454 return Visit(E->getSubExpr());
5455 case UO_Minus: {
5456 if (!Visit(E->getSubExpr()))
5457 return false;
5458 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00005459 const APSInt &Value = Result.getInt();
5460 if (Value.isSigned() && Value.isMinSignedValue())
5461 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5462 E->getType());
5463 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005464 }
5465 case UO_Not: {
5466 if (!Visit(E->getSubExpr()))
5467 return false;
5468 if (!Result.isInt()) return Error(E);
5469 return Success(~Result.getInt(), E);
5470 }
5471 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00005472 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00005473 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00005474 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005475 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005476 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005477 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005478}
Mike Stump11289f42009-09-09 15:08:12 +00005479
Chris Lattner477c4be2008-07-12 01:15:53 +00005480/// HandleCast - This is used to evaluate implicit or explicit casts where the
5481/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00005482bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5483 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005484 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00005485 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005486
Eli Friedmanc757de22011-03-25 00:43:55 +00005487 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00005488 case CK_BaseToDerived:
5489 case CK_DerivedToBase:
5490 case CK_UncheckedDerivedToBase:
5491 case CK_Dynamic:
5492 case CK_ToUnion:
5493 case CK_ArrayToPointerDecay:
5494 case CK_FunctionToPointerDecay:
5495 case CK_NullToPointer:
5496 case CK_NullToMemberPointer:
5497 case CK_BaseToDerivedMemberPointer:
5498 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00005499 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00005500 case CK_ConstructorConversion:
5501 case CK_IntegralToPointer:
5502 case CK_ToVoid:
5503 case CK_VectorSplat:
5504 case CK_IntegralToFloating:
5505 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005506 case CK_CPointerToObjCPointerCast:
5507 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005508 case CK_AnyPointerToBlockPointerCast:
5509 case CK_ObjCObjectLValueCast:
5510 case CK_FloatingRealToComplex:
5511 case CK_FloatingComplexToReal:
5512 case CK_FloatingComplexCast:
5513 case CK_FloatingComplexToIntegralComplex:
5514 case CK_IntegralRealToComplex:
5515 case CK_IntegralComplexCast:
5516 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00005517 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005518 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005519 llvm_unreachable("invalid cast kind for integral value");
5520
Eli Friedman9faf2f92011-03-25 19:07:11 +00005521 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005522 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005523 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00005524 case CK_ARCProduceObject:
5525 case CK_ARCConsumeObject:
5526 case CK_ARCReclaimReturnedObject:
5527 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00005528 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005529 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005530
Richard Smith4ef685b2012-01-17 21:17:26 +00005531 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00005532 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00005533 case CK_AtomicToNonAtomic:
5534 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00005535 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00005536 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005537
5538 case CK_MemberPointerToBoolean:
5539 case CK_PointerToBoolean:
5540 case CK_IntegralToBoolean:
5541 case CK_FloatingToBoolean:
5542 case CK_FloatingComplexToBoolean:
5543 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005544 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00005545 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00005546 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005547 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005548 }
5549
Eli Friedmanc757de22011-03-25 00:43:55 +00005550 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00005551 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00005552 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00005553
Eli Friedman742421e2009-02-20 01:15:07 +00005554 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005555 // Allow casts of address-of-label differences if they are no-ops
5556 // or narrowing. (The narrowing case isn't actually guaranteed to
5557 // be constant-evaluatable except in some narrow cases which are hard
5558 // to detect here. We let it through on the assumption the user knows
5559 // what they are doing.)
5560 if (Result.isAddrLabelDiff())
5561 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00005562 // Only allow casts of lvalues if they are lossless.
5563 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5564 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005565
Richard Smith911e1422012-01-30 22:27:01 +00005566 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5567 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00005568 }
Mike Stump11289f42009-09-09 15:08:12 +00005569
Eli Friedmanc757de22011-03-25 00:43:55 +00005570 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005571 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5572
John McCall45d55e42010-05-07 21:00:08 +00005573 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00005574 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00005575 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00005576
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005577 if (LV.getLValueBase()) {
5578 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00005579 // FIXME: Allow a larger integer size than the pointer size, and allow
5580 // narrowing back down to pointer width in subsequent integral casts.
5581 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005582 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005583 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005584
Richard Smithcf74da72011-11-16 07:18:12 +00005585 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005586 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005587 return true;
5588 }
5589
Ken Dyck02990832010-01-15 12:37:54 +00005590 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5591 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00005592 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005593 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005594
Eli Friedmanc757de22011-03-25 00:43:55 +00005595 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00005596 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005597 if (!EvaluateComplex(SubExpr, C, Info))
5598 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00005599 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005600 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00005601
Eli Friedmanc757de22011-03-25 00:43:55 +00005602 case CK_FloatingToIntegral: {
5603 APFloat F(0.0);
5604 if (!EvaluateFloat(SubExpr, F, Info))
5605 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00005606
Richard Smith357362d2011-12-13 06:39:58 +00005607 APSInt Value;
5608 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5609 return false;
5610 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005611 }
5612 }
Mike Stump11289f42009-09-09 15:08:12 +00005613
Eli Friedmanc757de22011-03-25 00:43:55 +00005614 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00005615}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005616
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005617bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5618 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005619 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005620 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5621 return false;
5622 if (!LV.isComplexInt())
5623 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005624 return Success(LV.getComplexIntReal(), E);
5625 }
5626
5627 return Visit(E->getSubExpr());
5628}
5629
Eli Friedman4e7a2412009-02-27 04:45:43 +00005630bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005631 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005632 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005633 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5634 return false;
5635 if (!LV.isComplexInt())
5636 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005637 return Success(LV.getComplexIntImag(), E);
5638 }
5639
Richard Smith4a678122011-10-24 18:44:57 +00005640 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00005641 return Success(0, E);
5642}
5643
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005644bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5645 return Success(E->getPackLength(), E);
5646}
5647
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005648bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5649 return Success(E->getValue(), E);
5650}
5651
Chris Lattner05706e882008-07-11 18:11:29 +00005652//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00005653// Float Evaluation
5654//===----------------------------------------------------------------------===//
5655
5656namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005657class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005658 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00005659 APFloat &Result;
5660public:
5661 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005662 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00005663
Richard Smith2e312c82012-03-03 22:46:17 +00005664 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005665 Result = V.getFloat();
5666 return true;
5667 }
Eli Friedman24c01542008-08-22 00:06:13 +00005668
Richard Smithfddd3842011-12-30 21:15:51 +00005669 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00005670 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5671 return true;
5672 }
5673
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005674 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005675
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005676 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005677 bool VisitBinaryOperator(const BinaryOperator *E);
5678 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005679 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00005680
John McCallb1fb0d32010-05-07 22:08:54 +00005681 bool VisitUnaryReal(const UnaryOperator *E);
5682 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00005683
Richard Smithfddd3842011-12-30 21:15:51 +00005684 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00005685};
5686} // end anonymous namespace
5687
5688static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005689 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005690 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00005691}
5692
Jay Foad39c79802011-01-12 09:06:06 +00005693static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00005694 QualType ResultTy,
5695 const Expr *Arg,
5696 bool SNaN,
5697 llvm::APFloat &Result) {
5698 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5699 if (!S) return false;
5700
5701 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5702
5703 llvm::APInt fill;
5704
5705 // Treat empty strings as if they were zero.
5706 if (S->getString().empty())
5707 fill = llvm::APInt(32, 0);
5708 else if (S->getString().getAsInteger(0, fill))
5709 return false;
5710
5711 if (SNaN)
5712 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5713 else
5714 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5715 return true;
5716}
5717
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005718bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005719 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005720 default:
5721 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5722
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005723 case Builtin::BI__builtin_huge_val:
5724 case Builtin::BI__builtin_huge_valf:
5725 case Builtin::BI__builtin_huge_vall:
5726 case Builtin::BI__builtin_inf:
5727 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00005728 case Builtin::BI__builtin_infl: {
5729 const llvm::fltSemantics &Sem =
5730 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00005731 Result = llvm::APFloat::getInf(Sem);
5732 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00005733 }
Mike Stump11289f42009-09-09 15:08:12 +00005734
John McCall16291492010-02-28 13:00:19 +00005735 case Builtin::BI__builtin_nans:
5736 case Builtin::BI__builtin_nansf:
5737 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005738 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5739 true, Result))
5740 return Error(E);
5741 return true;
John McCall16291492010-02-28 13:00:19 +00005742
Chris Lattner0b7282e2008-10-06 06:31:58 +00005743 case Builtin::BI__builtin_nan:
5744 case Builtin::BI__builtin_nanf:
5745 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00005746 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00005747 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005748 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5749 false, Result))
5750 return Error(E);
5751 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005752
5753 case Builtin::BI__builtin_fabs:
5754 case Builtin::BI__builtin_fabsf:
5755 case Builtin::BI__builtin_fabsl:
5756 if (!EvaluateFloat(E->getArg(0), Result, Info))
5757 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005758
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005759 if (Result.isNegative())
5760 Result.changeSign();
5761 return true;
5762
Mike Stump11289f42009-09-09 15:08:12 +00005763 case Builtin::BI__builtin_copysign:
5764 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005765 case Builtin::BI__builtin_copysignl: {
5766 APFloat RHS(0.);
5767 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5768 !EvaluateFloat(E->getArg(1), RHS, Info))
5769 return false;
5770 Result.copySign(RHS);
5771 return true;
5772 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005773 }
5774}
5775
John McCallb1fb0d32010-05-07 22:08:54 +00005776bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00005777 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5778 ComplexValue CV;
5779 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5780 return false;
5781 Result = CV.FloatReal;
5782 return true;
5783 }
5784
5785 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00005786}
5787
5788bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00005789 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5790 ComplexValue CV;
5791 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5792 return false;
5793 Result = CV.FloatImag;
5794 return true;
5795 }
5796
Richard Smith4a678122011-10-24 18:44:57 +00005797 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00005798 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5799 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00005800 return true;
5801}
5802
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005803bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005804 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005805 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005806 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00005807 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00005808 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00005809 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5810 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005811 Result.changeSign();
5812 return true;
5813 }
5814}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005815
Eli Friedman24c01542008-08-22 00:06:13 +00005816bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005817 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5818 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00005819
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005820 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00005821 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5822 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00005823 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005824 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00005825 return false;
5826
5827 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005828 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005829 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00005830 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005831 break;
John McCalle3027922010-08-25 11:45:40 +00005832 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00005833 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005834 break;
John McCalle3027922010-08-25 11:45:40 +00005835 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00005836 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005837 break;
John McCalle3027922010-08-25 11:45:40 +00005838 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00005839 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005840 break;
Eli Friedman24c01542008-08-22 00:06:13 +00005841 }
Richard Smithc8042322012-02-01 05:53:12 +00005842
5843 if (Result.isInfinity() || Result.isNaN())
5844 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5845 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00005846}
5847
5848bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5849 Result = E->getValue();
5850 return true;
5851}
5852
Peter Collingbournee9200682011-05-13 03:29:01 +00005853bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5854 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00005855
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005856 switch (E->getCastKind()) {
5857 default:
Richard Smith11562c52011-10-28 17:51:58 +00005858 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005859
5860 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005861 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00005862 return EvaluateInteger(SubExpr, IntResult, Info) &&
5863 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5864 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005865 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005866
5867 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005868 if (!Visit(SubExpr))
5869 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005870 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5871 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005872 }
John McCalld7646252010-11-14 08:17:51 +00005873
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005874 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00005875 ComplexValue V;
5876 if (!EvaluateComplex(SubExpr, V, Info))
5877 return false;
5878 Result = V.getComplexFloatReal();
5879 return true;
5880 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005881 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005882}
5883
Eli Friedman24c01542008-08-22 00:06:13 +00005884//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005885// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00005886//===----------------------------------------------------------------------===//
5887
5888namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005889class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005890 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00005891 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00005892
Anders Carlsson537969c2008-11-16 20:27:53 +00005893public:
John McCall93d91dc2010-05-07 17:22:02 +00005894 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005895 : ExprEvaluatorBaseTy(info), Result(Result) {}
5896
Richard Smith2e312c82012-03-03 22:46:17 +00005897 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005898 Result.setFrom(V);
5899 return true;
5900 }
Mike Stump11289f42009-09-09 15:08:12 +00005901
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005902 bool ZeroInitialization(const Expr *E);
5903
Anders Carlsson537969c2008-11-16 20:27:53 +00005904 //===--------------------------------------------------------------------===//
5905 // Visitor Methods
5906 //===--------------------------------------------------------------------===//
5907
Peter Collingbournee9200682011-05-13 03:29:01 +00005908 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005909 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00005910 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005911 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005912 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00005913};
5914} // end anonymous namespace
5915
John McCall93d91dc2010-05-07 17:22:02 +00005916static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5917 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005918 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005919 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00005920}
5921
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005922bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00005923 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005924 if (ElemTy->isRealFloatingType()) {
5925 Result.makeComplexFloat();
5926 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5927 Result.FloatReal = Zero;
5928 Result.FloatImag = Zero;
5929 } else {
5930 Result.makeComplexInt();
5931 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5932 Result.IntReal = Zero;
5933 Result.IntImag = Zero;
5934 }
5935 return true;
5936}
5937
Peter Collingbournee9200682011-05-13 03:29:01 +00005938bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5939 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005940
5941 if (SubExpr->getType()->isRealFloatingType()) {
5942 Result.makeComplexFloat();
5943 APFloat &Imag = Result.FloatImag;
5944 if (!EvaluateFloat(SubExpr, Imag, Info))
5945 return false;
5946
5947 Result.FloatReal = APFloat(Imag.getSemantics());
5948 return true;
5949 } else {
5950 assert(SubExpr->getType()->isIntegerType() &&
5951 "Unexpected imaginary literal.");
5952
5953 Result.makeComplexInt();
5954 APSInt &Imag = Result.IntImag;
5955 if (!EvaluateInteger(SubExpr, Imag, Info))
5956 return false;
5957
5958 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5959 return true;
5960 }
5961}
5962
Peter Collingbournee9200682011-05-13 03:29:01 +00005963bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005964
John McCallfcef3cf2010-12-14 17:51:41 +00005965 switch (E->getCastKind()) {
5966 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005967 case CK_BaseToDerived:
5968 case CK_DerivedToBase:
5969 case CK_UncheckedDerivedToBase:
5970 case CK_Dynamic:
5971 case CK_ToUnion:
5972 case CK_ArrayToPointerDecay:
5973 case CK_FunctionToPointerDecay:
5974 case CK_NullToPointer:
5975 case CK_NullToMemberPointer:
5976 case CK_BaseToDerivedMemberPointer:
5977 case CK_DerivedToBaseMemberPointer:
5978 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00005979 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00005980 case CK_ConstructorConversion:
5981 case CK_IntegralToPointer:
5982 case CK_PointerToIntegral:
5983 case CK_PointerToBoolean:
5984 case CK_ToVoid:
5985 case CK_VectorSplat:
5986 case CK_IntegralCast:
5987 case CK_IntegralToBoolean:
5988 case CK_IntegralToFloating:
5989 case CK_FloatingToIntegral:
5990 case CK_FloatingToBoolean:
5991 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005992 case CK_CPointerToObjCPointerCast:
5993 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005994 case CK_AnyPointerToBlockPointerCast:
5995 case CK_ObjCObjectLValueCast:
5996 case CK_FloatingComplexToReal:
5997 case CK_FloatingComplexToBoolean:
5998 case CK_IntegralComplexToReal:
5999 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006000 case CK_ARCProduceObject:
6001 case CK_ARCConsumeObject:
6002 case CK_ARCReclaimReturnedObject:
6003 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006004 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006005 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006006 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006007 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006008
John McCallfcef3cf2010-12-14 17:51:41 +00006009 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006010 case CK_AtomicToNonAtomic:
6011 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006012 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006013 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006014
6015 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006016 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006017 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006018 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006019
6020 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006021 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006022 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006023 return false;
6024
John McCallfcef3cf2010-12-14 17:51:41 +00006025 Result.makeComplexFloat();
6026 Result.FloatImag = APFloat(Real.getSemantics());
6027 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006028 }
6029
John McCallfcef3cf2010-12-14 17:51:41 +00006030 case CK_FloatingComplexCast: {
6031 if (!Visit(E->getSubExpr()))
6032 return false;
6033
6034 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6035 QualType From
6036 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6037
Richard Smith357362d2011-12-13 06:39:58 +00006038 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6039 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006040 }
6041
6042 case CK_FloatingComplexToIntegralComplex: {
6043 if (!Visit(E->getSubExpr()))
6044 return false;
6045
6046 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6047 QualType From
6048 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6049 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006050 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6051 To, Result.IntReal) &&
6052 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6053 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006054 }
6055
6056 case CK_IntegralRealToComplex: {
6057 APSInt &Real = Result.IntReal;
6058 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6059 return false;
6060
6061 Result.makeComplexInt();
6062 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6063 return true;
6064 }
6065
6066 case CK_IntegralComplexCast: {
6067 if (!Visit(E->getSubExpr()))
6068 return false;
6069
6070 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6071 QualType From
6072 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6073
Richard Smith911e1422012-01-30 22:27:01 +00006074 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6075 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006076 return true;
6077 }
6078
6079 case CK_IntegralComplexToFloatingComplex: {
6080 if (!Visit(E->getSubExpr()))
6081 return false;
6082
Ted Kremenek28831752012-08-23 20:46:57 +00006083 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006084 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006085 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006086 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006087 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6088 To, Result.FloatReal) &&
6089 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6090 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006091 }
6092 }
6093
6094 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006095}
6096
John McCall93d91dc2010-05-07 17:22:02 +00006097bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006098 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006099 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6100
Richard Smith253c2a32012-01-27 01:14:48 +00006101 bool LHSOK = Visit(E->getLHS());
6102 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006103 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006104
John McCall93d91dc2010-05-07 17:22:02 +00006105 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006106 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006107 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006108
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006109 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6110 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006111 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006112 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006113 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006114 if (Result.isComplexFloat()) {
6115 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6116 APFloat::rmNearestTiesToEven);
6117 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6118 APFloat::rmNearestTiesToEven);
6119 } else {
6120 Result.getComplexIntReal() += RHS.getComplexIntReal();
6121 Result.getComplexIntImag() += RHS.getComplexIntImag();
6122 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006123 break;
John McCalle3027922010-08-25 11:45:40 +00006124 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006125 if (Result.isComplexFloat()) {
6126 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6127 APFloat::rmNearestTiesToEven);
6128 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6129 APFloat::rmNearestTiesToEven);
6130 } else {
6131 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6132 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6133 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006134 break;
John McCalle3027922010-08-25 11:45:40 +00006135 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006136 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006137 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006138 APFloat &LHS_r = LHS.getComplexFloatReal();
6139 APFloat &LHS_i = LHS.getComplexFloatImag();
6140 APFloat &RHS_r = RHS.getComplexFloatReal();
6141 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006142
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006143 APFloat Tmp = LHS_r;
6144 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6145 Result.getComplexFloatReal() = Tmp;
6146 Tmp = LHS_i;
6147 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6148 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6149
6150 Tmp = LHS_r;
6151 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6152 Result.getComplexFloatImag() = Tmp;
6153 Tmp = LHS_i;
6154 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6155 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6156 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006157 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006158 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006159 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6160 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006161 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006162 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6163 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6164 }
6165 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006166 case BO_Div:
6167 if (Result.isComplexFloat()) {
6168 ComplexValue LHS = Result;
6169 APFloat &LHS_r = LHS.getComplexFloatReal();
6170 APFloat &LHS_i = LHS.getComplexFloatImag();
6171 APFloat &RHS_r = RHS.getComplexFloatReal();
6172 APFloat &RHS_i = RHS.getComplexFloatImag();
6173 APFloat &Res_r = Result.getComplexFloatReal();
6174 APFloat &Res_i = Result.getComplexFloatImag();
6175
6176 APFloat Den = RHS_r;
6177 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6178 APFloat Tmp = RHS_i;
6179 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6180 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6181
6182 Res_r = LHS_r;
6183 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6184 Tmp = LHS_i;
6185 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6186 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6187 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6188
6189 Res_i = LHS_i;
6190 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6191 Tmp = LHS_r;
6192 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6193 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6194 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6195 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006196 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6197 return Error(E, diag::note_expr_divide_by_zero);
6198
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006199 ComplexValue LHS = Result;
6200 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6201 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6202 Result.getComplexIntReal() =
6203 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6204 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6205 Result.getComplexIntImag() =
6206 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6207 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6208 }
6209 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006210 }
6211
John McCall93d91dc2010-05-07 17:22:02 +00006212 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006213}
6214
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006215bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6216 // Get the operand value into 'Result'.
6217 if (!Visit(E->getSubExpr()))
6218 return false;
6219
6220 switch (E->getOpcode()) {
6221 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006222 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006223 case UO_Extension:
6224 return true;
6225 case UO_Plus:
6226 // The result is always just the subexpr.
6227 return true;
6228 case UO_Minus:
6229 if (Result.isComplexFloat()) {
6230 Result.getComplexFloatReal().changeSign();
6231 Result.getComplexFloatImag().changeSign();
6232 }
6233 else {
6234 Result.getComplexIntReal() = -Result.getComplexIntReal();
6235 Result.getComplexIntImag() = -Result.getComplexIntImag();
6236 }
6237 return true;
6238 case UO_Not:
6239 if (Result.isComplexFloat())
6240 Result.getComplexFloatImag().changeSign();
6241 else
6242 Result.getComplexIntImag() = -Result.getComplexIntImag();
6243 return true;
6244 }
6245}
6246
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006247bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6248 if (E->getNumInits() == 2) {
6249 if (E->getType()->isComplexType()) {
6250 Result.makeComplexFloat();
6251 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6252 return false;
6253 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6254 return false;
6255 } else {
6256 Result.makeComplexInt();
6257 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6258 return false;
6259 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6260 return false;
6261 }
6262 return true;
6263 }
6264 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6265}
6266
Anders Carlsson537969c2008-11-16 20:27:53 +00006267//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006268// Void expression evaluation, primarily for a cast to void on the LHS of a
6269// comma operator
6270//===----------------------------------------------------------------------===//
6271
6272namespace {
6273class VoidExprEvaluator
6274 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6275public:
6276 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6277
Richard Smith2e312c82012-03-03 22:46:17 +00006278 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006279
6280 bool VisitCastExpr(const CastExpr *E) {
6281 switch (E->getCastKind()) {
6282 default:
6283 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6284 case CK_ToVoid:
6285 VisitIgnoredValue(E->getSubExpr());
6286 return true;
6287 }
6288 }
6289};
6290} // end anonymous namespace
6291
6292static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6293 assert(E->isRValue() && E->getType()->isVoidType());
6294 return VoidExprEvaluator(Info).Visit(E);
6295}
6296
6297//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006298// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006299//===----------------------------------------------------------------------===//
6300
Richard Smith2e312c82012-03-03 22:46:17 +00006301static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006302 // In C, function designators are not lvalues, but we evaluate them as if they
6303 // are.
6304 if (E->isGLValue() || E->getType()->isFunctionType()) {
6305 LValue LV;
6306 if (!EvaluateLValue(E, LV, Info))
6307 return false;
6308 LV.moveInto(Result);
6309 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006310 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006311 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006312 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006313 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006314 return false;
John McCall45d55e42010-05-07 21:00:08 +00006315 } else if (E->getType()->hasPointerRepresentation()) {
6316 LValue LV;
6317 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006318 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006319 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006320 } else if (E->getType()->isRealFloatingType()) {
6321 llvm::APFloat F(0.0);
6322 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006323 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006324 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006325 } else if (E->getType()->isAnyComplexType()) {
6326 ComplexValue C;
6327 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006328 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006329 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006330 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006331 MemberPtr P;
6332 if (!EvaluateMemberPointer(E, P, Info))
6333 return false;
6334 P.moveInto(Result);
6335 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006336 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006337 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006338 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006339 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006340 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006341 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006342 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006343 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006344 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006345 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6346 return false;
6347 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006348 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006349 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006350 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006351 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006352 if (!EvaluateVoid(E, Info))
6353 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006354 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006355 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006356 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006357 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006358 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006359 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006360 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006361
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006362 return true;
6363}
6364
Richard Smithb228a862012-02-15 02:18:13 +00006365/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6366/// cases, the in-place evaluation is essential, since later initializers for
6367/// an object can indirectly refer to subobjects which were initialized earlier.
6368static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6369 const Expr *E, CheckConstantExpressionKind CCEK,
6370 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006371 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006372 return false;
6373
6374 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006375 // Evaluate arrays and record types in-place, so that later initializers can
6376 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006377 if (E->getType()->isArrayType())
6378 return EvaluateArray(E, This, Result, Info);
6379 else if (E->getType()->isRecordType())
6380 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006381 }
6382
6383 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006384 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006385}
6386
Richard Smithf57d8cb2011-12-09 22:58:01 +00006387/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6388/// lvalue-to-rvalue cast if it is an lvalue.
6389static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006390 if (!CheckLiteralType(Info, E))
6391 return false;
6392
Richard Smith2e312c82012-03-03 22:46:17 +00006393 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006394 return false;
6395
6396 if (E->isGLValue()) {
6397 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00006398 LV.setFrom(Info.Ctx, Result);
6399 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006400 return false;
6401 }
6402
Richard Smith2e312c82012-03-03 22:46:17 +00006403 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00006404 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006405}
Richard Smith11562c52011-10-28 17:51:58 +00006406
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006407static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6408 const ASTContext &Ctx, bool &IsConst) {
6409 // Fast-path evaluations of integer literals, since we sometimes see files
6410 // containing vast quantities of these.
6411 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6412 Result.Val = APValue(APSInt(L->getValue(),
6413 L->getType()->isUnsignedIntegerType()));
6414 IsConst = true;
6415 return true;
6416 }
6417
6418 // FIXME: Evaluating values of large array and record types can cause
6419 // performance problems. Only do so in C++11 for now.
6420 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6421 Exp->getType()->isRecordType()) &&
6422 !Ctx.getLangOpts().CPlusPlus11) {
6423 IsConst = false;
6424 return true;
6425 }
6426 return false;
6427}
6428
6429
Richard Smith7b553f12011-10-29 00:50:52 +00006430/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00006431/// any crazy technique (that has nothing to do with language standards) that
6432/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00006433/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6434/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00006435bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006436 bool IsConst;
6437 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
6438 return IsConst;
6439
Richard Smithf57d8cb2011-12-09 22:58:01 +00006440 EvalInfo Info(Ctx, Result);
6441 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00006442}
6443
Jay Foad39c79802011-01-12 09:06:06 +00006444bool Expr::EvaluateAsBooleanCondition(bool &Result,
6445 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00006446 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00006447 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00006448 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00006449}
6450
Richard Smith5fab0c92011-12-28 19:48:30 +00006451bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6452 SideEffectsKind AllowSideEffects) const {
6453 if (!getType()->isIntegralOrEnumerationType())
6454 return false;
6455
Richard Smith11562c52011-10-28 17:51:58 +00006456 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00006457 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6458 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00006459 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006460
Richard Smith11562c52011-10-28 17:51:58 +00006461 Result = ExprResult.Val.getInt();
6462 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00006463}
6464
Jay Foad39c79802011-01-12 09:06:06 +00006465bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00006466 EvalInfo Info(Ctx, Result);
6467
John McCall45d55e42010-05-07 21:00:08 +00006468 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006469 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6470 !CheckLValueConstantExpression(Info, getExprLoc(),
6471 Ctx.getLValueReferenceType(getType()), LV))
6472 return false;
6473
Richard Smith2e312c82012-03-03 22:46:17 +00006474 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00006475 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00006476}
6477
Richard Smithd0b4dd62011-12-19 06:19:21 +00006478bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6479 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006480 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00006481 // FIXME: Evaluating initializers for large array and record types can cause
6482 // performance problems. Only do so in C++11 for now.
6483 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006484 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00006485 return false;
6486
Richard Smithd0b4dd62011-12-19 06:19:21 +00006487 Expr::EvalStatus EStatus;
6488 EStatus.Diag = &Notes;
6489
6490 EvalInfo InitInfo(Ctx, EStatus);
6491 InitInfo.setEvaluatingDecl(VD, Value);
6492
6493 LValue LVal;
6494 LVal.set(VD);
6495
Richard Smithfddd3842011-12-30 21:15:51 +00006496 // C++11 [basic.start.init]p2:
6497 // Variables with static storage duration or thread storage duration shall be
6498 // zero-initialized before any other initialization takes place.
6499 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006500 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00006501 !VD->getType()->isReferenceType()) {
6502 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006503 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6504 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00006505 return false;
6506 }
6507
Richard Smithb228a862012-02-15 02:18:13 +00006508 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6509 /*AllowNonLiteralTypes=*/true) ||
6510 EStatus.HasSideEffects)
6511 return false;
6512
6513 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6514 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00006515}
6516
Richard Smith7b553f12011-10-29 00:50:52 +00006517/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6518/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00006519bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00006520 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00006521 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00006522}
Anders Carlsson59689ed2008-11-22 21:04:56 +00006523
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006524APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006525 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006526 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006527 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00006528 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006529 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00006530 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006531 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00006532
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006533 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00006534}
John McCall864e3962010-05-07 05:32:02 +00006535
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006536void Expr::EvaluateForOverflow(const ASTContext &Ctx,
6537 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
6538 bool IsConst;
6539 EvalResult EvalResult;
6540 EvalResult.Diag = Diags;
6541 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
6542 EvalInfo Info(Ctx, EvalResult, true);
6543 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
6544 }
6545}
6546
Abramo Bagnaraf8199452010-05-14 17:07:14 +00006547 bool Expr::EvalResult::isGlobalLValue() const {
6548 assert(Val.isLValue());
6549 return IsGlobalLValue(Val.getLValueBase());
6550 }
6551
6552
John McCall864e3962010-05-07 05:32:02 +00006553/// isIntegerConstantExpr - this recursive routine will test if an expression is
6554/// an integer constant expression.
6555
6556/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6557/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00006558
6559// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00006560// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6561// and a (possibly null) SourceLocation indicating the location of the problem.
6562//
John McCall864e3962010-05-07 05:32:02 +00006563// Note that to reduce code duplication, this helper does no evaluation
6564// itself; the caller checks whether the expression is evaluatable, and
6565// in the rare cases where CheckICE actually cares about the evaluated
6566// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00006567
Dan Gohman28ade552010-07-26 21:25:24 +00006568namespace {
6569
Richard Smith9e575da2012-12-28 13:25:52 +00006570enum ICEKind {
6571 /// This expression is an ICE.
6572 IK_ICE,
6573 /// This expression is not an ICE, but if it isn't evaluated, it's
6574 /// a legal subexpression for an ICE. This return value is used to handle
6575 /// the comma operator in C99 mode, and non-constant subexpressions.
6576 IK_ICEIfUnevaluated,
6577 /// This expression is not an ICE, and is not a legal subexpression for one.
6578 IK_NotICE
6579};
6580
John McCall864e3962010-05-07 05:32:02 +00006581struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00006582 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00006583 SourceLocation Loc;
6584
Richard Smith9e575da2012-12-28 13:25:52 +00006585 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00006586};
6587
Dan Gohman28ade552010-07-26 21:25:24 +00006588}
6589
Richard Smith9e575da2012-12-28 13:25:52 +00006590static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6591
6592static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00006593
6594static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6595 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00006596 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00006597 !EVResult.Val.isInt())
6598 return ICEDiag(IK_NotICE, E->getLocStart());
6599
John McCall864e3962010-05-07 05:32:02 +00006600 return NoDiag();
6601}
6602
6603static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6604 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00006605 if (!E->getType()->isIntegralOrEnumerationType())
6606 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006607
6608 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00006609#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00006610#define STMT(Node, Base) case Expr::Node##Class:
6611#define EXPR(Node, Base)
6612#include "clang/AST/StmtNodes.inc"
6613 case Expr::PredefinedExprClass:
6614 case Expr::FloatingLiteralClass:
6615 case Expr::ImaginaryLiteralClass:
6616 case Expr::StringLiteralClass:
6617 case Expr::ArraySubscriptExprClass:
6618 case Expr::MemberExprClass:
6619 case Expr::CompoundAssignOperatorClass:
6620 case Expr::CompoundLiteralExprClass:
6621 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00006622 case Expr::DesignatedInitExprClass:
6623 case Expr::ImplicitValueInitExprClass:
6624 case Expr::ParenListExprClass:
6625 case Expr::VAArgExprClass:
6626 case Expr::AddrLabelExprClass:
6627 case Expr::StmtExprClass:
6628 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00006629 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00006630 case Expr::CXXDynamicCastExprClass:
6631 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00006632 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00006633 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006634 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00006635 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006636 case Expr::CXXThisExprClass:
6637 case Expr::CXXThrowExprClass:
6638 case Expr::CXXNewExprClass:
6639 case Expr::CXXDeleteExprClass:
6640 case Expr::CXXPseudoDestructorExprClass:
6641 case Expr::UnresolvedLookupExprClass:
6642 case Expr::DependentScopeDeclRefExprClass:
6643 case Expr::CXXConstructExprClass:
6644 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00006645 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00006646 case Expr::CXXTemporaryObjectExprClass:
6647 case Expr::CXXUnresolvedConstructExprClass:
6648 case Expr::CXXDependentScopeMemberExprClass:
6649 case Expr::UnresolvedMemberExprClass:
6650 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00006651 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006652 case Expr::ObjCArrayLiteralClass:
6653 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006654 case Expr::ObjCEncodeExprClass:
6655 case Expr::ObjCMessageExprClass:
6656 case Expr::ObjCSelectorExprClass:
6657 case Expr::ObjCProtocolExprClass:
6658 case Expr::ObjCIvarRefExprClass:
6659 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006660 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006661 case Expr::ObjCIsaExprClass:
6662 case Expr::ShuffleVectorExprClass:
6663 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00006664 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00006665 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00006666 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00006667 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00006668 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00006669 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00006670 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00006671 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00006672 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00006673 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00006674 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00006675 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00006676 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00006677
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006678 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00006679 case Expr::GNUNullExprClass:
6680 // GCC considers the GNU __null value to be an integral constant expression.
6681 return NoDiag();
6682
John McCall7c454bb2011-07-15 05:09:51 +00006683 case Expr::SubstNonTypeTemplateParmExprClass:
6684 return
6685 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6686
John McCall864e3962010-05-07 05:32:02 +00006687 case Expr::ParenExprClass:
6688 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00006689 case Expr::GenericSelectionExprClass:
6690 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006691 case Expr::IntegerLiteralClass:
6692 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006693 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00006694 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00006695 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00006696 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00006697 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00006698 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00006699 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00006700 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006701 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00006702 return NoDiag();
6703 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00006704 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00006705 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6706 // constant expressions, but they can never be ICEs because an ICE cannot
6707 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00006708 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006709 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00006710 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006711 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006712 }
Richard Smith6365c912012-02-24 22:12:32 +00006713 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006714 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6715 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00006716 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006717 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00006718 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00006719 // Parameter variables are never constants. Without this check,
6720 // getAnyInitializer() can find a default argument, which leads
6721 // to chaos.
6722 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00006723 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00006724
6725 // C++ 7.1.5.1p2
6726 // A variable of non-volatile const-qualified integral or enumeration
6727 // type initialized by an ICE can be used in ICEs.
6728 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00006729 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00006730 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00006731
Richard Smithd0b4dd62011-12-19 06:19:21 +00006732 const VarDecl *VD;
6733 // Look for a declaration of this variable that has an initializer, and
6734 // check whether it is an ICE.
6735 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6736 return NoDiag();
6737 else
Richard Smith9e575da2012-12-28 13:25:52 +00006738 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00006739 }
6740 }
Richard Smith9e575da2012-12-28 13:25:52 +00006741 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00006742 }
John McCall864e3962010-05-07 05:32:02 +00006743 case Expr::UnaryOperatorClass: {
6744 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6745 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006746 case UO_PostInc:
6747 case UO_PostDec:
6748 case UO_PreInc:
6749 case UO_PreDec:
6750 case UO_AddrOf:
6751 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00006752 // C99 6.6/3 allows increment and decrement within unevaluated
6753 // subexpressions of constant expressions, but they can never be ICEs
6754 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00006755 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00006756 case UO_Extension:
6757 case UO_LNot:
6758 case UO_Plus:
6759 case UO_Minus:
6760 case UO_Not:
6761 case UO_Real:
6762 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00006763 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006764 }
Richard Smith9e575da2012-12-28 13:25:52 +00006765
John McCall864e3962010-05-07 05:32:02 +00006766 // OffsetOf falls through here.
6767 }
6768 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00006769 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6770 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6771 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6772 // compliance: we should warn earlier for offsetof expressions with
6773 // array subscripts that aren't ICEs, and if the array subscripts
6774 // are ICEs, the value of the offsetof must be an integer constant.
6775 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00006776 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00006777 case Expr::UnaryExprOrTypeTraitExprClass: {
6778 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6779 if ((Exp->getKind() == UETT_SizeOf) &&
6780 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00006781 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006782 return NoDiag();
6783 }
6784 case Expr::BinaryOperatorClass: {
6785 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6786 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006787 case BO_PtrMemD:
6788 case BO_PtrMemI:
6789 case BO_Assign:
6790 case BO_MulAssign:
6791 case BO_DivAssign:
6792 case BO_RemAssign:
6793 case BO_AddAssign:
6794 case BO_SubAssign:
6795 case BO_ShlAssign:
6796 case BO_ShrAssign:
6797 case BO_AndAssign:
6798 case BO_XorAssign:
6799 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00006800 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6801 // constant expressions, but they can never be ICEs because an ICE cannot
6802 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00006803 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006804
John McCalle3027922010-08-25 11:45:40 +00006805 case BO_Mul:
6806 case BO_Div:
6807 case BO_Rem:
6808 case BO_Add:
6809 case BO_Sub:
6810 case BO_Shl:
6811 case BO_Shr:
6812 case BO_LT:
6813 case BO_GT:
6814 case BO_LE:
6815 case BO_GE:
6816 case BO_EQ:
6817 case BO_NE:
6818 case BO_And:
6819 case BO_Xor:
6820 case BO_Or:
6821 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00006822 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6823 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00006824 if (Exp->getOpcode() == BO_Div ||
6825 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00006826 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00006827 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00006828 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00006829 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00006830 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00006831 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006832 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00006833 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00006834 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00006835 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006836 }
6837 }
6838 }
John McCalle3027922010-08-25 11:45:40 +00006839 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006840 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00006841 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6842 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00006843 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
6844 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006845 } else {
6846 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00006847 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006848 }
6849 }
Richard Smith9e575da2012-12-28 13:25:52 +00006850 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00006851 }
John McCalle3027922010-08-25 11:45:40 +00006852 case BO_LAnd:
6853 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00006854 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6855 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006856 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00006857 // Rare case where the RHS has a comma "side-effect"; we need
6858 // to actually check the condition to see whether the side
6859 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00006860 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00006861 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00006862 return RHSResult;
6863 return NoDiag();
6864 }
6865
Richard Smith9e575da2012-12-28 13:25:52 +00006866 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00006867 }
6868 }
6869 }
6870 case Expr::ImplicitCastExprClass:
6871 case Expr::CStyleCastExprClass:
6872 case Expr::CXXFunctionalCastExprClass:
6873 case Expr::CXXStaticCastExprClass:
6874 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00006875 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006876 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006877 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00006878 if (isa<ExplicitCastExpr>(E)) {
6879 if (const FloatingLiteral *FL
6880 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6881 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6882 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6883 APSInt IgnoredVal(DestWidth, !DestSigned);
6884 bool Ignored;
6885 // If the value does not fit in the destination type, the behavior is
6886 // undefined, so we are not required to treat it as a constant
6887 // expression.
6888 if (FL->getValue().convertToInteger(IgnoredVal,
6889 llvm::APFloat::rmTowardZero,
6890 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00006891 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00006892 return NoDiag();
6893 }
6894 }
Eli Friedman76d4e432011-09-29 21:49:34 +00006895 switch (cast<CastExpr>(E)->getCastKind()) {
6896 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006897 case CK_AtomicToNonAtomic:
6898 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00006899 case CK_NoOp:
6900 case CK_IntegralToBoolean:
6901 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00006902 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00006903 default:
Richard Smith9e575da2012-12-28 13:25:52 +00006904 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00006905 }
John McCall864e3962010-05-07 05:32:02 +00006906 }
John McCallc07a0c72011-02-17 10:25:35 +00006907 case Expr::BinaryConditionalOperatorClass: {
6908 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6909 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006910 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00006911 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006912 if (FalseResult.Kind == IK_NotICE) return FalseResult;
6913 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
6914 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00006915 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00006916 return FalseResult;
6917 }
John McCall864e3962010-05-07 05:32:02 +00006918 case Expr::ConditionalOperatorClass: {
6919 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6920 // If the condition (ignoring parens) is a __builtin_constant_p call,
6921 // then only the true side is actually considered in an integer constant
6922 // expression, and it is fully evaluated. This is an important GNU
6923 // extension. See GCC PR38377 for discussion.
6924 if (const CallExpr *CallCE
6925 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00006926 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6927 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00006928 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006929 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006930 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006931
Richard Smithf57d8cb2011-12-09 22:58:01 +00006932 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6933 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006934
Richard Smith9e575da2012-12-28 13:25:52 +00006935 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006936 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006937 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006938 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006939 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00006940 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006941 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00006942 return NoDiag();
6943 // Rare case where the diagnostics depend on which side is evaluated
6944 // Note that if we get here, CondResult is 0, and at least one of
6945 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00006946 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00006947 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00006948 return TrueResult;
6949 }
6950 case Expr::CXXDefaultArgExprClass:
6951 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00006952 case Expr::CXXDefaultInitExprClass:
6953 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006954 case Expr::ChooseExprClass: {
6955 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6956 }
6957 }
6958
David Blaikiee4d798f2012-01-20 21:50:17 +00006959 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00006960}
6961
Richard Smithf57d8cb2011-12-09 22:58:01 +00006962/// Evaluate an expression as a C++11 integral constant expression.
6963static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6964 const Expr *E,
6965 llvm::APSInt *Value,
6966 SourceLocation *Loc) {
6967 if (!E->getType()->isIntegralOrEnumerationType()) {
6968 if (Loc) *Loc = E->getExprLoc();
6969 return false;
6970 }
6971
Richard Smith66e05fe2012-01-18 05:21:49 +00006972 APValue Result;
6973 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00006974 return false;
6975
Richard Smith66e05fe2012-01-18 05:21:49 +00006976 assert(Result.isInt() && "pointer cast to int is not an ICE");
6977 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00006978 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006979}
6980
Richard Smith92b1ce02011-12-12 09:28:41 +00006981bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006982 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006983 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6984
Richard Smith9e575da2012-12-28 13:25:52 +00006985 ICEDiag D = CheckICE(this, Ctx);
6986 if (D.Kind != IK_ICE) {
6987 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00006988 return false;
6989 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006990 return true;
6991}
6992
6993bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6994 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006995 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006996 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6997
6998 if (!isIntegerConstantExpr(Ctx, Loc))
6999 return false;
7000 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007001 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007002 return true;
7003}
Richard Smith66e05fe2012-01-18 05:21:49 +00007004
Richard Smith98a0a492012-02-14 21:38:30 +00007005bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007006 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007007}
7008
Richard Smith66e05fe2012-01-18 05:21:49 +00007009bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7010 SourceLocation *Loc) const {
7011 // We support this checking in C++98 mode in order to diagnose compatibility
7012 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007013 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007014
Richard Smith98a0a492012-02-14 21:38:30 +00007015 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007016 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007017 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007018 Status.Diag = &Diags;
7019 EvalInfo Info(Ctx, Status);
7020
7021 APValue Scratch;
7022 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7023
7024 if (!Diags.empty()) {
7025 IsConstExpr = false;
7026 if (Loc) *Loc = Diags[0].first;
7027 } else if (!IsConstExpr) {
7028 // FIXME: This shouldn't happen.
7029 if (Loc) *Loc = getExprLoc();
7030 }
7031
7032 return IsConstExpr;
7033}
Richard Smith253c2a32012-01-27 01:14:48 +00007034
7035bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007036 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007037 PartialDiagnosticAt> &Diags) {
7038 // FIXME: It would be useful to check constexpr function templates, but at the
7039 // moment the constant expression evaluator cannot cope with the non-rigorous
7040 // ASTs which we build for dependent expressions.
7041 if (FD->isDependentContext())
7042 return true;
7043
7044 Expr::EvalStatus Status;
7045 Status.Diag = &Diags;
7046
7047 EvalInfo Info(FD->getASTContext(), Status);
7048 Info.CheckingPotentialConstantExpression = true;
7049
7050 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7051 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7052
7053 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7054 // is a temporary being used as the 'this' pointer.
7055 LValue This;
7056 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007057 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007058
Richard Smith253c2a32012-01-27 01:14:48 +00007059 ArrayRef<const Expr*> Args;
7060
7061 SourceLocation Loc = FD->getLocation();
7062
Richard Smith2e312c82012-03-03 22:46:17 +00007063 APValue Scratch;
7064 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00007065 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00007066 else
Richard Smith253c2a32012-01-27 01:14:48 +00007067 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7068 Args, FD->getBody(), Info, Scratch);
7069
7070 return Diags.empty();
7071}