blob: 8c650290b579429812f3a68cb08374fb29640f23 [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 Smith3da88fa2013-04-26 14:36:30 +0000289 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 Smith3da88fa2013-04-26 14:36:30 +0000300 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 Smith3da88fa2013-04-26 14:36:30 +0000600 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.
Richard Smith4e18ca52013-05-06 05:56:11 +0000918/// \return \c true if the caller should keep evaluating.
919static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000920 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000921 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000922 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000923 return Info.keepEvaluatingAfterFailure();
924 }
925 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000926}
927
Richard Smithd62306a2011-11-10 06:34:14 +0000928/// Should this call expression be treated as a string literal?
929static bool IsStringLiteralCall(const CallExpr *E) {
930 unsigned Builtin = E->isBuiltinCall();
931 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
932 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
933}
934
Richard Smithce40ad62011-11-12 22:28:03 +0000935static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000936 // C++11 [expr.const]p3 An address constant expression is a prvalue core
937 // constant expression of pointer type that evaluates to...
938
939 // ... a null pointer value, or a prvalue core constant expression of type
940 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000941 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000942
Richard Smithce40ad62011-11-12 22:28:03 +0000943 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
944 // ... the address of an object with static storage duration,
945 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
946 return VD->hasGlobalStorage();
947 // ... the address of a function,
948 return isa<FunctionDecl>(D);
949 }
950
951 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000952 switch (E->getStmtClass()) {
953 default:
954 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000955 case Expr::CompoundLiteralExprClass: {
956 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
957 return CLE->isFileScope() && CLE->isLValue();
958 }
Richard Smithd62306a2011-11-10 06:34:14 +0000959 // A string literal has static storage duration.
960 case Expr::StringLiteralClass:
961 case Expr::PredefinedExprClass:
962 case Expr::ObjCStringLiteralClass:
963 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000964 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000965 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000966 return true;
967 case Expr::CallExprClass:
968 return IsStringLiteralCall(cast<CallExpr>(E));
969 // For GCC compatibility, &&label has static storage duration.
970 case Expr::AddrLabelExprClass:
971 return true;
972 // A Block literal expression may be used as the initialization value for
973 // Block variables at global or local static scope.
974 case Expr::BlockExprClass:
975 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000976 case Expr::ImplicitValueInitExprClass:
977 // FIXME:
978 // We can never form an lvalue with an implicit value initialization as its
979 // base through expression evaluation, so these only appear in one case: the
980 // implicit variable declaration we invent when checking whether a constexpr
981 // constructor can produce a constant expression. We must assume that such
982 // an expression might be a global lvalue.
983 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000984 }
John McCall95007602010-05-10 23:27:23 +0000985}
986
Richard Smithb228a862012-02-15 02:18:13 +0000987static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
988 assert(Base && "no location for a null lvalue");
989 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
990 if (VD)
991 Info.Note(VD->getLocation(), diag::note_declared_at);
992 else
Ted Kremenek28831752012-08-23 20:46:57 +0000993 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000994 diag::note_constexpr_temporary_here);
995}
996
Richard Smith80815602011-11-07 05:07:52 +0000997/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000998/// value for an address or reference constant expression. Return true if we
999/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001000static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1001 QualType Type, const LValue &LVal) {
1002 bool IsReferenceType = Type->isReferenceType();
1003
Richard Smith357362d2011-12-13 06:39:58 +00001004 APValue::LValueBase Base = LVal.getLValueBase();
1005 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1006
Richard Smith0dea49e2012-02-18 04:58:18 +00001007 // Check that the object is a global. Note that the fake 'this' object we
1008 // manufacture when checking potential constant expressions is conservatively
1009 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001010 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001011 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001013 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1014 << IsReferenceType << !Designator.Entries.empty()
1015 << !!VD << VD;
1016 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001017 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001018 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001019 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001020 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001021 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001022 }
Richard Smithb228a862012-02-15 02:18:13 +00001023 assert((Info.CheckingPotentialConstantExpression ||
1024 LVal.getLValueCallIndex() == 0) &&
1025 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001026
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001027 // Check if this is a thread-local variable.
1028 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1029 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001030 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001031 return false;
1032 }
1033 }
1034
Richard Smitha8105bc2012-01-06 16:39:00 +00001035 // Allow address constant expressions to be past-the-end pointers. This is
1036 // an extension: the standard requires them to point to an object.
1037 if (!IsReferenceType)
1038 return true;
1039
1040 // A reference constant expression must refer to an object.
1041 if (!Base) {
1042 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001043 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001044 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001045 }
1046
Richard Smith357362d2011-12-13 06:39:58 +00001047 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001048 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001049 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001050 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001051 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001052 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001053 }
1054
Richard Smith80815602011-11-07 05:07:52 +00001055 return true;
1056}
1057
Richard Smithfddd3842011-12-30 21:15:51 +00001058/// Check that this core constant expression is of literal type, and if not,
1059/// produce an appropriate diagnostic.
1060static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001061 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001062 return true;
1063
1064 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001065 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001066 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001067 << E->getType();
1068 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001069 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001070 return false;
1071}
1072
Richard Smith0b0a0b62011-10-29 20:57:55 +00001073/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001074/// constant expression. If not, report an appropriate diagnostic. Does not
1075/// check that the expression is of literal type.
1076static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1077 QualType Type, const APValue &Value) {
1078 // Core issue 1454: For a literal constant expression of array or class type,
1079 // each subobject of its value shall have been initialized by a constant
1080 // expression.
1081 if (Value.isArray()) {
1082 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1083 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1084 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1085 Value.getArrayInitializedElt(I)))
1086 return false;
1087 }
1088 if (!Value.hasArrayFiller())
1089 return true;
1090 return CheckConstantExpression(Info, DiagLoc, EltTy,
1091 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001092 }
Richard Smithb228a862012-02-15 02:18:13 +00001093 if (Value.isUnion() && Value.getUnionField()) {
1094 return CheckConstantExpression(Info, DiagLoc,
1095 Value.getUnionField()->getType(),
1096 Value.getUnionValue());
1097 }
1098 if (Value.isStruct()) {
1099 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1100 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1101 unsigned BaseIndex = 0;
1102 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1103 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1104 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1105 Value.getStructBase(BaseIndex)))
1106 return false;
1107 }
1108 }
1109 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1110 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001111 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1112 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001113 return false;
1114 }
1115 }
1116
1117 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001118 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001119 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001120 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1121 }
1122
1123 // Everything else is fine.
1124 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001125}
1126
Richard Smith83c68212011-10-31 05:11:32 +00001127const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001128 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001129}
1130
1131static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001132 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001133}
1134
Richard Smithcecf1842011-11-01 21:06:14 +00001135static bool IsWeakLValue(const LValue &Value) {
1136 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001137 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001138}
1139
Richard Smith2e312c82012-03-03 22:46:17 +00001140static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001141 // A null base expression indicates a null pointer. These are always
1142 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001143 if (!Value.getLValueBase()) {
1144 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001145 return true;
1146 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001147
Richard Smith027bf112011-11-17 22:56:20 +00001148 // We have a non-null base. These are generally known to be true, but if it's
1149 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001150 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001151 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001152 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001153}
1154
Richard Smith2e312c82012-03-03 22:46:17 +00001155static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001156 switch (Val.getKind()) {
1157 case APValue::Uninitialized:
1158 return false;
1159 case APValue::Int:
1160 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001161 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001162 case APValue::Float:
1163 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001164 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001165 case APValue::ComplexInt:
1166 Result = Val.getComplexIntReal().getBoolValue() ||
1167 Val.getComplexIntImag().getBoolValue();
1168 return true;
1169 case APValue::ComplexFloat:
1170 Result = !Val.getComplexFloatReal().isZero() ||
1171 !Val.getComplexFloatImag().isZero();
1172 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001173 case APValue::LValue:
1174 return EvalPointerValueAsBool(Val, Result);
1175 case APValue::MemberPointer:
1176 Result = Val.getMemberPointerDecl();
1177 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001178 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001179 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001180 case APValue::Struct:
1181 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001182 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001183 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001184 }
1185
Richard Smith11562c52011-10-28 17:51:58 +00001186 llvm_unreachable("unknown APValue kind");
1187}
1188
1189static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1190 EvalInfo &Info) {
1191 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001192 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001193 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001194 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001195 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001196}
1197
Richard Smith357362d2011-12-13 06:39:58 +00001198template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001199static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001200 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001201 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001202 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001203}
1204
1205static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1206 QualType SrcType, const APFloat &Value,
1207 QualType DestType, APSInt &Result) {
1208 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001209 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001210 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001211
Richard Smith357362d2011-12-13 06:39:58 +00001212 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001213 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001214 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1215 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001216 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001217 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001218}
1219
Richard Smith357362d2011-12-13 06:39:58 +00001220static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1221 QualType SrcType, QualType DestType,
1222 APFloat &Result) {
1223 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001224 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001225 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1226 APFloat::rmNearestTiesToEven, &ignored)
1227 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001228 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001229 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001230}
1231
Richard Smith911e1422012-01-30 22:27:01 +00001232static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1233 QualType DestType, QualType SrcType,
1234 APSInt &Value) {
1235 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001236 APSInt Result = Value;
1237 // Figure out if this is a truncate, extend or noop cast.
1238 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001239 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001240 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001241 return Result;
1242}
1243
Richard Smith357362d2011-12-13 06:39:58 +00001244static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1245 QualType SrcType, const APSInt &Value,
1246 QualType DestType, APFloat &Result) {
1247 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1248 if (Result.convertFromAPInt(Value, Value.isSigned(),
1249 APFloat::rmNearestTiesToEven)
1250 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001251 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001252 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001253}
1254
Eli Friedman803acb32011-12-22 03:51:45 +00001255static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1256 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001257 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001258 if (!Evaluate(SVal, Info, E))
1259 return false;
1260 if (SVal.isInt()) {
1261 Res = SVal.getInt();
1262 return true;
1263 }
1264 if (SVal.isFloat()) {
1265 Res = SVal.getFloat().bitcastToAPInt();
1266 return true;
1267 }
1268 if (SVal.isVector()) {
1269 QualType VecTy = E->getType();
1270 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1271 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1272 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1273 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1274 Res = llvm::APInt::getNullValue(VecSize);
1275 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1276 APValue &Elt = SVal.getVectorElt(i);
1277 llvm::APInt EltAsInt;
1278 if (Elt.isInt()) {
1279 EltAsInt = Elt.getInt();
1280 } else if (Elt.isFloat()) {
1281 EltAsInt = Elt.getFloat().bitcastToAPInt();
1282 } else {
1283 // Don't try to handle vectors of anything other than int or float
1284 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001285 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001286 return false;
1287 }
1288 unsigned BaseEltSize = EltAsInt.getBitWidth();
1289 if (BigEndian)
1290 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1291 else
1292 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1293 }
1294 return true;
1295 }
1296 // Give up if the input isn't an int, float, or vector. For example, we
1297 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001298 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001299 return false;
1300}
1301
Richard Smitha8105bc2012-01-06 16:39:00 +00001302/// Cast an lvalue referring to a base subobject to a derived class, by
1303/// truncating the lvalue's path to the given length.
1304static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1305 const RecordDecl *TruncatedType,
1306 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001307 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001308
1309 // Check we actually point to a derived class object.
1310 if (TruncatedElements == D.Entries.size())
1311 return true;
1312 assert(TruncatedElements >= D.MostDerivedPathLength &&
1313 "not casting to a derived class");
1314 if (!Result.checkSubobject(Info, E, CSK_Derived))
1315 return false;
1316
1317 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001318 const RecordDecl *RD = TruncatedType;
1319 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001320 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001321 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1322 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001323 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001324 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001325 else
Richard Smithd62306a2011-11-10 06:34:14 +00001326 Result.Offset -= Layout.getBaseClassOffset(Base);
1327 RD = Base;
1328 }
Richard Smith027bf112011-11-17 22:56:20 +00001329 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001330 return true;
1331}
1332
John McCalld7bca762012-05-01 00:38:49 +00001333static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001334 const CXXRecordDecl *Derived,
1335 const CXXRecordDecl *Base,
1336 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001337 if (!RL) {
1338 if (Derived->isInvalidDecl()) return false;
1339 RL = &Info.Ctx.getASTRecordLayout(Derived);
1340 }
1341
Richard Smithd62306a2011-11-10 06:34:14 +00001342 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001343 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001344 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001345}
1346
Richard Smitha8105bc2012-01-06 16:39:00 +00001347static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001348 const CXXRecordDecl *DerivedDecl,
1349 const CXXBaseSpecifier *Base) {
1350 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1351
John McCalld7bca762012-05-01 00:38:49 +00001352 if (!Base->isVirtual())
1353 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001354
Richard Smitha8105bc2012-01-06 16:39:00 +00001355 SubobjectDesignator &D = Obj.Designator;
1356 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001357 return false;
1358
Richard Smitha8105bc2012-01-06 16:39:00 +00001359 // Extract most-derived object and corresponding type.
1360 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1361 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1362 return false;
1363
1364 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001365 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001366 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1367 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001368 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001369 return true;
1370}
1371
1372/// Update LVal to refer to the given field, which must be a member of the type
1373/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001374static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001375 const FieldDecl *FD,
1376 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001377 if (!RL) {
1378 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001379 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001380 }
Richard Smithd62306a2011-11-10 06:34:14 +00001381
1382 unsigned I = FD->getFieldIndex();
1383 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001384 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001385 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001386}
1387
Richard Smith1b78b3d2012-01-25 22:15:11 +00001388/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001389static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001390 LValue &LVal,
1391 const IndirectFieldDecl *IFD) {
1392 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1393 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001394 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1395 return false;
1396 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001397}
1398
Richard Smithd62306a2011-11-10 06:34:14 +00001399/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001400static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1401 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001402 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1403 // extension.
1404 if (Type->isVoidType() || Type->isFunctionType()) {
1405 Size = CharUnits::One();
1406 return true;
1407 }
1408
1409 if (!Type->isConstantSizeType()) {
1410 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001411 // FIXME: Better diagnostic.
1412 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001413 return false;
1414 }
1415
1416 Size = Info.Ctx.getTypeSizeInChars(Type);
1417 return true;
1418}
1419
1420/// Update a pointer value to model pointer arithmetic.
1421/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001422/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001423/// \param LVal - The pointer value to be updated.
1424/// \param EltTy - The pointee type represented by LVal.
1425/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001426static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1427 LValue &LVal, QualType EltTy,
1428 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001429 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001430 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001431 return false;
1432
1433 // Compute the new offset in the appropriate width.
1434 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001435 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001436 return true;
1437}
1438
Richard Smith66c96992012-02-18 22:04:06 +00001439/// Update an lvalue to refer to a component of a complex number.
1440/// \param Info - Information about the ongoing evaluation.
1441/// \param LVal - The lvalue to be updated.
1442/// \param EltTy - The complex number's component type.
1443/// \param Imag - False for the real component, true for the imaginary.
1444static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1445 LValue &LVal, QualType EltTy,
1446 bool Imag) {
1447 if (Imag) {
1448 CharUnits SizeOfComponent;
1449 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1450 return false;
1451 LVal.Offset += SizeOfComponent;
1452 }
1453 LVal.addComplex(Info, E, EltTy, Imag);
1454 return true;
1455}
1456
Richard Smith27908702011-10-24 17:54:18 +00001457/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001458///
1459/// \param Info Information about the ongoing evaluation.
1460/// \param E An expression to be used when printing diagnostics.
1461/// \param VD The variable whose initializer should be obtained.
1462/// \param Frame The frame in which the variable was created. Must be null
1463/// if this variable is not local to the evaluation.
1464/// \param Result Filled in with a pointer to the value of the variable.
1465static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1466 const VarDecl *VD, CallStackFrame *Frame,
1467 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001468 // If this is a parameter to an active constexpr function call, perform
1469 // argument substitution.
1470 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001471 // Assume arguments of a potential constant expression are unknown
1472 // constant expressions.
1473 if (Info.CheckingPotentialConstantExpression)
1474 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001475 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001476 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001477 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001478 }
Richard Smith3229b742013-05-05 21:17:10 +00001479 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001480 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001481 }
Richard Smith27908702011-10-24 17:54:18 +00001482
Richard Smithd9f663b2013-04-22 15:31:51 +00001483 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001484 if (Frame) {
1485 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001486 // If we've carried on past an unevaluatable local variable initializer,
1487 // we can't go any further. This can happen during potential constant
1488 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001489 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001490 }
1491
Richard Smithd0b4dd62011-12-19 06:19:21 +00001492 // Dig out the initializer, and use the declaration which it's attached to.
1493 const Expr *Init = VD->getAnyInitializer(VD);
1494 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001495 // If we're checking a potential constant expression, the variable could be
1496 // initialized later.
1497 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001498 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001499 return false;
1500 }
1501
Richard Smithd62306a2011-11-10 06:34:14 +00001502 // If we're currently evaluating the initializer of this declaration, use that
1503 // in-flight value.
1504 if (Info.EvaluatingDecl == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001505 Result = Info.EvaluatingDeclValue;
1506 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001507 }
1508
Richard Smithcecf1842011-11-01 21:06:14 +00001509 // Never evaluate the initializer of a weak variable. We can't be sure that
1510 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001511 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001512 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001513 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001514 }
Richard Smithcecf1842011-11-01 21:06:14 +00001515
Richard Smithd0b4dd62011-12-19 06:19:21 +00001516 // Check that we can fold the initializer. In C++, we will have already done
1517 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001518 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001519 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001520 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001521 Notes.size() + 1) << VD;
1522 Info.Note(VD->getLocation(), diag::note_declared_at);
1523 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001524 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001525 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001526 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001527 Notes.size() + 1) << VD;
1528 Info.Note(VD->getLocation(), diag::note_declared_at);
1529 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001530 }
Richard Smith27908702011-10-24 17:54:18 +00001531
Richard Smith3229b742013-05-05 21:17:10 +00001532 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001533 return true;
Richard Smith27908702011-10-24 17:54:18 +00001534}
1535
Richard Smith11562c52011-10-28 17:51:58 +00001536static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001537 Qualifiers Quals = T.getQualifiers();
1538 return Quals.hasConst() && !Quals.hasVolatile();
1539}
1540
Richard Smithe97cbd72011-11-11 04:05:33 +00001541/// Get the base index of the given base class within an APValue representing
1542/// the given derived class.
1543static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1544 const CXXRecordDecl *Base) {
1545 Base = Base->getCanonicalDecl();
1546 unsigned Index = 0;
1547 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1548 E = Derived->bases_end(); I != E; ++I, ++Index) {
1549 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1550 return Index;
1551 }
1552
1553 llvm_unreachable("base class missing from derived class's bases list");
1554}
1555
Richard Smith3da88fa2013-04-26 14:36:30 +00001556/// Extract the value of a character from a string literal.
1557static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1558 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001559 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001560 const StringLiteral *S = cast<StringLiteral>(Lit);
1561 const ConstantArrayType *CAT =
1562 Info.Ctx.getAsConstantArrayType(S->getType());
1563 assert(CAT && "string literal isn't an array");
1564 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001565 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001566
1567 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001568 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001569 if (Index < S->getLength())
1570 Value = S->getCodeUnit(Index);
1571 return Value;
1572}
1573
Richard Smith3da88fa2013-04-26 14:36:30 +00001574// Expand a string literal into an array of characters.
1575static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1576 APValue &Result) {
1577 const StringLiteral *S = cast<StringLiteral>(Lit);
1578 const ConstantArrayType *CAT =
1579 Info.Ctx.getAsConstantArrayType(S->getType());
1580 assert(CAT && "string literal isn't an array");
1581 QualType CharType = CAT->getElementType();
1582 assert(CharType->isIntegerType() && "unexpected character type");
1583
1584 unsigned Elts = CAT->getSize().getZExtValue();
1585 Result = APValue(APValue::UninitArray(),
1586 std::min(S->getLength(), Elts), Elts);
1587 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1588 CharType->isUnsignedIntegerType());
1589 if (Result.hasArrayFiller())
1590 Result.getArrayFiller() = APValue(Value);
1591 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1592 Value = S->getCodeUnit(I);
1593 Result.getArrayInitializedElt(I) = APValue(Value);
1594 }
1595}
1596
1597// Expand an array so that it has more than Index filled elements.
1598static void expandArray(APValue &Array, unsigned Index) {
1599 unsigned Size = Array.getArraySize();
1600 assert(Index < Size);
1601
1602 // Always at least double the number of elements for which we store a value.
1603 unsigned OldElts = Array.getArrayInitializedElts();
1604 unsigned NewElts = std::max(Index+1, OldElts * 2);
1605 NewElts = std::min(Size, std::max(NewElts, 8u));
1606
1607 // Copy the data across.
1608 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1609 for (unsigned I = 0; I != OldElts; ++I)
1610 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1611 for (unsigned I = OldElts; I != NewElts; ++I)
1612 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1613 if (NewValue.hasArrayFiller())
1614 NewValue.getArrayFiller() = Array.getArrayFiller();
1615 Array.swap(NewValue);
1616}
1617
1618/// Kinds of access we can perform on an object.
1619enum AccessKinds {
1620 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001621 AK_Assign,
1622 AK_Increment,
1623 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001624};
1625
Richard Smith3229b742013-05-05 21:17:10 +00001626/// A handle to a complete object (an object that is not a subobject of
1627/// another object).
1628struct CompleteObject {
1629 /// The value of the complete object.
1630 APValue *Value;
1631 /// The type of the complete object.
1632 QualType Type;
1633
1634 CompleteObject() : Value(0) {}
1635 CompleteObject(APValue *Value, QualType Type)
1636 : Value(Value), Type(Type) {
1637 assert(Value && "missing value for complete object");
1638 }
1639
1640 operator bool() const { return Value; }
1641};
1642
Richard Smith3da88fa2013-04-26 14:36:30 +00001643/// Find the designated sub-object of an rvalue.
1644template<typename SubobjectHandler>
1645typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001646findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001647 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001648 if (Sub.Invalid)
1649 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001650 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001651 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001652 if (Info.getLangOpts().CPlusPlus11)
1653 Info.Diag(E, diag::note_constexpr_access_past_end)
1654 << handler.AccessKind;
1655 else
1656 Info.Diag(E);
1657 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001658 }
Richard Smith6804be52011-11-11 08:28:03 +00001659 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001660 return handler.found(*Obj.Value, Obj.Type);
1661 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001662 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001663 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001664
Richard Smith3229b742013-05-05 21:17:10 +00001665 APValue *O = Obj.Value;
1666 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001667 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001668 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001669 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001670 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001671 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001672 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001673 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001674 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001675 // Note, it should not be possible to form a pointer with a valid
1676 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001677 if (Info.getLangOpts().CPlusPlus11)
1678 Info.Diag(E, diag::note_constexpr_access_past_end)
1679 << handler.AccessKind;
1680 else
1681 Info.Diag(E);
1682 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001683 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001684
1685 ObjType = CAT->getElementType();
1686
Richard Smith14a94132012-02-17 03:35:37 +00001687 // An array object is represented as either an Array APValue or as an
1688 // LValue which refers to a string literal.
1689 if (O->isLValue()) {
1690 assert(I == N - 1 && "extracting subobject of character?");
1691 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001692 if (handler.AccessKind != AK_Read)
1693 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1694 *O);
1695 else
1696 return handler.foundString(*O, ObjType, Index);
1697 }
1698
1699 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001700 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001701 else if (handler.AccessKind != AK_Read) {
1702 expandArray(*O, Index);
1703 O = &O->getArrayInitializedElt(Index);
1704 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001705 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001706 } else if (ObjType->isAnyComplexType()) {
1707 // Next subobject is a complex number.
1708 uint64_t Index = Sub.Entries[I].ArrayIndex;
1709 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001710 if (Info.getLangOpts().CPlusPlus11)
1711 Info.Diag(E, diag::note_constexpr_access_past_end)
1712 << handler.AccessKind;
1713 else
1714 Info.Diag(E);
1715 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001716 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001717
1718 bool WasConstQualified = ObjType.isConstQualified();
1719 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1720 if (WasConstQualified)
1721 ObjType.addConst();
1722
Richard Smith66c96992012-02-18 22:04:06 +00001723 assert(I == N - 1 && "extracting subobject of scalar?");
1724 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001725 return handler.found(Index ? O->getComplexIntImag()
1726 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001727 } else {
1728 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001729 return handler.found(Index ? O->getComplexFloatImag()
1730 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001731 }
Richard Smithd62306a2011-11-10 06:34:14 +00001732 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001733 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001734 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001735 << Field;
1736 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001737 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001738 }
1739
Richard Smithd62306a2011-11-10 06:34:14 +00001740 // Next subobject is a class, struct or union field.
1741 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1742 if (RD->isUnion()) {
1743 const FieldDecl *UnionField = O->getUnionField();
1744 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001746 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1747 << handler.AccessKind << Field << !UnionField << UnionField;
1748 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001749 }
Richard Smithd62306a2011-11-10 06:34:14 +00001750 O = &O->getUnionValue();
1751 } else
1752 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001753
1754 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001755 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001756 if (WasConstQualified && !Field->isMutable())
1757 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001758
1759 if (ObjType.isVolatileQualified()) {
1760 if (Info.getLangOpts().CPlusPlus) {
1761 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001762 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1763 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001764 Info.Note(Field->getLocation(), diag::note_declared_at);
1765 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001766 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001767 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001768 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001769 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001770 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001771 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001772 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1773 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1774 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001775
1776 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001777 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001778 if (WasConstQualified)
1779 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001780 }
Richard Smithd62306a2011-11-10 06:34:14 +00001781
Richard Smithf57d8cb2011-12-09 22:58:01 +00001782 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001783 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001784 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1785 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001786 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001787 }
1788
Richard Smith3da88fa2013-04-26 14:36:30 +00001789 return handler.found(*O, ObjType);
1790}
1791
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001792namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001793struct ExtractSubobjectHandler {
1794 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001795 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001796
1797 static const AccessKinds AccessKind = AK_Read;
1798
1799 typedef bool result_type;
1800 bool failed() { return false; }
1801 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001802 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001803 return true;
1804 }
1805 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001806 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001807 return true;
1808 }
1809 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001810 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001811 return true;
1812 }
1813 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001814 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001815 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1816 return true;
1817 }
1818};
Richard Smith3229b742013-05-05 21:17:10 +00001819} // end anonymous namespace
1820
Richard Smith3da88fa2013-04-26 14:36:30 +00001821const AccessKinds ExtractSubobjectHandler::AccessKind;
1822
1823/// Extract the designated sub-object of an rvalue.
1824static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001825 const CompleteObject &Obj,
1826 const SubobjectDesignator &Sub,
1827 APValue &Result) {
1828 ExtractSubobjectHandler Handler = { Info, Result };
1829 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00001830}
1831
Richard Smith3229b742013-05-05 21:17:10 +00001832namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001833struct ModifySubobjectHandler {
1834 EvalInfo &Info;
1835 APValue &NewVal;
1836 const Expr *E;
1837
1838 typedef bool result_type;
1839 static const AccessKinds AccessKind = AK_Assign;
1840
1841 bool checkConst(QualType QT) {
1842 // Assigning to a const object has undefined behavior.
1843 if (QT.isConstQualified()) {
1844 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
1845 return false;
1846 }
1847 return true;
1848 }
1849
1850 bool failed() { return false; }
1851 bool found(APValue &Subobj, QualType SubobjType) {
1852 if (!checkConst(SubobjType))
1853 return false;
1854 // We've been given ownership of NewVal, so just swap it in.
1855 Subobj.swap(NewVal);
1856 return true;
1857 }
1858 bool found(APSInt &Value, QualType SubobjType) {
1859 if (!checkConst(SubobjType))
1860 return false;
1861 if (!NewVal.isInt()) {
1862 // Maybe trying to write a cast pointer value into a complex?
1863 Info.Diag(E);
1864 return false;
1865 }
1866 Value = NewVal.getInt();
1867 return true;
1868 }
1869 bool found(APFloat &Value, QualType SubobjType) {
1870 if (!checkConst(SubobjType))
1871 return false;
1872 Value = NewVal.getFloat();
1873 return true;
1874 }
1875 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1876 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
1877 }
1878};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001879} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00001880
Richard Smith3229b742013-05-05 21:17:10 +00001881const AccessKinds ModifySubobjectHandler::AccessKind;
1882
Richard Smith3da88fa2013-04-26 14:36:30 +00001883/// Update the designated sub-object of an rvalue to the given value.
1884static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001885 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001886 const SubobjectDesignator &Sub,
1887 APValue &NewVal) {
1888 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00001889 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00001890}
1891
Richard Smith84f6dcf2012-02-02 01:16:57 +00001892/// Find the position where two subobject designators diverge, or equivalently
1893/// the length of the common initial subsequence.
1894static unsigned FindDesignatorMismatch(QualType ObjType,
1895 const SubobjectDesignator &A,
1896 const SubobjectDesignator &B,
1897 bool &WasArrayIndex) {
1898 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1899 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001900 if (!ObjType.isNull() &&
1901 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001902 // Next subobject is an array element.
1903 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1904 WasArrayIndex = true;
1905 return I;
1906 }
Richard Smith66c96992012-02-18 22:04:06 +00001907 if (ObjType->isAnyComplexType())
1908 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1909 else
1910 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001911 } else {
1912 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1913 WasArrayIndex = false;
1914 return I;
1915 }
1916 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1917 // Next subobject is a field.
1918 ObjType = FD->getType();
1919 else
1920 // Next subobject is a base class.
1921 ObjType = QualType();
1922 }
1923 }
1924 WasArrayIndex = false;
1925 return I;
1926}
1927
1928/// Determine whether the given subobject designators refer to elements of the
1929/// same array object.
1930static bool AreElementsOfSameArray(QualType ObjType,
1931 const SubobjectDesignator &A,
1932 const SubobjectDesignator &B) {
1933 if (A.Entries.size() != B.Entries.size())
1934 return false;
1935
1936 bool IsArray = A.MostDerivedArraySize != 0;
1937 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1938 // A is a subobject of the array element.
1939 return false;
1940
1941 // If A (and B) designates an array element, the last entry will be the array
1942 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1943 // of length 1' case, and the entire path must match.
1944 bool WasArrayIndex;
1945 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1946 return CommonLength >= A.Entries.size() - IsArray;
1947}
1948
Richard Smith3229b742013-05-05 21:17:10 +00001949/// Find the complete object to which an LValue refers.
1950CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
1951 const LValue &LVal, QualType LValType) {
1952 if (!LVal.Base) {
1953 Info.Diag(E, diag::note_constexpr_access_null) << AK;
1954 return CompleteObject();
1955 }
1956
1957 CallStackFrame *Frame = 0;
1958 if (LVal.CallIndex) {
1959 Frame = Info.getCallFrame(LVal.CallIndex);
1960 if (!Frame) {
1961 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
1962 << AK << LVal.Base.is<const ValueDecl*>();
1963 NoteLValueLocation(Info, LVal.Base);
1964 return CompleteObject();
1965 }
1966 } else if (AK != AK_Read) {
1967 Info.Diag(E, diag::note_constexpr_modify_global);
1968 return CompleteObject();
1969 }
1970
1971 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1972 // is not a constant expression (even if the object is non-volatile). We also
1973 // apply this rule to C++98, in order to conform to the expected 'volatile'
1974 // semantics.
1975 if (LValType.isVolatileQualified()) {
1976 if (Info.getLangOpts().CPlusPlus)
1977 Info.Diag(E, diag::note_constexpr_access_volatile_type)
1978 << AK << LValType;
1979 else
1980 Info.Diag(E);
1981 return CompleteObject();
1982 }
1983
1984 // Compute value storage location and type of base object.
1985 APValue *BaseVal = 0;
1986 QualType BaseType;
1987
1988 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1989 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1990 // In C++11, constexpr, non-volatile variables initialized with constant
1991 // expressions are constant expressions too. Inside constexpr functions,
1992 // parameters are constant expressions even if they're non-const.
1993 // In C++1y, objects local to a constant expression (those with a Frame) are
1994 // both readable and writable inside constant expressions.
1995 // In C, such things can also be folded, although they are not ICEs.
1996 const VarDecl *VD = dyn_cast<VarDecl>(D);
1997 if (VD) {
1998 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1999 VD = VDef;
2000 }
2001 if (!VD || VD->isInvalidDecl()) {
2002 Info.Diag(E);
2003 return CompleteObject();
2004 }
2005
2006 // Accesses of volatile-qualified objects are not allowed.
2007 BaseType = VD->getType();
2008 if (BaseType.isVolatileQualified()) {
2009 if (Info.getLangOpts().CPlusPlus) {
2010 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2011 << AK << 1 << VD;
2012 Info.Note(VD->getLocation(), diag::note_declared_at);
2013 } else {
2014 Info.Diag(E);
2015 }
2016 return CompleteObject();
2017 }
2018
2019 // Unless we're looking at a local variable or argument in a constexpr call,
2020 // the variable we're reading must be const.
2021 if (!Frame) {
2022 assert(AK == AK_Read && "can't modify non-local");
2023 if (VD->isConstexpr()) {
2024 // OK, we can read this variable.
2025 } else if (BaseType->isIntegralOrEnumerationType()) {
2026 if (!BaseType.isConstQualified()) {
2027 if (Info.getLangOpts().CPlusPlus) {
2028 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2029 Info.Note(VD->getLocation(), diag::note_declared_at);
2030 } else {
2031 Info.Diag(E);
2032 }
2033 return CompleteObject();
2034 }
2035 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2036 // We support folding of const floating-point types, in order to make
2037 // static const data members of such types (supported as an extension)
2038 // more useful.
2039 if (Info.getLangOpts().CPlusPlus11) {
2040 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2041 Info.Note(VD->getLocation(), diag::note_declared_at);
2042 } else {
2043 Info.CCEDiag(E);
2044 }
2045 } else {
2046 // FIXME: Allow folding of values of any literal type in all languages.
2047 if (Info.getLangOpts().CPlusPlus11) {
2048 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2049 Info.Note(VD->getLocation(), diag::note_declared_at);
2050 } else {
2051 Info.Diag(E);
2052 }
2053 return CompleteObject();
2054 }
2055 }
2056
2057 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2058 return CompleteObject();
2059 } else {
2060 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2061
2062 if (!Frame) {
2063 Info.Diag(E);
2064 return CompleteObject();
2065 }
2066
2067 BaseType = Base->getType();
2068 BaseVal = &Frame->Temporaries[Base];
2069
2070 // Volatile temporary objects cannot be accessed in constant expressions.
2071 if (BaseType.isVolatileQualified()) {
2072 if (Info.getLangOpts().CPlusPlus) {
2073 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2074 << AK << 0;
2075 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2076 } else {
2077 Info.Diag(E);
2078 }
2079 return CompleteObject();
2080 }
2081 }
2082
2083 // In C++1y, we can't safely access any mutable state when checking a
2084 // potential constant expression.
2085 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2086 Info.CheckingPotentialConstantExpression)
2087 return CompleteObject();
2088
2089 return CompleteObject(BaseVal, BaseType);
2090}
2091
Richard Smith243ef902013-05-05 23:31:59 +00002092/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2093/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2094/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002095///
2096/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002097/// \param Conv - The expression for which we are performing the conversion.
2098/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002099/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2100/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002101/// \param LVal - The glvalue on which we are attempting to perform this action.
2102/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002103static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002104 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002105 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002106 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002107 return false;
2108
Richard Smith3229b742013-05-05 21:17:10 +00002109 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002110 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002111 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2112 !Type.isVolatileQualified()) {
2113 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2114 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2115 // initializer until now for such expressions. Such an expression can't be
2116 // an ICE in C, so this only matters for fold.
2117 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2118 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002119 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002120 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002121 }
Richard Smith3229b742013-05-05 21:17:10 +00002122 APValue Lit;
2123 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2124 return false;
2125 CompleteObject LitObj(&Lit, Base->getType());
2126 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2127 } else if (isa<StringLiteral>(Base)) {
2128 // We represent a string literal array as an lvalue pointing at the
2129 // corresponding expression, rather than building an array of chars.
2130 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2131 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2132 CompleteObject StrObj(&Str, Base->getType());
2133 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002134 }
Richard Smith11562c52011-10-28 17:51:58 +00002135 }
2136
Richard Smith3229b742013-05-05 21:17:10 +00002137 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2138 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002139}
2140
2141/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002142static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002143 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002144 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002145 return false;
2146
Richard Smith3229b742013-05-05 21:17:10 +00002147 if (!Info.getLangOpts().CPlusPlus1y) {
2148 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002149 return false;
2150 }
2151
Richard Smith3229b742013-05-05 21:17:10 +00002152 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2153 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002154}
2155
Richard Smith243ef902013-05-05 23:31:59 +00002156static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2157 return T->isSignedIntegerType() &&
2158 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2159}
2160
2161namespace {
2162struct IncDecSubobjectHandler {
2163 EvalInfo &Info;
2164 const Expr *E;
2165 AccessKinds AccessKind;
2166 APValue *Old;
2167
2168 typedef bool result_type;
2169
2170 bool checkConst(QualType QT) {
2171 // Assigning to a const object has undefined behavior.
2172 if (QT.isConstQualified()) {
2173 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2174 return false;
2175 }
2176 return true;
2177 }
2178
2179 bool failed() { return false; }
2180 bool found(APValue &Subobj, QualType SubobjType) {
2181 // Stash the old value. Also clear Old, so we don't clobber it later
2182 // if we're post-incrementing a complex.
2183 if (Old) {
2184 *Old = Subobj;
2185 Old = 0;
2186 }
2187
2188 switch (Subobj.getKind()) {
2189 case APValue::Int:
2190 return found(Subobj.getInt(), SubobjType);
2191 case APValue::Float:
2192 return found(Subobj.getFloat(), SubobjType);
2193 case APValue::ComplexInt:
2194 return found(Subobj.getComplexIntReal(),
2195 SubobjType->castAs<ComplexType>()->getElementType()
2196 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2197 case APValue::ComplexFloat:
2198 return found(Subobj.getComplexFloatReal(),
2199 SubobjType->castAs<ComplexType>()->getElementType()
2200 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2201 case APValue::LValue:
2202 return foundPointer(Subobj, SubobjType);
2203 default:
2204 // FIXME: can this happen?
2205 Info.Diag(E);
2206 return false;
2207 }
2208 }
2209 bool found(APSInt &Value, QualType SubobjType) {
2210 if (!checkConst(SubobjType))
2211 return false;
2212
2213 if (!SubobjType->isIntegerType()) {
2214 // We don't support increment / decrement on integer-cast-to-pointer
2215 // values.
2216 Info.Diag(E);
2217 return false;
2218 }
2219
2220 if (Old) *Old = APValue(Value);
2221
2222 // bool arithmetic promotes to int, and the conversion back to bool
2223 // doesn't reduce mod 2^n, so special-case it.
2224 if (SubobjType->isBooleanType()) {
2225 if (AccessKind == AK_Increment)
2226 Value = 1;
2227 else
2228 Value = !Value;
2229 return true;
2230 }
2231
2232 bool WasNegative = Value.isNegative();
2233 if (AccessKind == AK_Increment) {
2234 ++Value;
2235
2236 if (!WasNegative && Value.isNegative() &&
2237 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2238 APSInt ActualValue(Value, /*IsUnsigned*/true);
2239 HandleOverflow(Info, E, ActualValue, SubobjType);
2240 }
2241 } else {
2242 --Value;
2243
2244 if (WasNegative && !Value.isNegative() &&
2245 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2246 unsigned BitWidth = Value.getBitWidth();
2247 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2248 ActualValue.setBit(BitWidth);
2249 HandleOverflow(Info, E, ActualValue, SubobjType);
2250 }
2251 }
2252 return true;
2253 }
2254 bool found(APFloat &Value, QualType SubobjType) {
2255 if (!checkConst(SubobjType))
2256 return false;
2257
2258 if (Old) *Old = APValue(Value);
2259
2260 APFloat One(Value.getSemantics(), 1);
2261 if (AccessKind == AK_Increment)
2262 Value.add(One, APFloat::rmNearestTiesToEven);
2263 else
2264 Value.subtract(One, APFloat::rmNearestTiesToEven);
2265 return true;
2266 }
2267 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2268 if (!checkConst(SubobjType))
2269 return false;
2270
2271 QualType PointeeType;
2272 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2273 PointeeType = PT->getPointeeType();
2274 else {
2275 Info.Diag(E);
2276 return false;
2277 }
2278
2279 LValue LVal;
2280 LVal.setFrom(Info.Ctx, Subobj);
2281 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2282 AccessKind == AK_Increment ? 1 : -1))
2283 return false;
2284 LVal.moveInto(Subobj);
2285 return true;
2286 }
2287 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2288 llvm_unreachable("shouldn't encounter string elements here");
2289 }
2290};
2291} // end anonymous namespace
2292
2293/// Perform an increment or decrement on LVal.
2294static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2295 QualType LValType, bool IsIncrement, APValue *Old) {
2296 if (LVal.Designator.Invalid)
2297 return false;
2298
2299 if (!Info.getLangOpts().CPlusPlus1y) {
2300 Info.Diag(E);
2301 return false;
2302 }
2303
2304 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2305 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2306 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2307 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2308}
2309
Richard Smithe97cbd72011-11-11 04:05:33 +00002310/// Build an lvalue for the object argument of a member function call.
2311static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2312 LValue &This) {
2313 if (Object->getType()->isPointerType())
2314 return EvaluatePointer(Object, This, Info);
2315
2316 if (Object->isGLValue())
2317 return EvaluateLValue(Object, This, Info);
2318
Richard Smithd9f663b2013-04-22 15:31:51 +00002319 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002320 return EvaluateTemporary(Object, This, Info);
2321
2322 return false;
2323}
2324
2325/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2326/// lvalue referring to the result.
2327///
2328/// \param Info - Information about the ongoing evaluation.
2329/// \param BO - The member pointer access operation.
2330/// \param LV - Filled in with a reference to the resulting object.
2331/// \param IncludeMember - Specifies whether the member itself is included in
2332/// the resulting LValue subobject designator. This is not possible when
2333/// creating a bound member function.
2334/// \return The field or method declaration to which the member pointer refers,
2335/// or 0 if evaluation fails.
2336static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2337 const BinaryOperator *BO,
2338 LValue &LV,
2339 bool IncludeMember = true) {
2340 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2341
Richard Smith253c2a32012-01-27 01:14:48 +00002342 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2343 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002344 return 0;
2345
2346 MemberPtr MemPtr;
2347 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2348 return 0;
2349
2350 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2351 // member value, the behavior is undefined.
2352 if (!MemPtr.getDecl())
2353 return 0;
2354
Richard Smith253c2a32012-01-27 01:14:48 +00002355 if (!EvalObjOK)
2356 return 0;
2357
Richard Smith027bf112011-11-17 22:56:20 +00002358 if (MemPtr.isDerivedMember()) {
2359 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002360 // The end of the derived-to-base path for the base object must match the
2361 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002362 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002363 LV.Designator.Entries.size())
2364 return 0;
2365 unsigned PathLengthToMember =
2366 LV.Designator.Entries.size() - MemPtr.Path.size();
2367 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2368 const CXXRecordDecl *LVDecl = getAsBaseClass(
2369 LV.Designator.Entries[PathLengthToMember + I]);
2370 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2371 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2372 return 0;
2373 }
2374
2375 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002376 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2377 PathLengthToMember))
2378 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002379 } else if (!MemPtr.Path.empty()) {
2380 // Extend the LValue path with the member pointer's path.
2381 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2382 MemPtr.Path.size() + IncludeMember);
2383
2384 // Walk down to the appropriate base class.
2385 QualType LVType = BO->getLHS()->getType();
2386 if (const PointerType *PT = LVType->getAs<PointerType>())
2387 LVType = PT->getPointeeType();
2388 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2389 assert(RD && "member pointer access on non-class-type expression");
2390 // The first class in the path is that of the lvalue.
2391 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2392 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002393 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2394 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002395 RD = Base;
2396 }
2397 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002398 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2399 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002400 }
2401
2402 // Add the member. Note that we cannot build bound member functions here.
2403 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002404 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2405 if (!HandleLValueMember(Info, BO, LV, FD))
2406 return 0;
2407 } else if (const IndirectFieldDecl *IFD =
2408 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2409 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2410 return 0;
2411 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002412 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002413 }
Richard Smith027bf112011-11-17 22:56:20 +00002414 }
2415
2416 return MemPtr.getDecl();
2417}
2418
2419/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2420/// the provided lvalue, which currently refers to the base object.
2421static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2422 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002423 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002424 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002425 return false;
2426
Richard Smitha8105bc2012-01-06 16:39:00 +00002427 QualType TargetQT = E->getType();
2428 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2429 TargetQT = PT->getPointeeType();
2430
2431 // Check this cast lands within the final derived-to-base subobject path.
2432 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002433 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002434 << D.MostDerivedType << TargetQT;
2435 return false;
2436 }
2437
Richard Smith027bf112011-11-17 22:56:20 +00002438 // Check the type of the final cast. We don't need to check the path,
2439 // since a cast can only be formed if the path is unique.
2440 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002441 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2442 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002443 if (NewEntriesSize == D.MostDerivedPathLength)
2444 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2445 else
Richard Smith027bf112011-11-17 22:56:20 +00002446 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002447 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002448 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002449 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002450 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002451 }
Richard Smith027bf112011-11-17 22:56:20 +00002452
2453 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002454 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002455}
2456
Mike Stump876387b2009-10-27 22:09:17 +00002457namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002458enum EvalStmtResult {
2459 /// Evaluation failed.
2460 ESR_Failed,
2461 /// Hit a 'return' statement.
2462 ESR_Returned,
2463 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002464 ESR_Succeeded,
2465 /// Hit a 'continue' statement.
2466 ESR_Continue,
2467 /// Hit a 'break' statement.
2468 ESR_Break
Richard Smith254a73d2011-10-28 22:34:42 +00002469};
2470}
2471
Richard Smithd9f663b2013-04-22 15:31:51 +00002472static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2473 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2474 // We don't need to evaluate the initializer for a static local.
2475 if (!VD->hasLocalStorage())
2476 return true;
2477
2478 LValue Result;
2479 Result.set(VD, Info.CurrentCall->Index);
2480 APValue &Val = Info.CurrentCall->Temporaries[VD];
2481
2482 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2483 // Wipe out any partially-computed value, to allow tracking that this
2484 // evaluation failed.
2485 Val = APValue();
2486 return false;
2487 }
2488 }
2489
2490 return true;
2491}
2492
Richard Smith4e18ca52013-05-06 05:56:11 +00002493/// Evaluate a condition (either a variable declaration or an expression).
2494static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2495 const Expr *Cond, bool &Result) {
2496 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2497 return false;
2498 return EvaluateAsBooleanCondition(Cond, Result, Info);
2499}
2500
2501static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2502 const Stmt *S);
2503
2504/// Evaluate the body of a loop, and translate the result as appropriate.
2505static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
2506 const Stmt *Body) {
2507 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body)) {
2508 case ESR_Break:
2509 return ESR_Succeeded;
2510 case ESR_Succeeded:
2511 case ESR_Continue:
2512 return ESR_Continue;
2513 case ESR_Failed:
2514 case ESR_Returned:
2515 return ESR;
2516 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002517 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002518}
2519
Richard Smith254a73d2011-10-28 22:34:42 +00002520// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002521static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002522 const Stmt *S) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002523 // FIXME: Mark all temporaries in the current frame as destroyed at
2524 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002525 switch (S->getStmtClass()) {
2526 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002527 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002528 // Don't bother evaluating beyond an expression-statement which couldn't
2529 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00002530 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00002531 return ESR_Failed;
2532 return ESR_Succeeded;
2533 }
2534
2535 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002536 return ESR_Failed;
2537
2538 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002539 return ESR_Succeeded;
2540
Richard Smithd9f663b2013-04-22 15:31:51 +00002541 case Stmt::DeclStmtClass: {
2542 const DeclStmt *DS = cast<DeclStmt>(S);
2543 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2544 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2545 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2546 return ESR_Failed;
2547 return ESR_Succeeded;
2548 }
2549
Richard Smith357362d2011-12-13 06:39:58 +00002550 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002551 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002552 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002553 return ESR_Failed;
2554 return ESR_Returned;
2555 }
Richard Smith254a73d2011-10-28 22:34:42 +00002556
2557 case Stmt::CompoundStmtClass: {
2558 const CompoundStmt *CS = cast<CompoundStmt>(S);
2559 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2560 BE = CS->body_end(); BI != BE; ++BI) {
2561 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2562 if (ESR != ESR_Succeeded)
2563 return ESR;
2564 }
2565 return ESR_Succeeded;
2566 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002567
2568 case Stmt::IfStmtClass: {
2569 const IfStmt *IS = cast<IfStmt>(S);
2570
2571 // Evaluate the condition, as either a var decl or as an expression.
2572 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00002573 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00002574 return ESR_Failed;
2575
2576 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2577 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2578 if (ESR != ESR_Succeeded)
2579 return ESR;
2580 }
2581 return ESR_Succeeded;
2582 }
Richard Smith4e18ca52013-05-06 05:56:11 +00002583
2584 case Stmt::WhileStmtClass: {
2585 const WhileStmt *WS = cast<WhileStmt>(S);
2586 while (true) {
2587 bool Continue;
2588 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
2589 Continue))
2590 return ESR_Failed;
2591 if (!Continue)
2592 break;
2593
2594 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
2595 if (ESR != ESR_Continue)
2596 return ESR;
2597 }
2598 return ESR_Succeeded;
2599 }
2600
2601 case Stmt::DoStmtClass: {
2602 const DoStmt *DS = cast<DoStmt>(S);
2603 bool Continue;
2604 do {
2605 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody());
2606 if (ESR != ESR_Continue)
2607 return ESR;
2608
2609 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
2610 return ESR_Failed;
2611 } while (Continue);
2612 return ESR_Succeeded;
2613 }
2614
2615 case Stmt::ForStmtClass: {
2616 const ForStmt *FS = cast<ForStmt>(S);
2617 if (FS->getInit()) {
2618 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
2619 if (ESR != ESR_Succeeded)
2620 return ESR;
2621 }
2622 while (true) {
2623 bool Continue = true;
2624 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
2625 FS->getCond(), Continue))
2626 return ESR_Failed;
2627 if (!Continue)
2628 break;
2629
2630 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2631 if (ESR != ESR_Continue)
2632 return ESR;
2633
2634 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2635 return ESR_Failed;
2636 }
2637 return ESR_Succeeded;
2638 }
2639
Richard Smith896e0d72013-05-06 06:51:17 +00002640 case Stmt::CXXForRangeStmtClass: {
2641 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
2642
2643 // Initialize the __range variable.
2644 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
2645 if (ESR != ESR_Succeeded)
2646 return ESR;
2647
2648 // Create the __begin and __end iterators.
2649 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
2650 if (ESR != ESR_Succeeded)
2651 return ESR;
2652
2653 while (true) {
2654 // Condition: __begin != __end.
2655 bool Continue = true;
2656 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
2657 return ESR_Failed;
2658 if (!Continue)
2659 break;
2660
2661 // User's variable declaration, initialized by *__begin.
2662 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
2663 if (ESR != ESR_Succeeded)
2664 return ESR;
2665
2666 // Loop body.
2667 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2668 if (ESR != ESR_Continue)
2669 return ESR;
2670
2671 // Increment: ++__begin
2672 if (!EvaluateIgnoredValue(Info, FS->getInc()))
2673 return ESR_Failed;
2674 }
2675
2676 return ESR_Succeeded;
2677 }
2678
Richard Smith4e18ca52013-05-06 05:56:11 +00002679 case Stmt::ContinueStmtClass:
2680 return ESR_Continue;
2681
2682 case Stmt::BreakStmtClass:
2683 return ESR_Break;
Richard Smith254a73d2011-10-28 22:34:42 +00002684 }
2685}
2686
Richard Smithcc36f692011-12-22 02:22:31 +00002687/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2688/// default constructor. If so, we'll fold it whether or not it's marked as
2689/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2690/// so we need special handling.
2691static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002692 const CXXConstructorDecl *CD,
2693 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002694 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2695 return false;
2696
Richard Smith66e05fe2012-01-18 05:21:49 +00002697 // Value-initialization does not call a trivial default constructor, so such a
2698 // call is a core constant expression whether or not the constructor is
2699 // constexpr.
2700 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002701 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002702 // FIXME: If DiagDecl is an implicitly-declared special member function,
2703 // we should be much more explicit about why it's not constexpr.
2704 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2705 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2706 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002707 } else {
2708 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2709 }
2710 }
2711 return true;
2712}
2713
Richard Smith357362d2011-12-13 06:39:58 +00002714/// CheckConstexprFunction - Check that a function can be called in a constant
2715/// expression.
2716static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2717 const FunctionDecl *Declaration,
2718 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002719 // Potential constant expressions can contain calls to declared, but not yet
2720 // defined, constexpr functions.
2721 if (Info.CheckingPotentialConstantExpression && !Definition &&
2722 Declaration->isConstexpr())
2723 return false;
2724
Richard Smith357362d2011-12-13 06:39:58 +00002725 // Can we evaluate this function call?
2726 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2727 return true;
2728
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002729 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002730 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002731 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2732 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002733 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2734 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2735 << DiagDecl;
2736 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2737 } else {
2738 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2739 }
2740 return false;
2741}
2742
Richard Smithd62306a2011-11-10 06:34:14 +00002743namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002744typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002745}
2746
2747/// EvaluateArgs - Evaluate the arguments to a function call.
2748static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2749 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002750 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002751 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002752 I != E; ++I) {
2753 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2754 // If we're checking for a potential constant expression, evaluate all
2755 // initializers even if some of them fail.
2756 if (!Info.keepEvaluatingAfterFailure())
2757 return false;
2758 Success = false;
2759 }
2760 }
2761 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002762}
2763
Richard Smith254a73d2011-10-28 22:34:42 +00002764/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002765static bool HandleFunctionCall(SourceLocation CallLoc,
2766 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002767 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002768 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002769 ArgVector ArgValues(Args.size());
2770 if (!EvaluateArgs(Args, ArgValues, Info))
2771 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002772
Richard Smith253c2a32012-01-27 01:14:48 +00002773 if (!Info.CheckCallLimit(CallLoc))
2774 return false;
2775
2776 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd9f663b2013-04-22 15:31:51 +00002777 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00002778 if (ESR == ESR_Succeeded) {
2779 if (Callee->getResultType()->isVoidType())
2780 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002781 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00002782 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002783 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00002784}
2785
Richard Smithd62306a2011-11-10 06:34:14 +00002786/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002787static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002788 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002789 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002790 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002791 ArgVector ArgValues(Args.size());
2792 if (!EvaluateArgs(Args, ArgValues, Info))
2793 return false;
2794
Richard Smith253c2a32012-01-27 01:14:48 +00002795 if (!Info.CheckCallLimit(CallLoc))
2796 return false;
2797
Richard Smith3607ffe2012-02-13 03:54:03 +00002798 const CXXRecordDecl *RD = Definition->getParent();
2799 if (RD->getNumVBases()) {
2800 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2801 return false;
2802 }
2803
Richard Smith253c2a32012-01-27 01:14:48 +00002804 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002805
2806 // If it's a delegating constructor, just delegate.
2807 if (Definition->isDelegatingConstructor()) {
2808 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00002809 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
2810 return false;
2811 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002812 }
2813
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002814 // For a trivial copy or move constructor, perform an APValue copy. This is
2815 // essential for unions, where the operations performed by the constructor
2816 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002817 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002818 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2819 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002820 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002821 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00002822 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00002823 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002824 }
2825
2826 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002827 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002828 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2829 std::distance(RD->field_begin(), RD->field_end()));
2830
John McCalld7bca762012-05-01 00:38:49 +00002831 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002832 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2833
Richard Smith253c2a32012-01-27 01:14:48 +00002834 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002835 unsigned BasesSeen = 0;
2836#ifndef NDEBUG
2837 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2838#endif
2839 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2840 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002841 LValue Subobject = This;
2842 APValue *Value = &Result;
2843
2844 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002845 if ((*I)->isBaseInitializer()) {
2846 QualType BaseType((*I)->getBaseClass(), 0);
2847#ifndef NDEBUG
2848 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002849 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002850 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2851 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2852 "base class initializers not in expected order");
2853 ++BaseIt;
2854#endif
John McCalld7bca762012-05-01 00:38:49 +00002855 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2856 BaseType->getAsCXXRecordDecl(), &Layout))
2857 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002858 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002859 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002860 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2861 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002862 if (RD->isUnion()) {
2863 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002864 Value = &Result.getUnionValue();
2865 } else {
2866 Value = &Result.getStructField(FD->getFieldIndex());
2867 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002868 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002869 // Walk the indirect field decl's chain to find the object to initialize,
2870 // and make sure we've initialized every step along it.
2871 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2872 CE = IFD->chain_end();
2873 C != CE; ++C) {
2874 FieldDecl *FD = cast<FieldDecl>(*C);
2875 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2876 // Switch the union field if it differs. This happens if we had
2877 // preceding zero-initialization, and we're now initializing a union
2878 // subobject other than the first.
2879 // FIXME: In this case, the values of the other subobjects are
2880 // specified, since zero-initialization sets all padding bits to zero.
2881 if (Value->isUninit() ||
2882 (Value->isUnion() && Value->getUnionField() != FD)) {
2883 if (CD->isUnion())
2884 *Value = APValue(FD);
2885 else
2886 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2887 std::distance(CD->field_begin(), CD->field_end()));
2888 }
John McCalld7bca762012-05-01 00:38:49 +00002889 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2890 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002891 if (CD->isUnion())
2892 Value = &Value->getUnionValue();
2893 else
2894 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002895 }
Richard Smithd62306a2011-11-10 06:34:14 +00002896 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002897 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002898 }
Richard Smith253c2a32012-01-27 01:14:48 +00002899
Richard Smithb228a862012-02-15 02:18:13 +00002900 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2901 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002902 ? CCEK_Constant : CCEK_MemberInit)) {
2903 // If we're checking for a potential constant expression, evaluate all
2904 // initializers even if some of them fail.
2905 if (!Info.keepEvaluatingAfterFailure())
2906 return false;
2907 Success = false;
2908 }
Richard Smithd62306a2011-11-10 06:34:14 +00002909 }
2910
Richard Smithd9f663b2013-04-22 15:31:51 +00002911 return Success &&
2912 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002913}
2914
Eli Friedman9a156e52008-11-12 09:44:48 +00002915//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002916// Generic Evaluation
2917//===----------------------------------------------------------------------===//
2918namespace {
2919
Richard Smithf57d8cb2011-12-09 22:58:01 +00002920// FIXME: RetTy is always bool. Remove it.
2921template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002922class ExprEvaluatorBase
2923 : public ConstStmtVisitor<Derived, RetTy> {
2924private:
Richard Smith2e312c82012-03-03 22:46:17 +00002925 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002926 return static_cast<Derived*>(this)->Success(V, E);
2927 }
Richard Smithfddd3842011-12-30 21:15:51 +00002928 RetTy DerivedZeroInitialization(const Expr *E) {
2929 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002930 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002931
Richard Smith17100ba2012-02-16 02:46:34 +00002932 // Check whether a conditional operator with a non-constant condition is a
2933 // potential constant expression. If neither arm is a potential constant
2934 // expression, then the conditional operator is not either.
2935 template<typename ConditionalOperator>
2936 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2937 assert(Info.CheckingPotentialConstantExpression);
2938
2939 // Speculatively evaluate both arms.
2940 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002941 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002942 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2943
2944 StmtVisitorTy::Visit(E->getFalseExpr());
2945 if (Diag.empty())
2946 return;
2947
2948 Diag.clear();
2949 StmtVisitorTy::Visit(E->getTrueExpr());
2950 if (Diag.empty())
2951 return;
2952 }
2953
2954 Error(E, diag::note_constexpr_conditional_never_const);
2955 }
2956
2957
2958 template<typename ConditionalOperator>
2959 bool HandleConditionalOperator(const ConditionalOperator *E) {
2960 bool BoolResult;
2961 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2962 if (Info.CheckingPotentialConstantExpression)
2963 CheckPotentialConstantConditional(E);
2964 return false;
2965 }
2966
2967 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2968 return StmtVisitorTy::Visit(EvalExpr);
2969 }
2970
Peter Collingbournee9200682011-05-13 03:29:01 +00002971protected:
2972 EvalInfo &Info;
2973 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2974 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2975
Richard Smith92b1ce02011-12-12 09:28:41 +00002976 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002977 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002978 }
2979
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002980 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2981
2982public:
2983 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2984
2985 EvalInfo &getEvalInfo() { return Info; }
2986
Richard Smithf57d8cb2011-12-09 22:58:01 +00002987 /// Report an evaluation error. This should only be called when an error is
2988 /// first discovered. When propagating an error, just return false.
2989 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002990 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002991 return false;
2992 }
2993 bool Error(const Expr *E) {
2994 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2995 }
2996
Peter Collingbournee9200682011-05-13 03:29:01 +00002997 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002998 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002999 }
3000 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003001 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003002 }
3003
3004 RetTy VisitParenExpr(const ParenExpr *E)
3005 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3006 RetTy VisitUnaryExtension(const UnaryOperator *E)
3007 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3008 RetTy VisitUnaryPlus(const UnaryOperator *E)
3009 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3010 RetTy VisitChooseExpr(const ChooseExpr *E)
3011 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3012 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3013 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003014 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3015 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003016 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3017 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003018 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3019 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003020 // We cannot create any objects for which cleanups are required, so there is
3021 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3022 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3023 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003024
Richard Smith6d6ecc32011-12-12 12:46:16 +00003025 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3026 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3027 return static_cast<Derived*>(this)->VisitCastExpr(E);
3028 }
3029 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3030 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3031 return static_cast<Derived*>(this)->VisitCastExpr(E);
3032 }
3033
Richard Smith027bf112011-11-17 22:56:20 +00003034 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3035 switch (E->getOpcode()) {
3036 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003037 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003038
3039 case BO_Comma:
3040 VisitIgnoredValue(E->getLHS());
3041 return StmtVisitorTy::Visit(E->getRHS());
3042
3043 case BO_PtrMemD:
3044 case BO_PtrMemI: {
3045 LValue Obj;
3046 if (!HandleMemberPointerAccess(Info, E, Obj))
3047 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003048 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003049 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003050 return false;
3051 return DerivedSuccess(Result, E);
3052 }
3053 }
3054 }
3055
Peter Collingbournee9200682011-05-13 03:29:01 +00003056 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003057 // Evaluate and cache the common expression. We treat it as a temporary,
3058 // even though it's not quite the same thing.
3059 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3060 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003061 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003062
Richard Smith17100ba2012-02-16 02:46:34 +00003063 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003064 }
3065
3066 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003067 bool IsBcpCall = false;
3068 // If the condition (ignoring parens) is a __builtin_constant_p call,
3069 // the result is a constant expression if it can be folded without
3070 // side-effects. This is an important GNU extension. See GCC PR38377
3071 // for discussion.
3072 if (const CallExpr *CallCE =
3073 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3074 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3075 IsBcpCall = true;
3076
3077 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3078 // constant expression; we can't check whether it's potentially foldable.
3079 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3080 return false;
3081
3082 FoldConstant Fold(Info);
3083
Richard Smith17100ba2012-02-16 02:46:34 +00003084 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003085 return false;
3086
3087 if (IsBcpCall)
3088 Fold.Fold(Info);
3089
3090 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003091 }
3092
3093 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003094 APValue &Value = Info.CurrentCall->Temporaries[E];
3095 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003096 const Expr *Source = E->getSourceExpr();
3097 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003098 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003099 if (Source == E) { // sanity checking.
3100 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003101 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003102 }
3103 return StmtVisitorTy::Visit(Source);
3104 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003105 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003106 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003107
Richard Smith254a73d2011-10-28 22:34:42 +00003108 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003109 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003110 QualType CalleeType = Callee->getType();
3111
Richard Smith254a73d2011-10-28 22:34:42 +00003112 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003113 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003114 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003115 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003116
Richard Smithe97cbd72011-11-11 04:05:33 +00003117 // Extract function decl and 'this' pointer from the callee.
3118 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003119 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003120 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3121 // Explicit bound member calls, such as x.f() or p->g();
3122 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003123 return false;
3124 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003125 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003126 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003127 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3128 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003129 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3130 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003131 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003132 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003133 return Error(Callee);
3134
3135 FD = dyn_cast<FunctionDecl>(Member);
3136 if (!FD)
3137 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003138 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003139 LValue Call;
3140 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003141 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003142
Richard Smitha8105bc2012-01-06 16:39:00 +00003143 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003144 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003145 FD = dyn_cast_or_null<FunctionDecl>(
3146 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003147 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003148 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003149
3150 // Overloaded operator calls to member functions are represented as normal
3151 // calls with '*this' as the first argument.
3152 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3153 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003154 // FIXME: When selecting an implicit conversion for an overloaded
3155 // operator delete, we sometimes try to evaluate calls to conversion
3156 // operators without a 'this' parameter!
3157 if (Args.empty())
3158 return Error(E);
3159
Richard Smithe97cbd72011-11-11 04:05:33 +00003160 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3161 return false;
3162 This = &ThisVal;
3163 Args = Args.slice(1);
3164 }
3165
3166 // Don't call function pointers which have been cast to some other type.
3167 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003168 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003169 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003170 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003171
Richard Smith47b34932012-02-01 02:39:43 +00003172 if (This && !This->checkSubobject(Info, E, CSK_This))
3173 return false;
3174
Richard Smith3607ffe2012-02-13 03:54:03 +00003175 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3176 // calls to such functions in constant expressions.
3177 if (This && !HasQualifier &&
3178 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3179 return Error(E, diag::note_constexpr_virtual_call);
3180
Richard Smith357362d2011-12-13 06:39:58 +00003181 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003182 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003183 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003184
Richard Smith357362d2011-12-13 06:39:58 +00003185 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003186 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3187 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003188 return false;
3189
Richard Smithb228a862012-02-15 02:18:13 +00003190 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003191 }
3192
Richard Smith11562c52011-10-28 17:51:58 +00003193 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3194 return StmtVisitorTy::Visit(E->getInitializer());
3195 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003196 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003197 if (E->getNumInits() == 0)
3198 return DerivedZeroInitialization(E);
3199 if (E->getNumInits() == 1)
3200 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003201 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003202 }
3203 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003204 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003205 }
3206 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003207 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003208 }
Richard Smith027bf112011-11-17 22:56:20 +00003209 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003210 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003211 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003212
Richard Smithd62306a2011-11-10 06:34:14 +00003213 /// A member expression where the object is a prvalue is itself a prvalue.
3214 RetTy VisitMemberExpr(const MemberExpr *E) {
3215 assert(!E->isArrow() && "missing call to bound member function?");
3216
Richard Smith2e312c82012-03-03 22:46:17 +00003217 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003218 if (!Evaluate(Val, Info, E->getBase()))
3219 return false;
3220
3221 QualType BaseTy = E->getBase()->getType();
3222
3223 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003224 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003225 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003226 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003227 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3228
Richard Smith3229b742013-05-05 21:17:10 +00003229 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003230 SubobjectDesignator Designator(BaseTy);
3231 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003232
Richard Smith3229b742013-05-05 21:17:10 +00003233 APValue Result;
3234 return extractSubobject(Info, E, Obj, Designator, Result) &&
3235 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003236 }
3237
Richard Smith11562c52011-10-28 17:51:58 +00003238 RetTy VisitCastExpr(const CastExpr *E) {
3239 switch (E->getCastKind()) {
3240 default:
3241 break;
3242
David Chisnallfa35df62012-01-16 17:27:18 +00003243 case CK_AtomicToNonAtomic:
3244 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003245 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003246 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003247 return StmtVisitorTy::Visit(E->getSubExpr());
3248
3249 case CK_LValueToRValue: {
3250 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003251 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3252 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003253 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003254 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003255 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003256 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003257 return false;
3258 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003259 }
3260 }
3261
Richard Smithf57d8cb2011-12-09 22:58:01 +00003262 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003263 }
3264
Richard Smith243ef902013-05-05 23:31:59 +00003265 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3266 return VisitUnaryPostIncDec(UO);
3267 }
3268 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3269 return VisitUnaryPostIncDec(UO);
3270 }
3271 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3272 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3273 return Error(UO);
3274
3275 LValue LVal;
3276 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3277 return false;
3278 APValue RVal;
3279 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3280 UO->isIncrementOp(), &RVal))
3281 return false;
3282 return DerivedSuccess(RVal, UO);
3283 }
3284
Richard Smith4a678122011-10-24 18:44:57 +00003285 /// Visit a value which is evaluated, but whose value is ignored.
3286 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003287 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003288 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003289};
3290
3291}
3292
3293//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003294// Common base class for lvalue and temporary evaluation.
3295//===----------------------------------------------------------------------===//
3296namespace {
3297template<class Derived>
3298class LValueExprEvaluatorBase
3299 : public ExprEvaluatorBase<Derived, bool> {
3300protected:
3301 LValue &Result;
3302 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3303 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3304
3305 bool Success(APValue::LValueBase B) {
3306 Result.set(B);
3307 return true;
3308 }
3309
3310public:
3311 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3312 ExprEvaluatorBaseTy(Info), Result(Result) {}
3313
Richard Smith2e312c82012-03-03 22:46:17 +00003314 bool Success(const APValue &V, const Expr *E) {
3315 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003316 return true;
3317 }
Richard Smith027bf112011-11-17 22:56:20 +00003318
Richard Smith027bf112011-11-17 22:56:20 +00003319 bool VisitMemberExpr(const MemberExpr *E) {
3320 // Handle non-static data members.
3321 QualType BaseTy;
3322 if (E->isArrow()) {
3323 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3324 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003325 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003326 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003327 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003328 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3329 return false;
3330 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003331 } else {
3332 if (!this->Visit(E->getBase()))
3333 return false;
3334 BaseTy = E->getBase()->getType();
3335 }
Richard Smith027bf112011-11-17 22:56:20 +00003336
Richard Smith1b78b3d2012-01-25 22:15:11 +00003337 const ValueDecl *MD = E->getMemberDecl();
3338 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3339 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3340 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3341 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003342 if (!HandleLValueMember(this->Info, E, Result, FD))
3343 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003344 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003345 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3346 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003347 } else
3348 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003349
Richard Smith1b78b3d2012-01-25 22:15:11 +00003350 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003351 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003352 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003353 RefValue))
3354 return false;
3355 return Success(RefValue, E);
3356 }
3357 return true;
3358 }
3359
3360 bool VisitBinaryOperator(const BinaryOperator *E) {
3361 switch (E->getOpcode()) {
3362 default:
3363 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3364
3365 case BO_PtrMemD:
3366 case BO_PtrMemI:
3367 return HandleMemberPointerAccess(this->Info, E, Result);
3368 }
3369 }
3370
3371 bool VisitCastExpr(const CastExpr *E) {
3372 switch (E->getCastKind()) {
3373 default:
3374 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3375
3376 case CK_DerivedToBase:
3377 case CK_UncheckedDerivedToBase: {
3378 if (!this->Visit(E->getSubExpr()))
3379 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003380
3381 // Now figure out the necessary offset to add to the base LV to get from
3382 // the derived class to the base class.
3383 QualType Type = E->getSubExpr()->getType();
3384
3385 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3386 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003387 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003388 *PathI))
3389 return false;
3390 Type = (*PathI)->getType();
3391 }
3392
3393 return true;
3394 }
3395 }
3396 }
3397};
3398}
3399
3400//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003401// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003402//
3403// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3404// function designators (in C), decl references to void objects (in C), and
3405// temporaries (if building with -Wno-address-of-temporary).
3406//
3407// LValue evaluation produces values comprising a base expression of one of the
3408// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003409// - Declarations
3410// * VarDecl
3411// * FunctionDecl
3412// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003413// * CompoundLiteralExpr in C
3414// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003415// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003416// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003417// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003418// * ObjCEncodeExpr
3419// * AddrLabelExpr
3420// * BlockExpr
3421// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003422// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003423// * Any Expr, with a CallIndex indicating the function in which the temporary
3424// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003425// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003426//===----------------------------------------------------------------------===//
3427namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003428class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003429 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003430public:
Richard Smith027bf112011-11-17 22:56:20 +00003431 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3432 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003433
Richard Smith11562c52011-10-28 17:51:58 +00003434 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003435 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003436
Peter Collingbournee9200682011-05-13 03:29:01 +00003437 bool VisitDeclRefExpr(const DeclRefExpr *E);
3438 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003439 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003440 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3441 bool VisitMemberExpr(const MemberExpr *E);
3442 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3443 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003444 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003445 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003446 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3447 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003448 bool VisitUnaryReal(const UnaryOperator *E);
3449 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003450 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3451 return VisitUnaryPreIncDec(UO);
3452 }
3453 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3454 return VisitUnaryPreIncDec(UO);
3455 }
Richard Smith3229b742013-05-05 21:17:10 +00003456 bool VisitBinAssign(const BinaryOperator *BO);
3457 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003458
Peter Collingbournee9200682011-05-13 03:29:01 +00003459 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003460 switch (E->getCastKind()) {
3461 default:
Richard Smith027bf112011-11-17 22:56:20 +00003462 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003463
Eli Friedmance3e02a2011-10-11 00:13:24 +00003464 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003465 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003466 if (!Visit(E->getSubExpr()))
3467 return false;
3468 Result.Designator.setInvalid();
3469 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003470
Richard Smith027bf112011-11-17 22:56:20 +00003471 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003472 if (!Visit(E->getSubExpr()))
3473 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003474 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003475 }
3476 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003477};
3478} // end anonymous namespace
3479
Richard Smith11562c52011-10-28 17:51:58 +00003480/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003481/// expressions which are not glvalues, in two cases:
3482/// * function designators in C, and
3483/// * "extern void" objects
3484static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3485 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3486 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003487 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003488}
3489
Peter Collingbournee9200682011-05-13 03:29:01 +00003490bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003491 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3492 return Success(FD);
3493 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003494 return VisitVarDecl(E, VD);
3495 return Error(E);
3496}
Richard Smith733237d2011-10-24 23:14:33 +00003497
Richard Smith11562c52011-10-28 17:51:58 +00003498bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003499 CallStackFrame *Frame = 0;
3500 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3501 Frame = Info.CurrentCall;
3502
Richard Smithfec09922011-11-01 16:57:24 +00003503 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003504 if (Frame) {
3505 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003506 return true;
3507 }
Richard Smithce40ad62011-11-12 22:28:03 +00003508 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003509 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003510
Richard Smith3229b742013-05-05 21:17:10 +00003511 APValue *V;
3512 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003513 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003514 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003515}
3516
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003517bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3518 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003519 if (E->getType()->isRecordType())
3520 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003521
Richard Smithb228a862012-02-15 02:18:13 +00003522 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003523 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3524 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003525}
3526
Peter Collingbournee9200682011-05-13 03:29:01 +00003527bool
3528LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003529 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3530 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3531 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003532 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003533}
3534
Richard Smith6e525142011-12-27 12:18:28 +00003535bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003536 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003537 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003538
3539 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3540 << E->getExprOperand()->getType()
3541 << E->getExprOperand()->getSourceRange();
3542 return false;
Richard Smith6e525142011-12-27 12:18:28 +00003543}
3544
Francois Pichet0066db92012-04-16 04:08:35 +00003545bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3546 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00003547}
Francois Pichet0066db92012-04-16 04:08:35 +00003548
Peter Collingbournee9200682011-05-13 03:29:01 +00003549bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003550 // Handle static data members.
3551 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3552 VisitIgnoredValue(E->getBase());
3553 return VisitVarDecl(E, VD);
3554 }
3555
Richard Smith254a73d2011-10-28 22:34:42 +00003556 // Handle static member functions.
3557 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3558 if (MD->isStatic()) {
3559 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003560 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003561 }
3562 }
3563
Richard Smithd62306a2011-11-10 06:34:14 +00003564 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003565 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003566}
3567
Peter Collingbournee9200682011-05-13 03:29:01 +00003568bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003569 // FIXME: Deal with vectors as array subscript bases.
3570 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003571 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003572
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003573 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003574 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003575
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003576 APSInt Index;
3577 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003578 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003579 int64_t IndexValue
3580 = Index.isSigned() ? Index.getSExtValue()
3581 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003582
Richard Smitha8105bc2012-01-06 16:39:00 +00003583 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003584}
Eli Friedman9a156e52008-11-12 09:44:48 +00003585
Peter Collingbournee9200682011-05-13 03:29:01 +00003586bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003587 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003588}
3589
Richard Smith66c96992012-02-18 22:04:06 +00003590bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3591 if (!Visit(E->getSubExpr()))
3592 return false;
3593 // __real is a no-op on scalar lvalues.
3594 if (E->getSubExpr()->getType()->isAnyComplexType())
3595 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3596 return true;
3597}
3598
3599bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3600 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3601 "lvalue __imag__ on scalar?");
3602 if (!Visit(E->getSubExpr()))
3603 return false;
3604 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3605 return true;
3606}
3607
Richard Smith243ef902013-05-05 23:31:59 +00003608bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
3609 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003610 return Error(UO);
3611
3612 if (!this->Visit(UO->getSubExpr()))
3613 return false;
3614
Richard Smith243ef902013-05-05 23:31:59 +00003615 return handleIncDec(
3616 this->Info, UO, Result, UO->getSubExpr()->getType(),
3617 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00003618}
3619
3620bool LValueExprEvaluator::VisitCompoundAssignOperator(
3621 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00003622 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003623 return Error(CAO);
3624
Richard Smith3229b742013-05-05 21:17:10 +00003625 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00003626
3627 // The overall lvalue result is the result of evaluating the LHS.
3628 if (!this->Visit(CAO->getLHS())) {
3629 if (Info.keepEvaluatingAfterFailure())
3630 Evaluate(RHS, this->Info, CAO->getRHS());
3631 return false;
3632 }
3633
Richard Smith3229b742013-05-05 21:17:10 +00003634 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
3635 return false;
3636
3637 // FIXME:
3638 //return handleCompoundAssignment(
3639 // this->Info, CAO,
3640 // Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
3641 // RHS, CAO->getRHS()->getType(),
3642 // CAO->getOpForCompoundAssignment(CAO->getOpcode()),
3643 // CAO->getComputationResultType());
3644 return Error(CAO);
3645}
3646
3647bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00003648 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3649 return Error(E);
3650
Richard Smith3229b742013-05-05 21:17:10 +00003651 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00003652
3653 if (!this->Visit(E->getLHS())) {
3654 if (Info.keepEvaluatingAfterFailure())
3655 Evaluate(NewVal, this->Info, E->getRHS());
3656 return false;
3657 }
3658
Richard Smith3229b742013-05-05 21:17:10 +00003659 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3660 return false;
Richard Smith243ef902013-05-05 23:31:59 +00003661
3662 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00003663 NewVal);
3664}
3665
Eli Friedman9a156e52008-11-12 09:44:48 +00003666//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003667// Pointer Evaluation
3668//===----------------------------------------------------------------------===//
3669
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003670namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003671class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003672 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003673 LValue &Result;
3674
Peter Collingbournee9200682011-05-13 03:29:01 +00003675 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003676 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003677 return true;
3678 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003679public:
Mike Stump11289f42009-09-09 15:08:12 +00003680
John McCall45d55e42010-05-07 21:00:08 +00003681 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003682 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003683
Richard Smith2e312c82012-03-03 22:46:17 +00003684 bool Success(const APValue &V, const Expr *E) {
3685 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00003686 return true;
3687 }
Richard Smithfddd3842011-12-30 21:15:51 +00003688 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003689 return Success((Expr*)0);
3690 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003691
John McCall45d55e42010-05-07 21:00:08 +00003692 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003693 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003694 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003695 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003696 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003697 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003698 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003699 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003700 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003701 bool VisitCallExpr(const CallExpr *E);
3702 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003703 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003704 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003705 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003706 }
Richard Smithd62306a2011-11-10 06:34:14 +00003707 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3708 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003709 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003710 Result = *Info.CurrentCall->This;
3711 return true;
3712 }
John McCallc07a0c72011-02-17 10:25:35 +00003713
Eli Friedman449fe542009-03-23 04:56:01 +00003714 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003715};
Chris Lattner05706e882008-07-11 18:11:29 +00003716} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003717
John McCall45d55e42010-05-07 21:00:08 +00003718static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003719 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003720 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003721}
3722
John McCall45d55e42010-05-07 21:00:08 +00003723bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003724 if (E->getOpcode() != BO_Add &&
3725 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003726 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003727
Chris Lattner05706e882008-07-11 18:11:29 +00003728 const Expr *PExp = E->getLHS();
3729 const Expr *IExp = E->getRHS();
3730 if (IExp->getType()->isPointerType())
3731 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003732
Richard Smith253c2a32012-01-27 01:14:48 +00003733 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3734 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003735 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003736
John McCall45d55e42010-05-07 21:00:08 +00003737 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003738 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003739 return false;
3740 int64_t AdditionalOffset
3741 = Offset.isSigned() ? Offset.getSExtValue()
3742 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003743 if (E->getOpcode() == BO_Sub)
3744 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003745
Ted Kremenek28831752012-08-23 20:46:57 +00003746 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003747 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3748 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003749}
Eli Friedman9a156e52008-11-12 09:44:48 +00003750
John McCall45d55e42010-05-07 21:00:08 +00003751bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3752 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003753}
Mike Stump11289f42009-09-09 15:08:12 +00003754
Peter Collingbournee9200682011-05-13 03:29:01 +00003755bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3756 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003757
Eli Friedman847a2bc2009-12-27 05:43:15 +00003758 switch (E->getCastKind()) {
3759 default:
3760 break;
3761
John McCalle3027922010-08-25 11:45:40 +00003762 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003763 case CK_CPointerToObjCPointerCast:
3764 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003765 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003766 if (!Visit(SubExpr))
3767 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003768 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3769 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3770 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003771 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003772 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003773 if (SubExpr->getType()->isVoidPointerType())
3774 CCEDiag(E, diag::note_constexpr_invalid_cast)
3775 << 3 << SubExpr->getType();
3776 else
3777 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3778 }
Richard Smith96e0c102011-11-04 02:25:55 +00003779 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003780
Anders Carlsson18275092010-10-31 20:41:46 +00003781 case CK_DerivedToBase:
3782 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003783 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003784 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003785 if (!Result.Base && Result.Offset.isZero())
3786 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003787
Richard Smithd62306a2011-11-10 06:34:14 +00003788 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003789 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003790 QualType Type =
3791 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003792
Richard Smithd62306a2011-11-10 06:34:14 +00003793 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003794 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003795 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3796 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003797 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003798 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003799 }
3800
Anders Carlsson18275092010-10-31 20:41:46 +00003801 return true;
3802 }
3803
Richard Smith027bf112011-11-17 22:56:20 +00003804 case CK_BaseToDerived:
3805 if (!Visit(E->getSubExpr()))
3806 return false;
3807 if (!Result.Base && Result.Offset.isZero())
3808 return true;
3809 return HandleBaseToDerivedCast(Info, E, Result);
3810
Richard Smith0b0a0b62011-10-29 20:57:55 +00003811 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003812 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003813 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003814
John McCalle3027922010-08-25 11:45:40 +00003815 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003816 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3817
Richard Smith2e312c82012-03-03 22:46:17 +00003818 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003819 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003820 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003821
John McCall45d55e42010-05-07 21:00:08 +00003822 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003823 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3824 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003825 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003826 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003827 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003828 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003829 return true;
3830 } else {
3831 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003832 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003833 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003834 }
3835 }
John McCalle3027922010-08-25 11:45:40 +00003836 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003837 if (SubExpr->isGLValue()) {
3838 if (!EvaluateLValue(SubExpr, Result, Info))
3839 return false;
3840 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003841 Result.set(SubExpr, Info.CurrentCall->Index);
3842 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3843 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003844 return false;
3845 }
Richard Smith96e0c102011-11-04 02:25:55 +00003846 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003847 if (const ConstantArrayType *CAT
3848 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3849 Result.addArray(Info, E, CAT);
3850 else
3851 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003852 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003853
John McCalle3027922010-08-25 11:45:40 +00003854 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003855 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003856 }
3857
Richard Smith11562c52011-10-28 17:51:58 +00003858 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003859}
Chris Lattner05706e882008-07-11 18:11:29 +00003860
Peter Collingbournee9200682011-05-13 03:29:01 +00003861bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003862 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003863 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003864
Peter Collingbournee9200682011-05-13 03:29:01 +00003865 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003866}
Chris Lattner05706e882008-07-11 18:11:29 +00003867
3868//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003869// Member Pointer Evaluation
3870//===----------------------------------------------------------------------===//
3871
3872namespace {
3873class MemberPointerExprEvaluator
3874 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3875 MemberPtr &Result;
3876
3877 bool Success(const ValueDecl *D) {
3878 Result = MemberPtr(D);
3879 return true;
3880 }
3881public:
3882
3883 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3884 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3885
Richard Smith2e312c82012-03-03 22:46:17 +00003886 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003887 Result.setFrom(V);
3888 return true;
3889 }
Richard Smithfddd3842011-12-30 21:15:51 +00003890 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003891 return Success((const ValueDecl*)0);
3892 }
3893
3894 bool VisitCastExpr(const CastExpr *E);
3895 bool VisitUnaryAddrOf(const UnaryOperator *E);
3896};
3897} // end anonymous namespace
3898
3899static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3900 EvalInfo &Info) {
3901 assert(E->isRValue() && E->getType()->isMemberPointerType());
3902 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3903}
3904
3905bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3906 switch (E->getCastKind()) {
3907 default:
3908 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3909
3910 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003911 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003912 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003913
3914 case CK_BaseToDerivedMemberPointer: {
3915 if (!Visit(E->getSubExpr()))
3916 return false;
3917 if (E->path_empty())
3918 return true;
3919 // Base-to-derived member pointer casts store the path in derived-to-base
3920 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3921 // the wrong end of the derived->base arc, so stagger the path by one class.
3922 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3923 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3924 PathI != PathE; ++PathI) {
3925 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3926 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3927 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003928 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003929 }
3930 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3931 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003932 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003933 return true;
3934 }
3935
3936 case CK_DerivedToBaseMemberPointer:
3937 if (!Visit(E->getSubExpr()))
3938 return false;
3939 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3940 PathE = E->path_end(); PathI != PathE; ++PathI) {
3941 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3942 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3943 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003944 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003945 }
3946 return true;
3947 }
3948}
3949
3950bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3951 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3952 // member can be formed.
3953 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3954}
3955
3956//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003957// Record Evaluation
3958//===----------------------------------------------------------------------===//
3959
3960namespace {
3961 class RecordExprEvaluator
3962 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3963 const LValue &This;
3964 APValue &Result;
3965 public:
3966
3967 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3968 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3969
Richard Smith2e312c82012-03-03 22:46:17 +00003970 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003971 Result = V;
3972 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003973 }
Richard Smithfddd3842011-12-30 21:15:51 +00003974 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003975
Richard Smithe97cbd72011-11-11 04:05:33 +00003976 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003977 bool VisitInitListExpr(const InitListExpr *E);
3978 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3979 };
3980}
3981
Richard Smithfddd3842011-12-30 21:15:51 +00003982/// Perform zero-initialization on an object of non-union class type.
3983/// C++11 [dcl.init]p5:
3984/// To zero-initialize an object or reference of type T means:
3985/// [...]
3986/// -- if T is a (possibly cv-qualified) non-union class type,
3987/// each non-static data member and each base-class subobject is
3988/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003989static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3990 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003991 const LValue &This, APValue &Result) {
3992 assert(!RD->isUnion() && "Expected non-union class type");
3993 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3994 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3995 std::distance(RD->field_begin(), RD->field_end()));
3996
John McCalld7bca762012-05-01 00:38:49 +00003997 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003998 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3999
4000 if (CD) {
4001 unsigned Index = 0;
4002 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004003 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004004 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4005 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004006 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4007 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004008 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004009 Result.getStructBase(Index)))
4010 return false;
4011 }
4012 }
4013
Richard Smitha8105bc2012-01-06 16:39:00 +00004014 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4015 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004016 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004017 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004018 continue;
4019
4020 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004021 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004022 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004023
David Blaikie2d7c57e2012-04-30 02:36:29 +00004024 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004025 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004026 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004027 return false;
4028 }
4029
4030 return true;
4031}
4032
4033bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4034 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004035 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004036 if (RD->isUnion()) {
4037 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4038 // object's first non-static named data member is zero-initialized
4039 RecordDecl::field_iterator I = RD->field_begin();
4040 if (I == RD->field_end()) {
4041 Result = APValue((const FieldDecl*)0);
4042 return true;
4043 }
4044
4045 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004046 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004047 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004048 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004049 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004050 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004051 }
4052
Richard Smith5d108602012-02-17 00:44:16 +00004053 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004054 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004055 return false;
4056 }
4057
Richard Smitha8105bc2012-01-06 16:39:00 +00004058 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004059}
4060
Richard Smithe97cbd72011-11-11 04:05:33 +00004061bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4062 switch (E->getCastKind()) {
4063 default:
4064 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4065
4066 case CK_ConstructorConversion:
4067 return Visit(E->getSubExpr());
4068
4069 case CK_DerivedToBase:
4070 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004071 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004072 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004073 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004074 if (!DerivedObject.isStruct())
4075 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004076
4077 // Derived-to-base rvalue conversion: just slice off the derived part.
4078 APValue *Value = &DerivedObject;
4079 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4080 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4081 PathE = E->path_end(); PathI != PathE; ++PathI) {
4082 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4083 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4084 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4085 RD = Base;
4086 }
4087 Result = *Value;
4088 return true;
4089 }
4090 }
4091}
4092
Richard Smithd62306a2011-11-10 06:34:14 +00004093bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004094 // Cannot constant-evaluate std::initializer_list inits.
4095 if (E->initializesStdInitializerList())
4096 return false;
4097
Richard Smithd62306a2011-11-10 06:34:14 +00004098 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004099 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004100 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4101
4102 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004103 const FieldDecl *Field = E->getInitializedFieldInUnion();
4104 Result = APValue(Field);
4105 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004106 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004107
4108 // If the initializer list for a union does not contain any elements, the
4109 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004110 // FIXME: The element should be initialized from an initializer list.
4111 // Is this difference ever observable for initializer lists which
4112 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004113 ImplicitValueInitExpr VIE(Field->getType());
4114 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4115
Richard Smithd62306a2011-11-10 06:34:14 +00004116 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004117 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4118 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004119
4120 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4121 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4122 isa<CXXDefaultInitExpr>(InitExpr));
4123
Richard Smithb228a862012-02-15 02:18:13 +00004124 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004125 }
4126
4127 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4128 "initializer list for class with base classes");
4129 Result = APValue(APValue::UninitStruct(), 0,
4130 std::distance(RD->field_begin(), RD->field_end()));
4131 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004132 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004133 for (RecordDecl::field_iterator Field = RD->field_begin(),
4134 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4135 // Anonymous bit-fields are not considered members of the class for
4136 // purposes of aggregate initialization.
4137 if (Field->isUnnamedBitfield())
4138 continue;
4139
4140 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004141
Richard Smith253c2a32012-01-27 01:14:48 +00004142 bool HaveInit = ElementNo < E->getNumInits();
4143
4144 // FIXME: Diagnostics here should point to the end of the initializer
4145 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004146 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004147 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004148 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004149
4150 // Perform an implicit value-initialization for members beyond the end of
4151 // the initializer list.
4152 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004153 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004154
Richard Smith852c9db2013-04-20 22:23:05 +00004155 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4156 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4157 isa<CXXDefaultInitExpr>(Init));
4158
4159 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4160 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004161 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004162 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004163 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004164 }
4165 }
4166
Richard Smith253c2a32012-01-27 01:14:48 +00004167 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004168}
4169
4170bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4171 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004172 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4173
Richard Smithfddd3842011-12-30 21:15:51 +00004174 bool ZeroInit = E->requiresZeroInitialization();
4175 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004176 // If we've already performed zero-initialization, we're already done.
4177 if (!Result.isUninit())
4178 return true;
4179
Richard Smithfddd3842011-12-30 21:15:51 +00004180 if (ZeroInit)
4181 return ZeroInitialization(E);
4182
Richard Smithcc36f692011-12-22 02:22:31 +00004183 const CXXRecordDecl *RD = FD->getParent();
4184 if (RD->isUnion())
4185 Result = APValue((FieldDecl*)0);
4186 else
4187 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4188 std::distance(RD->field_begin(), RD->field_end()));
4189 return true;
4190 }
4191
Richard Smithd62306a2011-11-10 06:34:14 +00004192 const FunctionDecl *Definition = 0;
4193 FD->getBody(Definition);
4194
Richard Smith357362d2011-12-13 06:39:58 +00004195 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4196 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004197
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004198 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004199 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004200 if (const MaterializeTemporaryExpr *ME
4201 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4202 return Visit(ME->GetTemporaryExpr());
4203
Richard Smithfddd3842011-12-30 21:15:51 +00004204 if (ZeroInit && !ZeroInitialization(E))
4205 return false;
4206
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004207 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004208 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004209 cast<CXXConstructorDecl>(Definition), Info,
4210 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004211}
4212
4213static bool EvaluateRecord(const Expr *E, const LValue &This,
4214 APValue &Result, EvalInfo &Info) {
4215 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004216 "can't evaluate expression as a record rvalue");
4217 return RecordExprEvaluator(Info, This, Result).Visit(E);
4218}
4219
4220//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004221// Temporary Evaluation
4222//
4223// Temporaries are represented in the AST as rvalues, but generally behave like
4224// lvalues. The full-object of which the temporary is a subobject is implicitly
4225// materialized so that a reference can bind to it.
4226//===----------------------------------------------------------------------===//
4227namespace {
4228class TemporaryExprEvaluator
4229 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4230public:
4231 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4232 LValueExprEvaluatorBaseTy(Info, Result) {}
4233
4234 /// Visit an expression which constructs the value of this temporary.
4235 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004236 Result.set(E, Info.CurrentCall->Index);
4237 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004238 }
4239
4240 bool VisitCastExpr(const CastExpr *E) {
4241 switch (E->getCastKind()) {
4242 default:
4243 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4244
4245 case CK_ConstructorConversion:
4246 return VisitConstructExpr(E->getSubExpr());
4247 }
4248 }
4249 bool VisitInitListExpr(const InitListExpr *E) {
4250 return VisitConstructExpr(E);
4251 }
4252 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4253 return VisitConstructExpr(E);
4254 }
4255 bool VisitCallExpr(const CallExpr *E) {
4256 return VisitConstructExpr(E);
4257 }
4258};
4259} // end anonymous namespace
4260
4261/// Evaluate an expression of record type as a temporary.
4262static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004263 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004264 return TemporaryExprEvaluator(Info, Result).Visit(E);
4265}
4266
4267//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004268// Vector Evaluation
4269//===----------------------------------------------------------------------===//
4270
4271namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004272 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004273 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4274 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004275 public:
Mike Stump11289f42009-09-09 15:08:12 +00004276
Richard Smith2d406342011-10-22 21:10:00 +00004277 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4278 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004279
Richard Smith2d406342011-10-22 21:10:00 +00004280 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4281 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4282 // FIXME: remove this APValue copy.
4283 Result = APValue(V.data(), V.size());
4284 return true;
4285 }
Richard Smith2e312c82012-03-03 22:46:17 +00004286 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004287 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004288 Result = V;
4289 return true;
4290 }
Richard Smithfddd3842011-12-30 21:15:51 +00004291 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004292
Richard Smith2d406342011-10-22 21:10:00 +00004293 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004294 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004295 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004296 bool VisitInitListExpr(const InitListExpr *E);
4297 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004298 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004299 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004300 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004301 };
4302} // end anonymous namespace
4303
4304static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004305 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004306 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004307}
4308
Richard Smith2d406342011-10-22 21:10:00 +00004309bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4310 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004311 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004312
Richard Smith161f09a2011-12-06 22:44:34 +00004313 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004314 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004315
Eli Friedmanc757de22011-03-25 00:43:55 +00004316 switch (E->getCastKind()) {
4317 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004318 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004319 if (SETy->isIntegerType()) {
4320 APSInt IntResult;
4321 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004322 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004323 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004324 } else if (SETy->isRealFloatingType()) {
4325 APFloat F(0.0);
4326 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004327 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004328 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004329 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004330 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004331 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004332
4333 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004334 SmallVector<APValue, 4> Elts(NElts, Val);
4335 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004336 }
Eli Friedman803acb32011-12-22 03:51:45 +00004337 case CK_BitCast: {
4338 // Evaluate the operand into an APInt we can extract from.
4339 llvm::APInt SValInt;
4340 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4341 return false;
4342 // Extract the elements
4343 QualType EltTy = VTy->getElementType();
4344 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4345 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4346 SmallVector<APValue, 4> Elts;
4347 if (EltTy->isRealFloatingType()) {
4348 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004349 unsigned FloatEltSize = EltSize;
4350 if (&Sem == &APFloat::x87DoubleExtended)
4351 FloatEltSize = 80;
4352 for (unsigned i = 0; i < NElts; i++) {
4353 llvm::APInt Elt;
4354 if (BigEndian)
4355 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4356 else
4357 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004358 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004359 }
4360 } else if (EltTy->isIntegerType()) {
4361 for (unsigned i = 0; i < NElts; i++) {
4362 llvm::APInt Elt;
4363 if (BigEndian)
4364 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4365 else
4366 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4367 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4368 }
4369 } else {
4370 return Error(E);
4371 }
4372 return Success(Elts, E);
4373 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004374 default:
Richard Smith11562c52011-10-28 17:51:58 +00004375 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004376 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004377}
4378
Richard Smith2d406342011-10-22 21:10:00 +00004379bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004380VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004381 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004382 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004383 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004384
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004385 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004386 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004387
Eli Friedmanb9c71292012-01-03 23:24:20 +00004388 // The number of initializers can be less than the number of
4389 // vector elements. For OpenCL, this can be due to nested vector
4390 // initialization. For GCC compatibility, missing trailing elements
4391 // should be initialized with zeroes.
4392 unsigned CountInits = 0, CountElts = 0;
4393 while (CountElts < NumElements) {
4394 // Handle nested vector initialization.
4395 if (CountInits < NumInits
4396 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4397 APValue v;
4398 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4399 return Error(E);
4400 unsigned vlen = v.getVectorLength();
4401 for (unsigned j = 0; j < vlen; j++)
4402 Elements.push_back(v.getVectorElt(j));
4403 CountElts += vlen;
4404 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004405 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004406 if (CountInits < NumInits) {
4407 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004408 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004409 } else // trailing integer zero.
4410 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4411 Elements.push_back(APValue(sInt));
4412 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004413 } else {
4414 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004415 if (CountInits < NumInits) {
4416 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004417 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004418 } else // trailing float zero.
4419 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4420 Elements.push_back(APValue(f));
4421 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004422 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004423 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004424 }
Richard Smith2d406342011-10-22 21:10:00 +00004425 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004426}
4427
Richard Smith2d406342011-10-22 21:10:00 +00004428bool
Richard Smithfddd3842011-12-30 21:15:51 +00004429VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004430 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004431 QualType EltTy = VT->getElementType();
4432 APValue ZeroElement;
4433 if (EltTy->isIntegerType())
4434 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4435 else
4436 ZeroElement =
4437 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4438
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004439 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004440 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004441}
4442
Richard Smith2d406342011-10-22 21:10:00 +00004443bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004444 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004445 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004446}
4447
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004448//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004449// Array Evaluation
4450//===----------------------------------------------------------------------===//
4451
4452namespace {
4453 class ArrayExprEvaluator
4454 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004455 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004456 APValue &Result;
4457 public:
4458
Richard Smithd62306a2011-11-10 06:34:14 +00004459 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4460 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004461
4462 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004463 assert((V.isArray() || V.isLValue()) &&
4464 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004465 Result = V;
4466 return true;
4467 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004468
Richard Smithfddd3842011-12-30 21:15:51 +00004469 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004470 const ConstantArrayType *CAT =
4471 Info.Ctx.getAsConstantArrayType(E->getType());
4472 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004473 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004474
4475 Result = APValue(APValue::UninitArray(), 0,
4476 CAT->getSize().getZExtValue());
4477 if (!Result.hasArrayFiller()) return true;
4478
Richard Smithfddd3842011-12-30 21:15:51 +00004479 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004480 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004481 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004482 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004483 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004484 }
4485
Richard Smithf3e9e432011-11-07 09:22:26 +00004486 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004487 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004488 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4489 const LValue &Subobject,
4490 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004491 };
4492} // end anonymous namespace
4493
Richard Smithd62306a2011-11-10 06:34:14 +00004494static bool EvaluateArray(const Expr *E, const LValue &This,
4495 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004496 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004497 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004498}
4499
4500bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4501 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4502 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004503 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004504
Richard Smithca2cfbf2011-12-22 01:07:19 +00004505 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4506 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004507 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004508 LValue LV;
4509 if (!EvaluateLValue(E->getInit(0), LV, Info))
4510 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004511 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004512 LV.moveInto(Val);
4513 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004514 }
4515
Richard Smith253c2a32012-01-27 01:14:48 +00004516 bool Success = true;
4517
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004518 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4519 "zero-initialized array shouldn't have any initialized elts");
4520 APValue Filler;
4521 if (Result.isArray() && Result.hasArrayFiller())
4522 Filler = Result.getArrayFiller();
4523
Richard Smith9543c5e2013-04-22 14:44:29 +00004524 unsigned NumEltsToInit = E->getNumInits();
4525 unsigned NumElts = CAT->getSize().getZExtValue();
4526 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4527
4528 // If the initializer might depend on the array index, run it for each
4529 // array element. For now, just whitelist non-class value-initialization.
4530 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4531 NumEltsToInit = NumElts;
4532
4533 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004534
4535 // If the array was previously zero-initialized, preserve the
4536 // zero-initialized values.
4537 if (!Filler.isUninit()) {
4538 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4539 Result.getArrayInitializedElt(I) = Filler;
4540 if (Result.hasArrayFiller())
4541 Result.getArrayFiller() = Filler;
4542 }
4543
Richard Smithd62306a2011-11-10 06:34:14 +00004544 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004545 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004546 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4547 const Expr *Init =
4548 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00004549 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00004550 Info, Subobject, Init) ||
4551 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00004552 CAT->getElementType(), 1)) {
4553 if (!Info.keepEvaluatingAfterFailure())
4554 return false;
4555 Success = false;
4556 }
Richard Smithd62306a2011-11-10 06:34:14 +00004557 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004558
Richard Smith9543c5e2013-04-22 14:44:29 +00004559 if (!Result.hasArrayFiller())
4560 return Success;
4561
4562 // If we get here, we have a trivial filler, which we can just evaluate
4563 // once and splat over the rest of the array elements.
4564 assert(FillerExpr && "no array filler for incomplete init list");
4565 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4566 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00004567}
4568
Richard Smith027bf112011-11-17 22:56:20 +00004569bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004570 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4571}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004572
Richard Smith9543c5e2013-04-22 14:44:29 +00004573bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4574 const LValue &Subobject,
4575 APValue *Value,
4576 QualType Type) {
4577 bool HadZeroInit = !Value->isUninit();
4578
4579 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4580 unsigned N = CAT->getSize().getZExtValue();
4581
4582 // Preserve the array filler if we had prior zero-initialization.
4583 APValue Filler =
4584 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4585 : APValue();
4586
4587 *Value = APValue(APValue::UninitArray(), N, N);
4588
4589 if (HadZeroInit)
4590 for (unsigned I = 0; I != N; ++I)
4591 Value->getArrayInitializedElt(I) = Filler;
4592
4593 // Initialize the elements.
4594 LValue ArrayElt = Subobject;
4595 ArrayElt.addArray(Info, E, CAT);
4596 for (unsigned I = 0; I != N; ++I)
4597 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4598 CAT->getElementType()) ||
4599 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4600 CAT->getElementType(), 1))
4601 return false;
4602
4603 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004604 }
Richard Smith027bf112011-11-17 22:56:20 +00004605
Richard Smith9543c5e2013-04-22 14:44:29 +00004606 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004607 return Error(E);
4608
Richard Smith027bf112011-11-17 22:56:20 +00004609 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004610
Richard Smithfddd3842011-12-30 21:15:51 +00004611 bool ZeroInit = E->requiresZeroInitialization();
4612 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004613 if (HadZeroInit)
4614 return true;
4615
Richard Smithfddd3842011-12-30 21:15:51 +00004616 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004617 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004618 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004619 }
4620
Richard Smithcc36f692011-12-22 02:22:31 +00004621 const CXXRecordDecl *RD = FD->getParent();
4622 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004623 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004624 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004625 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004626 APValue(APValue::UninitStruct(), RD->getNumBases(),
4627 std::distance(RD->field_begin(), RD->field_end()));
4628 return true;
4629 }
4630
Richard Smith027bf112011-11-17 22:56:20 +00004631 const FunctionDecl *Definition = 0;
4632 FD->getBody(Definition);
4633
Richard Smith357362d2011-12-13 06:39:58 +00004634 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4635 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004636
Richard Smith9eae7232012-01-12 18:54:33 +00004637 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004638 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004639 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004640 return false;
4641 }
4642
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004643 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004644 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004645 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004646 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004647}
4648
Richard Smithf3e9e432011-11-07 09:22:26 +00004649//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004650// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004651//
4652// As a GNU extension, we support casting pointers to sufficiently-wide integer
4653// types and back in constant folding. Integer values are thus represented
4654// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004655//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004656
4657namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004658class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004659 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004660 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004661public:
Richard Smith2e312c82012-03-03 22:46:17 +00004662 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004663 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004664
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004665 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004666 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004667 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004668 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004669 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004670 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004671 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004672 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004673 return true;
4674 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004675 bool Success(const llvm::APSInt &SI, const Expr *E) {
4676 return Success(SI, E, Result);
4677 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004678
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004679 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004680 assert(E->getType()->isIntegralOrEnumerationType() &&
4681 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004682 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004683 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004684 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004685 Result.getInt().setIsUnsigned(
4686 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004687 return true;
4688 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004689 bool Success(const llvm::APInt &I, const Expr *E) {
4690 return Success(I, E, Result);
4691 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004692
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004693 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004694 assert(E->getType()->isIntegralOrEnumerationType() &&
4695 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004696 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004697 return true;
4698 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004699 bool Success(uint64_t Value, const Expr *E) {
4700 return Success(Value, E, Result);
4701 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004702
Ken Dyckdbc01912011-03-11 02:13:43 +00004703 bool Success(CharUnits Size, const Expr *E) {
4704 return Success(Size.getQuantity(), E);
4705 }
4706
Richard Smith2e312c82012-03-03 22:46:17 +00004707 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004708 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00004709 Result = V;
4710 return true;
4711 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004712 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004713 }
Mike Stump11289f42009-09-09 15:08:12 +00004714
Richard Smithfddd3842011-12-30 21:15:51 +00004715 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00004716
Peter Collingbournee9200682011-05-13 03:29:01 +00004717 //===--------------------------------------------------------------------===//
4718 // Visitor Methods
4719 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004720
Chris Lattner7174bf32008-07-12 00:38:25 +00004721 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004722 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004723 }
4724 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004725 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004726 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004727
4728 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4729 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004730 if (CheckReferencedDecl(E, E->getDecl()))
4731 return true;
4732
4733 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004734 }
4735 bool VisitMemberExpr(const MemberExpr *E) {
4736 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004737 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004738 return true;
4739 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004740
4741 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004742 }
4743
Peter Collingbournee9200682011-05-13 03:29:01 +00004744 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004745 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004746 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004747 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004748
Peter Collingbournee9200682011-05-13 03:29:01 +00004749 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004750 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004751
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004752 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004753 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004754 }
Mike Stump11289f42009-09-09 15:08:12 +00004755
Ted Kremeneke65b0862012-03-06 20:05:56 +00004756 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4757 return Success(E->getValue(), E);
4758 }
4759
Richard Smith4ce706a2011-10-11 21:43:33 +00004760 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004761 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004762 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004763 }
4764
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004765 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004766 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004767 }
4768
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004769 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4770 return Success(E->getValue(), E);
4771 }
4772
Douglas Gregor29c42f22012-02-24 07:38:34 +00004773 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4774 return Success(E->getValue(), E);
4775 }
4776
John Wiegley6242b6a2011-04-28 00:16:57 +00004777 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4778 return Success(E->getValue(), E);
4779 }
4780
John Wiegleyf9f65842011-04-25 06:54:41 +00004781 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4782 return Success(E->getValue(), E);
4783 }
4784
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004785 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004786 bool VisitUnaryImag(const UnaryOperator *E);
4787
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004788 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004789 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004790
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004791private:
Ken Dyck160146e2010-01-27 17:10:57 +00004792 CharUnits GetAlignOfExpr(const Expr *E);
4793 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004794 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004795 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004796 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004797};
Chris Lattner05706e882008-07-11 18:11:29 +00004798} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004799
Richard Smith11562c52011-10-28 17:51:58 +00004800/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4801/// produce either the integer value or a pointer.
4802///
4803/// GCC has a heinous extension which folds casts between pointer types and
4804/// pointer-sized integral types. We support this by allowing the evaluation of
4805/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4806/// Some simple arithmetic on such values is supported (they are treated much
4807/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004808static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004809 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004810 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004811 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004812}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004813
Richard Smithf57d8cb2011-12-09 22:58:01 +00004814static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004815 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004816 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004817 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004818 if (!Val.isInt()) {
4819 // FIXME: It would be better to produce the diagnostic for casting
4820 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004821 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004822 return false;
4823 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004824 Result = Val.getInt();
4825 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004826}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004827
Richard Smithf57d8cb2011-12-09 22:58:01 +00004828/// Check whether the given declaration can be directly converted to an integral
4829/// rvalue. If not, no diagnostic is produced; there are other things we can
4830/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004831bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004832 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004833 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004834 // Check for signedness/width mismatches between E type and ECD value.
4835 bool SameSign = (ECD->getInitVal().isSigned()
4836 == E->getType()->isSignedIntegerOrEnumerationType());
4837 bool SameWidth = (ECD->getInitVal().getBitWidth()
4838 == Info.Ctx.getIntWidth(E->getType()));
4839 if (SameSign && SameWidth)
4840 return Success(ECD->getInitVal(), E);
4841 else {
4842 // Get rid of mismatch (otherwise Success assertions will fail)
4843 // by computing a new value matching the type of E.
4844 llvm::APSInt Val = ECD->getInitVal();
4845 if (!SameSign)
4846 Val.setIsSigned(!ECD->getInitVal().isSigned());
4847 if (!SameWidth)
4848 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4849 return Success(Val, E);
4850 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004851 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004852 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004853}
4854
Chris Lattner86ee2862008-10-06 06:40:35 +00004855/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4856/// as GCC.
4857static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4858 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004859 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004860 enum gcc_type_class {
4861 no_type_class = -1,
4862 void_type_class, integer_type_class, char_type_class,
4863 enumeral_type_class, boolean_type_class,
4864 pointer_type_class, reference_type_class, offset_type_class,
4865 real_type_class, complex_type_class,
4866 function_type_class, method_type_class,
4867 record_type_class, union_type_class,
4868 array_type_class, string_type_class,
4869 lang_type_class
4870 };
Mike Stump11289f42009-09-09 15:08:12 +00004871
4872 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004873 // ideal, however it is what gcc does.
4874 if (E->getNumArgs() == 0)
4875 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004876
Chris Lattner86ee2862008-10-06 06:40:35 +00004877 QualType ArgTy = E->getArg(0)->getType();
4878 if (ArgTy->isVoidType())
4879 return void_type_class;
4880 else if (ArgTy->isEnumeralType())
4881 return enumeral_type_class;
4882 else if (ArgTy->isBooleanType())
4883 return boolean_type_class;
4884 else if (ArgTy->isCharType())
4885 return string_type_class; // gcc doesn't appear to use char_type_class
4886 else if (ArgTy->isIntegerType())
4887 return integer_type_class;
4888 else if (ArgTy->isPointerType())
4889 return pointer_type_class;
4890 else if (ArgTy->isReferenceType())
4891 return reference_type_class;
4892 else if (ArgTy->isRealType())
4893 return real_type_class;
4894 else if (ArgTy->isComplexType())
4895 return complex_type_class;
4896 else if (ArgTy->isFunctionType())
4897 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004898 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004899 return record_type_class;
4900 else if (ArgTy->isUnionType())
4901 return union_type_class;
4902 else if (ArgTy->isArrayType())
4903 return array_type_class;
4904 else if (ArgTy->isUnionType())
4905 return union_type_class;
4906 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004907 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004908}
4909
Richard Smith5fab0c92011-12-28 19:48:30 +00004910/// EvaluateBuiltinConstantPForLValue - Determine the result of
4911/// __builtin_constant_p when applied to the given lvalue.
4912///
4913/// An lvalue is only "constant" if it is a pointer or reference to the first
4914/// character of a string literal.
4915template<typename LValue>
4916static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004917 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004918 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4919}
4920
4921/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4922/// GCC as we can manage.
4923static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4924 QualType ArgType = Arg->getType();
4925
4926 // __builtin_constant_p always has one operand. The rules which gcc follows
4927 // are not precisely documented, but are as follows:
4928 //
4929 // - If the operand is of integral, floating, complex or enumeration type,
4930 // and can be folded to a known value of that type, it returns 1.
4931 // - If the operand and can be folded to a pointer to the first character
4932 // of a string literal (or such a pointer cast to an integral type), it
4933 // returns 1.
4934 //
4935 // Otherwise, it returns 0.
4936 //
4937 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4938 // its support for this does not currently work.
4939 if (ArgType->isIntegralOrEnumerationType()) {
4940 Expr::EvalResult Result;
4941 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4942 return false;
4943
4944 APValue &V = Result.Val;
4945 if (V.getKind() == APValue::Int)
4946 return true;
4947
4948 return EvaluateBuiltinConstantPForLValue(V);
4949 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4950 return Arg->isEvaluatable(Ctx);
4951 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4952 LValue LV;
4953 Expr::EvalStatus Status;
4954 EvalInfo Info(Ctx, Status);
4955 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4956 : EvaluatePointer(Arg, LV, Info)) &&
4957 !Status.HasSideEffects)
4958 return EvaluateBuiltinConstantPForLValue(LV);
4959 }
4960
4961 // Anything else isn't considered to be sufficiently constant.
4962 return false;
4963}
4964
John McCall95007602010-05-10 23:27:23 +00004965/// Retrieves the "underlying object type" of the given expression,
4966/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004967QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4968 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4969 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004970 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004971 } else if (const Expr *E = B.get<const Expr*>()) {
4972 if (isa<CompoundLiteralExpr>(E))
4973 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004974 }
4975
4976 return QualType();
4977}
4978
Peter Collingbournee9200682011-05-13 03:29:01 +00004979bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004980 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004981
4982 {
4983 // The operand of __builtin_object_size is never evaluated for side-effects.
4984 // If there are any, but we can determine the pointed-to object anyway, then
4985 // ignore the side-effects.
4986 SpeculativeEvaluationRAII SpeculativeEval(Info);
4987 if (!EvaluatePointer(E->getArg(0), Base, Info))
4988 return false;
4989 }
John McCall95007602010-05-10 23:27:23 +00004990
4991 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004992 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004993
Richard Smithce40ad62011-11-12 22:28:03 +00004994 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004995 if (T.isNull() ||
4996 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004997 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004998 T->isVariablyModifiedType() ||
4999 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005000 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005001
5002 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5003 CharUnits Offset = Base.getLValueOffset();
5004
5005 if (!Offset.isNegative() && Offset <= Size)
5006 Size -= Offset;
5007 else
5008 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005009 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005010}
5011
Peter Collingbournee9200682011-05-13 03:29:01 +00005012bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005013 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005014 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005015 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005016
5017 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005018 if (TryEvaluateBuiltinObjectSize(E))
5019 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005020
Richard Smith0421ce72012-08-07 04:16:51 +00005021 // If evaluating the argument has side-effects, we can't determine the size
5022 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5023 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005024 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005025 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005026 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005027 return Success(0, E);
5028 }
Mike Stump876387b2009-10-27 22:09:17 +00005029
Richard Smith01ade172012-05-23 04:13:20 +00005030 // Expression had no side effects, but we couldn't statically determine the
5031 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005032 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005033 }
5034
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005035 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005036 case Builtin::BI__builtin_bswap32:
5037 case Builtin::BI__builtin_bswap64: {
5038 APSInt Val;
5039 if (!EvaluateInteger(E->getArg(0), Val, Info))
5040 return false;
5041
5042 return Success(Val.byteSwap(), E);
5043 }
5044
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005045 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005046 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005047
Richard Smith5fab0c92011-12-28 19:48:30 +00005048 case Builtin::BI__builtin_constant_p:
5049 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005050
Chris Lattnerd545ad12009-09-23 06:06:36 +00005051 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005052 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005053 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005054 return Success(Operand, E);
5055 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005056
5057 case Builtin::BI__builtin_expect:
5058 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005059
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005060 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005061 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005062 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005063 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005064 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5065 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005066 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005067 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005068 case Builtin::BI__builtin_strlen:
5069 // As an extension, we support strlen() and __builtin_strlen() as constant
5070 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005071 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005072 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5073 // The string literal may have embedded null characters. Find the first
5074 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005075 StringRef Str = S->getString();
5076 StringRef::size_type Pos = Str.find(0);
5077 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005078 Str = Str.substr(0, Pos);
5079
5080 return Success(Str.size(), E);
5081 }
5082
Richard Smithf57d8cb2011-12-09 22:58:01 +00005083 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005084
Richard Smith01ba47d2012-04-13 00:45:38 +00005085 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005086 case Builtin::BI__atomic_is_lock_free:
5087 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005088 APSInt SizeVal;
5089 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5090 return false;
5091
5092 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5093 // of two less than the maximum inline atomic width, we know it is
5094 // lock-free. If the size isn't a power of two, or greater than the
5095 // maximum alignment where we promote atomics, we know it is not lock-free
5096 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5097 // the answer can only be determined at runtime; for example, 16-byte
5098 // atomics have lock-free implementations on some, but not all,
5099 // x86-64 processors.
5100
5101 // Check power-of-two.
5102 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005103 if (Size.isPowerOfTwo()) {
5104 // Check against inlining width.
5105 unsigned InlineWidthBits =
5106 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5107 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5108 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5109 Size == CharUnits::One() ||
5110 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5111 Expr::NPC_NeverValueDependent))
5112 // OK, we will inline appropriately-aligned operations of this size,
5113 // and _Atomic(T) is appropriately-aligned.
5114 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005115
Richard Smith01ba47d2012-04-13 00:45:38 +00005116 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5117 castAs<PointerType>()->getPointeeType();
5118 if (!PointeeType->isIncompleteType() &&
5119 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5120 // OK, we will inline operations on this object.
5121 return Success(1, E);
5122 }
5123 }
5124 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005125
Richard Smith01ba47d2012-04-13 00:45:38 +00005126 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5127 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005128 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005129 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005130}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005131
Richard Smith8b3497e2011-10-31 01:37:14 +00005132static bool HasSameBase(const LValue &A, const LValue &B) {
5133 if (!A.getLValueBase())
5134 return !B.getLValueBase();
5135 if (!B.getLValueBase())
5136 return false;
5137
Richard Smithce40ad62011-11-12 22:28:03 +00005138 if (A.getLValueBase().getOpaqueValue() !=
5139 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005140 const Decl *ADecl = GetLValueBaseDecl(A);
5141 if (!ADecl)
5142 return false;
5143 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005144 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005145 return false;
5146 }
5147
5148 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005149 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005150}
5151
Richard Smithc8042322012-02-01 05:53:12 +00005152/// Perform the given integer operation, which is known to need at most BitWidth
5153/// bits, and check for overflow in the original type (if that type was not an
5154/// unsigned type).
5155template<typename Operation>
5156static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
5157 const APSInt &LHS, const APSInt &RHS,
5158 unsigned BitWidth, Operation Op) {
5159 if (LHS.isUnsigned())
5160 return Op(LHS, RHS);
5161
5162 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
5163 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005164 if (Result.extend(BitWidth) != Value) {
5165 if (Info.getIntOverflowCheckMode())
5166 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
5167 diag::warn_integer_constant_overflow)
5168 << Result.toString(10) << E->getType();
5169 else
5170 HandleOverflow(Info, E, Value, E->getType());
5171 }
Richard Smithc8042322012-02-01 05:53:12 +00005172 return Result;
5173}
5174
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005175namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005176
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005177/// \brief Data recursive integer evaluator of certain binary operators.
5178///
5179/// We use a data recursive algorithm for binary operators so that we are able
5180/// to handle extreme cases of chained binary operators without causing stack
5181/// overflow.
5182class DataRecursiveIntBinOpEvaluator {
5183 struct EvalResult {
5184 APValue Val;
5185 bool Failed;
5186
5187 EvalResult() : Failed(false) { }
5188
5189 void swap(EvalResult &RHS) {
5190 Val.swap(RHS.Val);
5191 Failed = RHS.Failed;
5192 RHS.Failed = false;
5193 }
5194 };
5195
5196 struct Job {
5197 const Expr *E;
5198 EvalResult LHSResult; // meaningful only for binary operator expression.
5199 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5200
5201 Job() : StoredInfo(0) { }
5202 void startSpeculativeEval(EvalInfo &Info) {
5203 OldEvalStatus = Info.EvalStatus;
5204 Info.EvalStatus.Diag = 0;
5205 StoredInfo = &Info;
5206 }
5207 ~Job() {
5208 if (StoredInfo) {
5209 StoredInfo->EvalStatus = OldEvalStatus;
5210 }
5211 }
5212 private:
5213 EvalInfo *StoredInfo; // non-null if status changed.
5214 Expr::EvalStatus OldEvalStatus;
5215 };
5216
5217 SmallVector<Job, 16> Queue;
5218
5219 IntExprEvaluator &IntEval;
5220 EvalInfo &Info;
5221 APValue &FinalResult;
5222
5223public:
5224 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5225 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5226
5227 /// \brief True if \param E is a binary operator that we are going to handle
5228 /// data recursively.
5229 /// We handle binary operators that are comma, logical, or that have operands
5230 /// with integral or enumeration type.
5231 static bool shouldEnqueue(const BinaryOperator *E) {
5232 return E->getOpcode() == BO_Comma ||
5233 E->isLogicalOp() ||
5234 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5235 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005236 }
5237
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005238 bool Traverse(const BinaryOperator *E) {
5239 enqueue(E);
5240 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005241 while (!Queue.empty())
5242 process(PrevResult);
5243
5244 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005245
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005246 FinalResult.swap(PrevResult.Val);
5247 return true;
5248 }
5249
5250private:
5251 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5252 return IntEval.Success(Value, E, Result);
5253 }
5254 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5255 return IntEval.Success(Value, E, Result);
5256 }
5257 bool Error(const Expr *E) {
5258 return IntEval.Error(E);
5259 }
5260 bool Error(const Expr *E, diag::kind D) {
5261 return IntEval.Error(E, D);
5262 }
5263
5264 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5265 return Info.CCEDiag(E, D);
5266 }
5267
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005268 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5269 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005270 bool &SuppressRHSDiags);
5271
5272 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5273 const BinaryOperator *E, APValue &Result);
5274
5275 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5276 Result.Failed = !Evaluate(Result.Val, Info, E);
5277 if (Result.Failed)
5278 Result.Val = APValue();
5279 }
5280
Richard Trieuba4d0872012-03-21 23:30:30 +00005281 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005282
5283 void enqueue(const Expr *E) {
5284 E = E->IgnoreParens();
5285 Queue.resize(Queue.size()+1);
5286 Queue.back().E = E;
5287 Queue.back().Kind = Job::AnyExprKind;
5288 }
5289};
5290
5291}
5292
5293bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005294 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005295 bool &SuppressRHSDiags) {
5296 if (E->getOpcode() == BO_Comma) {
5297 // Ignore LHS but note if we could not evaluate it.
5298 if (LHSResult.Failed)
5299 Info.EvalStatus.HasSideEffects = true;
5300 return true;
5301 }
5302
5303 if (E->isLogicalOp()) {
5304 bool lhsResult;
5305 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005306 // We were able to evaluate the LHS, see if we can get away with not
5307 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005308 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005309 Success(lhsResult, E, LHSResult.Val);
5310 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005311 }
5312 } else {
5313 // Since we weren't able to evaluate the left hand side, it
5314 // must have had side effects.
5315 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005316
5317 // We can't evaluate the LHS; however, sometimes the result
5318 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5319 // Don't ignore RHS and suppress diagnostics from this arm.
5320 SuppressRHSDiags = true;
5321 }
5322
5323 return true;
5324 }
5325
5326 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5327 E->getRHS()->getType()->isIntegralOrEnumerationType());
5328
5329 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005330 return false; // Ignore RHS;
5331
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005332 return true;
5333}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005334
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005335bool DataRecursiveIntBinOpEvaluator::
5336 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5337 const BinaryOperator *E, APValue &Result) {
5338 if (E->getOpcode() == BO_Comma) {
5339 if (RHSResult.Failed)
5340 return false;
5341 Result = RHSResult.Val;
5342 return true;
5343 }
5344
5345 if (E->isLogicalOp()) {
5346 bool lhsResult, rhsResult;
5347 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5348 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5349
5350 if (LHSIsOK) {
5351 if (RHSIsOK) {
5352 if (E->getOpcode() == BO_LOr)
5353 return Success(lhsResult || rhsResult, E, Result);
5354 else
5355 return Success(lhsResult && rhsResult, E, Result);
5356 }
5357 } else {
5358 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005359 // We can't evaluate the LHS; however, sometimes the result
5360 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5361 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005362 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005363 }
5364 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005365
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005366 return false;
5367 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005368
5369 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5370 E->getRHS()->getType()->isIntegralOrEnumerationType());
5371
5372 if (LHSResult.Failed || RHSResult.Failed)
5373 return false;
5374
5375 const APValue &LHSVal = LHSResult.Val;
5376 const APValue &RHSVal = RHSResult.Val;
5377
5378 // Handle cases like (unsigned long)&a + 4.
5379 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5380 Result = LHSVal;
5381 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5382 RHSVal.getInt().getZExtValue());
5383 if (E->getOpcode() == BO_Add)
5384 Result.getLValueOffset() += AdditionalOffset;
5385 else
5386 Result.getLValueOffset() -= AdditionalOffset;
5387 return true;
5388 }
5389
5390 // Handle cases like 4 + (unsigned long)&a
5391 if (E->getOpcode() == BO_Add &&
5392 RHSVal.isLValue() && LHSVal.isInt()) {
5393 Result = RHSVal;
5394 Result.getLValueOffset() += CharUnits::fromQuantity(
5395 LHSVal.getInt().getZExtValue());
5396 return true;
5397 }
5398
5399 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5400 // Handle (intptr_t)&&A - (intptr_t)&&B.
5401 if (!LHSVal.getLValueOffset().isZero() ||
5402 !RHSVal.getLValueOffset().isZero())
5403 return false;
5404 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5405 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5406 if (!LHSExpr || !RHSExpr)
5407 return false;
5408 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5409 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5410 if (!LHSAddrExpr || !RHSAddrExpr)
5411 return false;
5412 // Make sure both labels come from the same function.
5413 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5414 RHSAddrExpr->getLabel()->getDeclContext())
5415 return false;
5416 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5417 return true;
5418 }
5419
5420 // All the following cases expect both operands to be an integer
5421 if (!LHSVal.isInt() || !RHSVal.isInt())
5422 return Error(E);
5423
5424 const APSInt &LHS = LHSVal.getInt();
5425 APSInt RHS = RHSVal.getInt();
5426
5427 switch (E->getOpcode()) {
5428 default:
5429 return Error(E);
5430 case BO_Mul:
5431 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5432 LHS.getBitWidth() * 2,
5433 std::multiplies<APSInt>()), E,
5434 Result);
5435 case BO_Add:
5436 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5437 LHS.getBitWidth() + 1,
5438 std::plus<APSInt>()), E, Result);
5439 case BO_Sub:
5440 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5441 LHS.getBitWidth() + 1,
5442 std::minus<APSInt>()), E, Result);
5443 case BO_And: return Success(LHS & RHS, E, Result);
5444 case BO_Xor: return Success(LHS ^ RHS, E, Result);
5445 case BO_Or: return Success(LHS | RHS, E, Result);
5446 case BO_Div:
5447 case BO_Rem:
5448 if (RHS == 0)
5449 return Error(E, diag::note_expr_divide_by_zero);
5450 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
5451 // not actually undefined behavior in C++11 due to a language defect.
5452 if (RHS.isNegative() && RHS.isAllOnesValue() &&
5453 LHS.isSigned() && LHS.isMinSignedValue())
5454 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
5455 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
5456 Result);
5457 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00005458 if (Info.getLangOpts().OpenCL)
5459 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005460 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005461 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5462 RHS.isUnsigned());
5463 else if (RHS.isSigned() && RHS.isNegative()) {
5464 // During constant-folding, a negative shift is an opposite shift. Such
5465 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005466 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5467 RHS = -RHS;
5468 goto shift_right;
5469 }
5470
5471 shift_left:
5472 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
5473 // the shifted type.
5474 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5475 if (SA != RHS) {
5476 CCEDiag(E, diag::note_constexpr_large_shift)
5477 << RHS << E->getType() << LHS.getBitWidth();
5478 } else if (LHS.isSigned()) {
5479 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
5480 // operand, and must not overflow the corresponding unsigned type.
5481 if (LHS.isNegative())
5482 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
5483 else if (LHS.countLeadingZeros() < SA)
5484 CCEDiag(E, diag::note_constexpr_lshift_discards);
5485 }
5486
5487 return Success(LHS << SA, E, Result);
5488 }
5489 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00005490 if (Info.getLangOpts().OpenCL)
5491 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005492 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005493 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5494 RHS.isUnsigned());
5495 else if (RHS.isSigned() && RHS.isNegative()) {
5496 // During constant-folding, a negative shift is an opposite shift. Such a
5497 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005498 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5499 RHS = -RHS;
5500 goto shift_left;
5501 }
5502
5503 shift_right:
5504 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
5505 // shifted type.
5506 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5507 if (SA != RHS)
5508 CCEDiag(E, diag::note_constexpr_large_shift)
5509 << RHS << E->getType() << LHS.getBitWidth();
5510
5511 return Success(LHS >> SA, E, Result);
5512 }
5513
5514 case BO_LT: return Success(LHS < RHS, E, Result);
5515 case BO_GT: return Success(LHS > RHS, E, Result);
5516 case BO_LE: return Success(LHS <= RHS, E, Result);
5517 case BO_GE: return Success(LHS >= RHS, E, Result);
5518 case BO_EQ: return Success(LHS == RHS, E, Result);
5519 case BO_NE: return Success(LHS != RHS, E, Result);
5520 }
5521}
5522
Richard Trieuba4d0872012-03-21 23:30:30 +00005523void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005524 Job &job = Queue.back();
5525
5526 switch (job.Kind) {
5527 case Job::AnyExprKind: {
5528 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5529 if (shouldEnqueue(Bop)) {
5530 job.Kind = Job::BinOpKind;
5531 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005532 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005533 }
5534 }
5535
5536 EvaluateExpr(job.E, Result);
5537 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005538 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005539 }
5540
5541 case Job::BinOpKind: {
5542 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005543 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005544 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005545 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005546 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005547 }
5548 if (SuppressRHSDiags)
5549 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005550 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005551 job.Kind = Job::BinOpVisitedLHSKind;
5552 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005553 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005554 }
5555
5556 case Job::BinOpVisitedLHSKind: {
5557 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5558 EvalResult RHS;
5559 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005560 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005561 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005562 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005563 }
5564 }
5565
5566 llvm_unreachable("Invalid Job::Kind!");
5567}
5568
5569bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5570 if (E->isAssignmentOp())
5571 return Error(E);
5572
5573 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5574 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005575
Anders Carlssonacc79812008-11-16 07:17:21 +00005576 QualType LHSTy = E->getLHS()->getType();
5577 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005578
5579 if (LHSTy->isAnyComplexType()) {
5580 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005581 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005582
Richard Smith253c2a32012-01-27 01:14:48 +00005583 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5584 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005585 return false;
5586
Richard Smith253c2a32012-01-27 01:14:48 +00005587 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005588 return false;
5589
5590 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005591 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005592 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005593 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005594 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5595
John McCalle3027922010-08-25 11:45:40 +00005596 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005597 return Success((CR_r == APFloat::cmpEqual &&
5598 CR_i == APFloat::cmpEqual), E);
5599 else {
John McCalle3027922010-08-25 11:45:40 +00005600 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005601 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005602 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005603 CR_r == APFloat::cmpLessThan ||
5604 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005605 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005606 CR_i == APFloat::cmpLessThan ||
5607 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005608 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005609 } else {
John McCalle3027922010-08-25 11:45:40 +00005610 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005611 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5612 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5613 else {
John McCalle3027922010-08-25 11:45:40 +00005614 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005615 "Invalid compex comparison.");
5616 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5617 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5618 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005619 }
5620 }
Mike Stump11289f42009-09-09 15:08:12 +00005621
Anders Carlssonacc79812008-11-16 07:17:21 +00005622 if (LHSTy->isRealFloatingType() &&
5623 RHSTy->isRealFloatingType()) {
5624 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005625
Richard Smith253c2a32012-01-27 01:14:48 +00005626 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5627 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005628 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005629
Richard Smith253c2a32012-01-27 01:14:48 +00005630 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005631 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005632
Anders Carlssonacc79812008-11-16 07:17:21 +00005633 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005634
Anders Carlssonacc79812008-11-16 07:17:21 +00005635 switch (E->getOpcode()) {
5636 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005637 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005638 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005639 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005640 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005641 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005642 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005643 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005644 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005645 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005646 E);
John McCalle3027922010-08-25 11:45:40 +00005647 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005648 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005649 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005650 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005651 || CR == APFloat::cmpLessThan
5652 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005653 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005654 }
Mike Stump11289f42009-09-09 15:08:12 +00005655
Eli Friedmana38da572009-04-28 19:17:36 +00005656 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005657 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005658 LValue LHSValue, RHSValue;
5659
5660 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5661 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005662 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005663
Richard Smith253c2a32012-01-27 01:14:48 +00005664 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005665 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005666
Richard Smith8b3497e2011-10-31 01:37:14 +00005667 // Reject differing bases from the normal codepath; we special-case
5668 // comparisons to null.
5669 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005670 if (E->getOpcode() == BO_Sub) {
5671 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005672 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5673 return false;
5674 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005675 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005676 if (!LHSExpr || !RHSExpr)
5677 return false;
5678 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5679 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5680 if (!LHSAddrExpr || !RHSAddrExpr)
5681 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005682 // Make sure both labels come from the same function.
5683 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5684 RHSAddrExpr->getLabel()->getDeclContext())
5685 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005686 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005687 return true;
5688 }
Richard Smith83c68212011-10-31 05:11:32 +00005689 // Inequalities and subtractions between unrelated pointers have
5690 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005691 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005692 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005693 // A constant address may compare equal to the address of a symbol.
5694 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005695 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005696 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5697 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005698 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005699 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005700 // distinct addresses. In clang, the result of such a comparison is
5701 // unspecified, so it is not a constant expression. However, we do know
5702 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005703 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5704 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005705 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005706 // We can't tell whether weak symbols will end up pointing to the same
5707 // object.
5708 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005709 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005710 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005711 // (Note that clang defaults to -fmerge-all-constants, which can
5712 // lead to inconsistent results for comparisons involving the address
5713 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005714 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005715 }
Eli Friedman64004332009-03-23 04:38:34 +00005716
Richard Smith1b470412012-02-01 08:10:20 +00005717 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5718 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5719
Richard Smith84f6dcf2012-02-02 01:16:57 +00005720 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5721 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5722
John McCalle3027922010-08-25 11:45:40 +00005723 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005724 // C++11 [expr.add]p6:
5725 // Unless both pointers point to elements of the same array object, or
5726 // one past the last element of the array object, the behavior is
5727 // undefined.
5728 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5729 !AreElementsOfSameArray(getType(LHSValue.Base),
5730 LHSDesignator, RHSDesignator))
5731 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5732
Chris Lattner882bdf22010-04-20 17:13:14 +00005733 QualType Type = E->getLHS()->getType();
5734 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005735
Richard Smithd62306a2011-11-10 06:34:14 +00005736 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005737 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005738 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005739
Richard Smith1b470412012-02-01 08:10:20 +00005740 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5741 // and produce incorrect results when it overflows. Such behavior
5742 // appears to be non-conforming, but is common, so perhaps we should
5743 // assume the standard intended for such cases to be undefined behavior
5744 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005745
Richard Smith1b470412012-02-01 08:10:20 +00005746 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5747 // overflow in the final conversion to ptrdiff_t.
5748 APSInt LHS(
5749 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5750 APSInt RHS(
5751 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5752 APSInt ElemSize(
5753 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5754 APSInt TrueResult = (LHS - RHS) / ElemSize;
5755 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5756
5757 if (Result.extend(65) != TrueResult)
5758 HandleOverflow(Info, E, TrueResult, E->getType());
5759 return Success(Result, E);
5760 }
Richard Smithde21b242012-01-31 06:41:30 +00005761
5762 // C++11 [expr.rel]p3:
5763 // Pointers to void (after pointer conversions) can be compared, with a
5764 // result defined as follows: If both pointers represent the same
5765 // address or are both the null pointer value, the result is true if the
5766 // operator is <= or >= and false otherwise; otherwise the result is
5767 // unspecified.
5768 // We interpret this as applying to pointers to *cv* void.
5769 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005770 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005771 CCEDiag(E, diag::note_constexpr_void_comparison);
5772
Richard Smith84f6dcf2012-02-02 01:16:57 +00005773 // C++11 [expr.rel]p2:
5774 // - If two pointers point to non-static data members of the same object,
5775 // or to subobjects or array elements fo such members, recursively, the
5776 // pointer to the later declared member compares greater provided the
5777 // two members have the same access control and provided their class is
5778 // not a union.
5779 // [...]
5780 // - Otherwise pointer comparisons are unspecified.
5781 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5782 E->isRelationalOp()) {
5783 bool WasArrayIndex;
5784 unsigned Mismatch =
5785 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5786 RHSDesignator, WasArrayIndex);
5787 // At the point where the designators diverge, the comparison has a
5788 // specified value if:
5789 // - we are comparing array indices
5790 // - we are comparing fields of a union, or fields with the same access
5791 // Otherwise, the result is unspecified and thus the comparison is not a
5792 // constant expression.
5793 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5794 Mismatch < RHSDesignator.Entries.size()) {
5795 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5796 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5797 if (!LF && !RF)
5798 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5799 else if (!LF)
5800 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5801 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5802 << RF->getParent() << RF;
5803 else if (!RF)
5804 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5805 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5806 << LF->getParent() << LF;
5807 else if (!LF->getParent()->isUnion() &&
5808 LF->getAccess() != RF->getAccess())
5809 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5810 << LF << LF->getAccess() << RF << RF->getAccess()
5811 << LF->getParent();
5812 }
5813 }
5814
Eli Friedman6c31cb42012-04-16 04:30:08 +00005815 // The comparison here must be unsigned, and performed with the same
5816 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005817 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5818 uint64_t CompareLHS = LHSOffset.getQuantity();
5819 uint64_t CompareRHS = RHSOffset.getQuantity();
5820 assert(PtrSize <= 64 && "Unexpected pointer width");
5821 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5822 CompareLHS &= Mask;
5823 CompareRHS &= Mask;
5824
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005825 // If there is a base and this is a relational operator, we can only
5826 // compare pointers within the object in question; otherwise, the result
5827 // depends on where the object is located in memory.
5828 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5829 QualType BaseTy = getType(LHSValue.Base);
5830 if (BaseTy->isIncompleteType())
5831 return Error(E);
5832 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5833 uint64_t OffsetLimit = Size.getQuantity();
5834 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5835 return Error(E);
5836 }
5837
Richard Smith8b3497e2011-10-31 01:37:14 +00005838 switch (E->getOpcode()) {
5839 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005840 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5841 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5842 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5843 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5844 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5845 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005846 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005847 }
5848 }
Richard Smith7bb00672012-02-01 01:42:44 +00005849
5850 if (LHSTy->isMemberPointerType()) {
5851 assert(E->isEqualityOp() && "unexpected member pointer operation");
5852 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5853
5854 MemberPtr LHSValue, RHSValue;
5855
5856 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5857 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5858 return false;
5859
5860 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5861 return false;
5862
5863 // C++11 [expr.eq]p2:
5864 // If both operands are null, they compare equal. Otherwise if only one is
5865 // null, they compare unequal.
5866 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5867 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5868 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5869 }
5870
5871 // Otherwise if either is a pointer to a virtual member function, the
5872 // result is unspecified.
5873 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5874 if (MD->isVirtual())
5875 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5876 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5877 if (MD->isVirtual())
5878 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5879
5880 // Otherwise they compare equal if and only if they would refer to the
5881 // same member of the same most derived object or the same subobject if
5882 // they were dereferenced with a hypothetical object of the associated
5883 // class type.
5884 bool Equal = LHSValue == RHSValue;
5885 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5886 }
5887
Richard Smithab44d9b2012-02-14 22:35:28 +00005888 if (LHSTy->isNullPtrType()) {
5889 assert(E->isComparisonOp() && "unexpected nullptr operation");
5890 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5891 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5892 // are compared, the result is true of the operator is <=, >= or ==, and
5893 // false otherwise.
5894 BinaryOperator::Opcode Opcode = E->getOpcode();
5895 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5896 }
5897
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005898 assert((!LHSTy->isIntegralOrEnumerationType() ||
5899 !RHSTy->isIntegralOrEnumerationType()) &&
5900 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5901 // We can't continue from here for non-integral types.
5902 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005903}
5904
Ken Dyck160146e2010-01-27 17:10:57 +00005905CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005906 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5907 // result shall be the alignment of the referenced type."
5908 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5909 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005910
5911 // __alignof is defined to return the preferred alignment.
5912 return Info.Ctx.toCharUnitsFromBits(
5913 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005914}
5915
Ken Dyck160146e2010-01-27 17:10:57 +00005916CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005917 E = E->IgnoreParens();
5918
John McCall768439e2013-05-06 07:40:34 +00005919 // The kinds of expressions that we have special-case logic here for
5920 // should be kept up to date with the special checks for those
5921 // expressions in Sema.
5922
Chris Lattner68061312009-01-24 21:53:27 +00005923 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005924 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005925 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005926 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5927 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005928
Chris Lattner68061312009-01-24 21:53:27 +00005929 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005930 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5931 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005932
Chris Lattner24aeeab2009-01-24 21:09:06 +00005933 return GetAlignOfType(E->getType());
5934}
5935
5936
Peter Collingbournee190dee2011-03-11 19:24:49 +00005937/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5938/// a result as the expression's type.
5939bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5940 const UnaryExprOrTypeTraitExpr *E) {
5941 switch(E->getKind()) {
5942 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005943 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005944 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005945 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005946 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005947 }
Eli Friedman64004332009-03-23 04:38:34 +00005948
Peter Collingbournee190dee2011-03-11 19:24:49 +00005949 case UETT_VecStep: {
5950 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005951
Peter Collingbournee190dee2011-03-11 19:24:49 +00005952 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005953 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005954
Peter Collingbournee190dee2011-03-11 19:24:49 +00005955 // The vec_step built-in functions that take a 3-component
5956 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5957 if (n == 3)
5958 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005959
Peter Collingbournee190dee2011-03-11 19:24:49 +00005960 return Success(n, E);
5961 } else
5962 return Success(1, E);
5963 }
5964
5965 case UETT_SizeOf: {
5966 QualType SrcTy = E->getTypeOfArgument();
5967 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5968 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005969 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5970 SrcTy = Ref->getPointeeType();
5971
Richard Smithd62306a2011-11-10 06:34:14 +00005972 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005973 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005974 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005975 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005976 }
5977 }
5978
5979 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005980}
5981
Peter Collingbournee9200682011-05-13 03:29:01 +00005982bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005983 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005984 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005985 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005986 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005987 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005988 for (unsigned i = 0; i != n; ++i) {
5989 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5990 switch (ON.getKind()) {
5991 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005992 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005993 APSInt IdxResult;
5994 if (!EvaluateInteger(Idx, IdxResult, Info))
5995 return false;
5996 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5997 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005998 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005999 CurrentType = AT->getElementType();
6000 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6001 Result += IdxResult.getSExtValue() * ElementSize;
6002 break;
6003 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006004
Douglas Gregor882211c2010-04-28 22:16:22 +00006005 case OffsetOfExpr::OffsetOfNode::Field: {
6006 FieldDecl *MemberDecl = ON.getField();
6007 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006008 if (!RT)
6009 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006010 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006011 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006012 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006013 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006014 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006015 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006016 CurrentType = MemberDecl->getType().getNonReferenceType();
6017 break;
6018 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006019
Douglas Gregor882211c2010-04-28 22:16:22 +00006020 case OffsetOfExpr::OffsetOfNode::Identifier:
6021 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006022
Douglas Gregord1702062010-04-29 00:18:15 +00006023 case OffsetOfExpr::OffsetOfNode::Base: {
6024 CXXBaseSpecifier *BaseSpec = ON.getBase();
6025 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006026 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006027
6028 // Find the layout of the class whose base we are looking into.
6029 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006030 if (!RT)
6031 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006032 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006033 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006034 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6035
6036 // Find the base class itself.
6037 CurrentType = BaseSpec->getType();
6038 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6039 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006040 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006041
6042 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006043 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006044 break;
6045 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006046 }
6047 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006048 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006049}
6050
Chris Lattnere13042c2008-07-11 19:10:17 +00006051bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006052 switch (E->getOpcode()) {
6053 default:
6054 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6055 // See C99 6.6p3.
6056 return Error(E);
6057 case UO_Extension:
6058 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6059 // If so, we could clear the diagnostic ID.
6060 return Visit(E->getSubExpr());
6061 case UO_Plus:
6062 // The result is just the value.
6063 return Visit(E->getSubExpr());
6064 case UO_Minus: {
6065 if (!Visit(E->getSubExpr()))
6066 return false;
6067 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006068 const APSInt &Value = Result.getInt();
6069 if (Value.isSigned() && Value.isMinSignedValue())
6070 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6071 E->getType());
6072 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006073 }
6074 case UO_Not: {
6075 if (!Visit(E->getSubExpr()))
6076 return false;
6077 if (!Result.isInt()) return Error(E);
6078 return Success(~Result.getInt(), E);
6079 }
6080 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006081 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006082 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006083 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006084 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006085 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006086 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006087}
Mike Stump11289f42009-09-09 15:08:12 +00006088
Chris Lattner477c4be2008-07-12 01:15:53 +00006089/// HandleCast - This is used to evaluate implicit or explicit casts where the
6090/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006091bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6092 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006093 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006094 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006095
Eli Friedmanc757de22011-03-25 00:43:55 +00006096 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006097 case CK_BaseToDerived:
6098 case CK_DerivedToBase:
6099 case CK_UncheckedDerivedToBase:
6100 case CK_Dynamic:
6101 case CK_ToUnion:
6102 case CK_ArrayToPointerDecay:
6103 case CK_FunctionToPointerDecay:
6104 case CK_NullToPointer:
6105 case CK_NullToMemberPointer:
6106 case CK_BaseToDerivedMemberPointer:
6107 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006108 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006109 case CK_ConstructorConversion:
6110 case CK_IntegralToPointer:
6111 case CK_ToVoid:
6112 case CK_VectorSplat:
6113 case CK_IntegralToFloating:
6114 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006115 case CK_CPointerToObjCPointerCast:
6116 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006117 case CK_AnyPointerToBlockPointerCast:
6118 case CK_ObjCObjectLValueCast:
6119 case CK_FloatingRealToComplex:
6120 case CK_FloatingComplexToReal:
6121 case CK_FloatingComplexCast:
6122 case CK_FloatingComplexToIntegralComplex:
6123 case CK_IntegralRealToComplex:
6124 case CK_IntegralComplexCast:
6125 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006126 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006127 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006128 llvm_unreachable("invalid cast kind for integral value");
6129
Eli Friedman9faf2f92011-03-25 19:07:11 +00006130 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006131 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006132 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006133 case CK_ARCProduceObject:
6134 case CK_ARCConsumeObject:
6135 case CK_ARCReclaimReturnedObject:
6136 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006137 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006138 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006139
Richard Smith4ef685b2012-01-17 21:17:26 +00006140 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006141 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006142 case CK_AtomicToNonAtomic:
6143 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006144 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006145 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006146
6147 case CK_MemberPointerToBoolean:
6148 case CK_PointerToBoolean:
6149 case CK_IntegralToBoolean:
6150 case CK_FloatingToBoolean:
6151 case CK_FloatingComplexToBoolean:
6152 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006153 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006154 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006155 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006156 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006157 }
6158
Eli Friedmanc757de22011-03-25 00:43:55 +00006159 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006160 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006161 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006162
Eli Friedman742421e2009-02-20 01:15:07 +00006163 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006164 // Allow casts of address-of-label differences if they are no-ops
6165 // or narrowing. (The narrowing case isn't actually guaranteed to
6166 // be constant-evaluatable except in some narrow cases which are hard
6167 // to detect here. We let it through on the assumption the user knows
6168 // what they are doing.)
6169 if (Result.isAddrLabelDiff())
6170 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006171 // Only allow casts of lvalues if they are lossless.
6172 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6173 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006174
Richard Smith911e1422012-01-30 22:27:01 +00006175 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6176 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006177 }
Mike Stump11289f42009-09-09 15:08:12 +00006178
Eli Friedmanc757de22011-03-25 00:43:55 +00006179 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006180 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6181
John McCall45d55e42010-05-07 21:00:08 +00006182 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006183 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006184 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006185
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006186 if (LV.getLValueBase()) {
6187 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006188 // FIXME: Allow a larger integer size than the pointer size, and allow
6189 // narrowing back down to pointer width in subsequent integral casts.
6190 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006191 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006192 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006193
Richard Smithcf74da72011-11-16 07:18:12 +00006194 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006195 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006196 return true;
6197 }
6198
Ken Dyck02990832010-01-15 12:37:54 +00006199 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6200 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006201 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006202 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006203
Eli Friedmanc757de22011-03-25 00:43:55 +00006204 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006205 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006206 if (!EvaluateComplex(SubExpr, C, Info))
6207 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006208 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006209 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006210
Eli Friedmanc757de22011-03-25 00:43:55 +00006211 case CK_FloatingToIntegral: {
6212 APFloat F(0.0);
6213 if (!EvaluateFloat(SubExpr, F, Info))
6214 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006215
Richard Smith357362d2011-12-13 06:39:58 +00006216 APSInt Value;
6217 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6218 return false;
6219 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006220 }
6221 }
Mike Stump11289f42009-09-09 15:08:12 +00006222
Eli Friedmanc757de22011-03-25 00:43:55 +00006223 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006224}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006225
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006226bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6227 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006228 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006229 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6230 return false;
6231 if (!LV.isComplexInt())
6232 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006233 return Success(LV.getComplexIntReal(), E);
6234 }
6235
6236 return Visit(E->getSubExpr());
6237}
6238
Eli Friedman4e7a2412009-02-27 04:45:43 +00006239bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006240 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006241 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006242 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6243 return false;
6244 if (!LV.isComplexInt())
6245 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006246 return Success(LV.getComplexIntImag(), E);
6247 }
6248
Richard Smith4a678122011-10-24 18:44:57 +00006249 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006250 return Success(0, E);
6251}
6252
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006253bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6254 return Success(E->getPackLength(), E);
6255}
6256
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006257bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6258 return Success(E->getValue(), E);
6259}
6260
Chris Lattner05706e882008-07-11 18:11:29 +00006261//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006262// Float Evaluation
6263//===----------------------------------------------------------------------===//
6264
6265namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006266class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006267 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006268 APFloat &Result;
6269public:
6270 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006271 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006272
Richard Smith2e312c82012-03-03 22:46:17 +00006273 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006274 Result = V.getFloat();
6275 return true;
6276 }
Eli Friedman24c01542008-08-22 00:06:13 +00006277
Richard Smithfddd3842011-12-30 21:15:51 +00006278 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006279 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6280 return true;
6281 }
6282
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006283 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006284
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006285 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006286 bool VisitBinaryOperator(const BinaryOperator *E);
6287 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006288 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006289
John McCallb1fb0d32010-05-07 22:08:54 +00006290 bool VisitUnaryReal(const UnaryOperator *E);
6291 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006292
Richard Smithfddd3842011-12-30 21:15:51 +00006293 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006294};
6295} // end anonymous namespace
6296
6297static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006298 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006299 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006300}
6301
Jay Foad39c79802011-01-12 09:06:06 +00006302static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006303 QualType ResultTy,
6304 const Expr *Arg,
6305 bool SNaN,
6306 llvm::APFloat &Result) {
6307 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6308 if (!S) return false;
6309
6310 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6311
6312 llvm::APInt fill;
6313
6314 // Treat empty strings as if they were zero.
6315 if (S->getString().empty())
6316 fill = llvm::APInt(32, 0);
6317 else if (S->getString().getAsInteger(0, fill))
6318 return false;
6319
6320 if (SNaN)
6321 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6322 else
6323 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6324 return true;
6325}
6326
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006327bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006328 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006329 default:
6330 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6331
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006332 case Builtin::BI__builtin_huge_val:
6333 case Builtin::BI__builtin_huge_valf:
6334 case Builtin::BI__builtin_huge_vall:
6335 case Builtin::BI__builtin_inf:
6336 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006337 case Builtin::BI__builtin_infl: {
6338 const llvm::fltSemantics &Sem =
6339 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006340 Result = llvm::APFloat::getInf(Sem);
6341 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006342 }
Mike Stump11289f42009-09-09 15:08:12 +00006343
John McCall16291492010-02-28 13:00:19 +00006344 case Builtin::BI__builtin_nans:
6345 case Builtin::BI__builtin_nansf:
6346 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006347 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6348 true, Result))
6349 return Error(E);
6350 return true;
John McCall16291492010-02-28 13:00:19 +00006351
Chris Lattner0b7282e2008-10-06 06:31:58 +00006352 case Builtin::BI__builtin_nan:
6353 case Builtin::BI__builtin_nanf:
6354 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006355 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006356 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006357 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6358 false, Result))
6359 return Error(E);
6360 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006361
6362 case Builtin::BI__builtin_fabs:
6363 case Builtin::BI__builtin_fabsf:
6364 case Builtin::BI__builtin_fabsl:
6365 if (!EvaluateFloat(E->getArg(0), Result, Info))
6366 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006367
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006368 if (Result.isNegative())
6369 Result.changeSign();
6370 return true;
6371
Mike Stump11289f42009-09-09 15:08:12 +00006372 case Builtin::BI__builtin_copysign:
6373 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006374 case Builtin::BI__builtin_copysignl: {
6375 APFloat RHS(0.);
6376 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6377 !EvaluateFloat(E->getArg(1), RHS, Info))
6378 return false;
6379 Result.copySign(RHS);
6380 return true;
6381 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006382 }
6383}
6384
John McCallb1fb0d32010-05-07 22:08:54 +00006385bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006386 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6387 ComplexValue CV;
6388 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6389 return false;
6390 Result = CV.FloatReal;
6391 return true;
6392 }
6393
6394 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006395}
6396
6397bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006398 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6399 ComplexValue CV;
6400 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6401 return false;
6402 Result = CV.FloatImag;
6403 return true;
6404 }
6405
Richard Smith4a678122011-10-24 18:44:57 +00006406 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006407 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6408 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006409 return true;
6410}
6411
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006412bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006413 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006414 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006415 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006416 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006417 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006418 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6419 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006420 Result.changeSign();
6421 return true;
6422 }
6423}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006424
Eli Friedman24c01542008-08-22 00:06:13 +00006425bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006426 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6427 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006428
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006429 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006430 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6431 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006432 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006433 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00006434 return false;
6435
6436 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006437 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006438 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00006439 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006440 break;
John McCalle3027922010-08-25 11:45:40 +00006441 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00006442 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006443 break;
John McCalle3027922010-08-25 11:45:40 +00006444 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00006445 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006446 break;
John McCalle3027922010-08-25 11:45:40 +00006447 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00006448 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006449 break;
Eli Friedman24c01542008-08-22 00:06:13 +00006450 }
Richard Smithc8042322012-02-01 05:53:12 +00006451
6452 if (Result.isInfinity() || Result.isNaN())
6453 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
6454 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00006455}
6456
6457bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6458 Result = E->getValue();
6459 return true;
6460}
6461
Peter Collingbournee9200682011-05-13 03:29:01 +00006462bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6463 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006464
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006465 switch (E->getCastKind()) {
6466 default:
Richard Smith11562c52011-10-28 17:51:58 +00006467 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006468
6469 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006470 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006471 return EvaluateInteger(SubExpr, IntResult, Info) &&
6472 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6473 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006474 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006475
6476 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006477 if (!Visit(SubExpr))
6478 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006479 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6480 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006481 }
John McCalld7646252010-11-14 08:17:51 +00006482
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006483 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006484 ComplexValue V;
6485 if (!EvaluateComplex(SubExpr, V, Info))
6486 return false;
6487 Result = V.getComplexFloatReal();
6488 return true;
6489 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006490 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006491}
6492
Eli Friedman24c01542008-08-22 00:06:13 +00006493//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006494// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006495//===----------------------------------------------------------------------===//
6496
6497namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006498class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006499 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006500 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006501
Anders Carlsson537969c2008-11-16 20:27:53 +00006502public:
John McCall93d91dc2010-05-07 17:22:02 +00006503 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006504 : ExprEvaluatorBaseTy(info), Result(Result) {}
6505
Richard Smith2e312c82012-03-03 22:46:17 +00006506 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006507 Result.setFrom(V);
6508 return true;
6509 }
Mike Stump11289f42009-09-09 15:08:12 +00006510
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006511 bool ZeroInitialization(const Expr *E);
6512
Anders Carlsson537969c2008-11-16 20:27:53 +00006513 //===--------------------------------------------------------------------===//
6514 // Visitor Methods
6515 //===--------------------------------------------------------------------===//
6516
Peter Collingbournee9200682011-05-13 03:29:01 +00006517 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006518 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006519 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006520 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006521 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006522};
6523} // end anonymous namespace
6524
John McCall93d91dc2010-05-07 17:22:02 +00006525static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6526 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006527 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006528 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006529}
6530
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006531bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006532 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006533 if (ElemTy->isRealFloatingType()) {
6534 Result.makeComplexFloat();
6535 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6536 Result.FloatReal = Zero;
6537 Result.FloatImag = Zero;
6538 } else {
6539 Result.makeComplexInt();
6540 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6541 Result.IntReal = Zero;
6542 Result.IntImag = Zero;
6543 }
6544 return true;
6545}
6546
Peter Collingbournee9200682011-05-13 03:29:01 +00006547bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6548 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006549
6550 if (SubExpr->getType()->isRealFloatingType()) {
6551 Result.makeComplexFloat();
6552 APFloat &Imag = Result.FloatImag;
6553 if (!EvaluateFloat(SubExpr, Imag, Info))
6554 return false;
6555
6556 Result.FloatReal = APFloat(Imag.getSemantics());
6557 return true;
6558 } else {
6559 assert(SubExpr->getType()->isIntegerType() &&
6560 "Unexpected imaginary literal.");
6561
6562 Result.makeComplexInt();
6563 APSInt &Imag = Result.IntImag;
6564 if (!EvaluateInteger(SubExpr, Imag, Info))
6565 return false;
6566
6567 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6568 return true;
6569 }
6570}
6571
Peter Collingbournee9200682011-05-13 03:29:01 +00006572bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006573
John McCallfcef3cf2010-12-14 17:51:41 +00006574 switch (E->getCastKind()) {
6575 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006576 case CK_BaseToDerived:
6577 case CK_DerivedToBase:
6578 case CK_UncheckedDerivedToBase:
6579 case CK_Dynamic:
6580 case CK_ToUnion:
6581 case CK_ArrayToPointerDecay:
6582 case CK_FunctionToPointerDecay:
6583 case CK_NullToPointer:
6584 case CK_NullToMemberPointer:
6585 case CK_BaseToDerivedMemberPointer:
6586 case CK_DerivedToBaseMemberPointer:
6587 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006588 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006589 case CK_ConstructorConversion:
6590 case CK_IntegralToPointer:
6591 case CK_PointerToIntegral:
6592 case CK_PointerToBoolean:
6593 case CK_ToVoid:
6594 case CK_VectorSplat:
6595 case CK_IntegralCast:
6596 case CK_IntegralToBoolean:
6597 case CK_IntegralToFloating:
6598 case CK_FloatingToIntegral:
6599 case CK_FloatingToBoolean:
6600 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006601 case CK_CPointerToObjCPointerCast:
6602 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006603 case CK_AnyPointerToBlockPointerCast:
6604 case CK_ObjCObjectLValueCast:
6605 case CK_FloatingComplexToReal:
6606 case CK_FloatingComplexToBoolean:
6607 case CK_IntegralComplexToReal:
6608 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006609 case CK_ARCProduceObject:
6610 case CK_ARCConsumeObject:
6611 case CK_ARCReclaimReturnedObject:
6612 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006613 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006614 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006615 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006616 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006617
John McCallfcef3cf2010-12-14 17:51:41 +00006618 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006619 case CK_AtomicToNonAtomic:
6620 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006621 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006622 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006623
6624 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006625 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006626 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006627 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006628
6629 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006630 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006631 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006632 return false;
6633
John McCallfcef3cf2010-12-14 17:51:41 +00006634 Result.makeComplexFloat();
6635 Result.FloatImag = APFloat(Real.getSemantics());
6636 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006637 }
6638
John McCallfcef3cf2010-12-14 17:51:41 +00006639 case CK_FloatingComplexCast: {
6640 if (!Visit(E->getSubExpr()))
6641 return false;
6642
6643 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6644 QualType From
6645 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6646
Richard Smith357362d2011-12-13 06:39:58 +00006647 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6648 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006649 }
6650
6651 case CK_FloatingComplexToIntegralComplex: {
6652 if (!Visit(E->getSubExpr()))
6653 return false;
6654
6655 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6656 QualType From
6657 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6658 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006659 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6660 To, Result.IntReal) &&
6661 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6662 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006663 }
6664
6665 case CK_IntegralRealToComplex: {
6666 APSInt &Real = Result.IntReal;
6667 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6668 return false;
6669
6670 Result.makeComplexInt();
6671 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6672 return true;
6673 }
6674
6675 case CK_IntegralComplexCast: {
6676 if (!Visit(E->getSubExpr()))
6677 return false;
6678
6679 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6680 QualType From
6681 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6682
Richard Smith911e1422012-01-30 22:27:01 +00006683 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6684 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006685 return true;
6686 }
6687
6688 case CK_IntegralComplexToFloatingComplex: {
6689 if (!Visit(E->getSubExpr()))
6690 return false;
6691
Ted Kremenek28831752012-08-23 20:46:57 +00006692 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006693 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006694 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006695 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006696 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6697 To, Result.FloatReal) &&
6698 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6699 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006700 }
6701 }
6702
6703 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006704}
6705
John McCall93d91dc2010-05-07 17:22:02 +00006706bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006707 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006708 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6709
Richard Smith253c2a32012-01-27 01:14:48 +00006710 bool LHSOK = Visit(E->getLHS());
6711 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006712 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006713
John McCall93d91dc2010-05-07 17:22:02 +00006714 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006715 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006716 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006717
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006718 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6719 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006720 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006721 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006722 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006723 if (Result.isComplexFloat()) {
6724 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6725 APFloat::rmNearestTiesToEven);
6726 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6727 APFloat::rmNearestTiesToEven);
6728 } else {
6729 Result.getComplexIntReal() += RHS.getComplexIntReal();
6730 Result.getComplexIntImag() += RHS.getComplexIntImag();
6731 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006732 break;
John McCalle3027922010-08-25 11:45:40 +00006733 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006734 if (Result.isComplexFloat()) {
6735 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6736 APFloat::rmNearestTiesToEven);
6737 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6738 APFloat::rmNearestTiesToEven);
6739 } else {
6740 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6741 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6742 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006743 break;
John McCalle3027922010-08-25 11:45:40 +00006744 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006745 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006746 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006747 APFloat &LHS_r = LHS.getComplexFloatReal();
6748 APFloat &LHS_i = LHS.getComplexFloatImag();
6749 APFloat &RHS_r = RHS.getComplexFloatReal();
6750 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006751
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006752 APFloat Tmp = LHS_r;
6753 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6754 Result.getComplexFloatReal() = Tmp;
6755 Tmp = LHS_i;
6756 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6757 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6758
6759 Tmp = LHS_r;
6760 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6761 Result.getComplexFloatImag() = Tmp;
6762 Tmp = LHS_i;
6763 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6764 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6765 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006766 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006767 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006768 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6769 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006770 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006771 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6772 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6773 }
6774 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006775 case BO_Div:
6776 if (Result.isComplexFloat()) {
6777 ComplexValue LHS = Result;
6778 APFloat &LHS_r = LHS.getComplexFloatReal();
6779 APFloat &LHS_i = LHS.getComplexFloatImag();
6780 APFloat &RHS_r = RHS.getComplexFloatReal();
6781 APFloat &RHS_i = RHS.getComplexFloatImag();
6782 APFloat &Res_r = Result.getComplexFloatReal();
6783 APFloat &Res_i = Result.getComplexFloatImag();
6784
6785 APFloat Den = RHS_r;
6786 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6787 APFloat Tmp = RHS_i;
6788 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6789 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6790
6791 Res_r = LHS_r;
6792 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6793 Tmp = LHS_i;
6794 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6795 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6796 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6797
6798 Res_i = LHS_i;
6799 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6800 Tmp = LHS_r;
6801 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6802 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6803 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6804 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006805 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6806 return Error(E, diag::note_expr_divide_by_zero);
6807
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006808 ComplexValue LHS = Result;
6809 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6810 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6811 Result.getComplexIntReal() =
6812 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6813 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6814 Result.getComplexIntImag() =
6815 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6816 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6817 }
6818 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006819 }
6820
John McCall93d91dc2010-05-07 17:22:02 +00006821 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006822}
6823
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006824bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6825 // Get the operand value into 'Result'.
6826 if (!Visit(E->getSubExpr()))
6827 return false;
6828
6829 switch (E->getOpcode()) {
6830 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006831 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006832 case UO_Extension:
6833 return true;
6834 case UO_Plus:
6835 // The result is always just the subexpr.
6836 return true;
6837 case UO_Minus:
6838 if (Result.isComplexFloat()) {
6839 Result.getComplexFloatReal().changeSign();
6840 Result.getComplexFloatImag().changeSign();
6841 }
6842 else {
6843 Result.getComplexIntReal() = -Result.getComplexIntReal();
6844 Result.getComplexIntImag() = -Result.getComplexIntImag();
6845 }
6846 return true;
6847 case UO_Not:
6848 if (Result.isComplexFloat())
6849 Result.getComplexFloatImag().changeSign();
6850 else
6851 Result.getComplexIntImag() = -Result.getComplexIntImag();
6852 return true;
6853 }
6854}
6855
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006856bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6857 if (E->getNumInits() == 2) {
6858 if (E->getType()->isComplexType()) {
6859 Result.makeComplexFloat();
6860 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6861 return false;
6862 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6863 return false;
6864 } else {
6865 Result.makeComplexInt();
6866 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6867 return false;
6868 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6869 return false;
6870 }
6871 return true;
6872 }
6873 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6874}
6875
Anders Carlsson537969c2008-11-16 20:27:53 +00006876//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006877// Void expression evaluation, primarily for a cast to void on the LHS of a
6878// comma operator
6879//===----------------------------------------------------------------------===//
6880
6881namespace {
6882class VoidExprEvaluator
6883 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6884public:
6885 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6886
Richard Smith2e312c82012-03-03 22:46:17 +00006887 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006888
6889 bool VisitCastExpr(const CastExpr *E) {
6890 switch (E->getCastKind()) {
6891 default:
6892 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6893 case CK_ToVoid:
6894 VisitIgnoredValue(E->getSubExpr());
6895 return true;
6896 }
6897 }
6898};
6899} // end anonymous namespace
6900
6901static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6902 assert(E->isRValue() && E->getType()->isVoidType());
6903 return VoidExprEvaluator(Info).Visit(E);
6904}
6905
6906//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006907// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006908//===----------------------------------------------------------------------===//
6909
Richard Smith2e312c82012-03-03 22:46:17 +00006910static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006911 // In C, function designators are not lvalues, but we evaluate them as if they
6912 // are.
6913 if (E->isGLValue() || E->getType()->isFunctionType()) {
6914 LValue LV;
6915 if (!EvaluateLValue(E, LV, Info))
6916 return false;
6917 LV.moveInto(Result);
6918 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006919 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006920 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006921 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006922 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006923 return false;
John McCall45d55e42010-05-07 21:00:08 +00006924 } else if (E->getType()->hasPointerRepresentation()) {
6925 LValue LV;
6926 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006927 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006928 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006929 } else if (E->getType()->isRealFloatingType()) {
6930 llvm::APFloat F(0.0);
6931 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006932 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006933 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006934 } else if (E->getType()->isAnyComplexType()) {
6935 ComplexValue C;
6936 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006937 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006938 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006939 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006940 MemberPtr P;
6941 if (!EvaluateMemberPointer(E, P, Info))
6942 return false;
6943 P.moveInto(Result);
6944 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006945 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006946 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006947 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006948 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006949 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006950 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006951 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006952 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006953 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006954 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6955 return false;
6956 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006957 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006958 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006959 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006960 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006961 if (!EvaluateVoid(E, Info))
6962 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006963 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006964 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006965 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006966 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006967 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006968 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006969 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006970
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006971 return true;
6972}
6973
Richard Smithb228a862012-02-15 02:18:13 +00006974/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6975/// cases, the in-place evaluation is essential, since later initializers for
6976/// an object can indirectly refer to subobjects which were initialized earlier.
6977static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6978 const Expr *E, CheckConstantExpressionKind CCEK,
6979 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006980 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006981 return false;
6982
6983 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006984 // Evaluate arrays and record types in-place, so that later initializers can
6985 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006986 if (E->getType()->isArrayType())
6987 return EvaluateArray(E, This, Result, Info);
6988 else if (E->getType()->isRecordType())
6989 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006990 }
6991
6992 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006993 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006994}
6995
Richard Smithf57d8cb2011-12-09 22:58:01 +00006996/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6997/// lvalue-to-rvalue cast if it is an lvalue.
6998static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006999 if (!CheckLiteralType(Info, E))
7000 return false;
7001
Richard Smith2e312c82012-03-03 22:46:17 +00007002 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007003 return false;
7004
7005 if (E->isGLValue()) {
7006 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007007 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007008 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007009 return false;
7010 }
7011
Richard Smith2e312c82012-03-03 22:46:17 +00007012 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007013 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007014}
Richard Smith11562c52011-10-28 17:51:58 +00007015
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007016static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7017 const ASTContext &Ctx, bool &IsConst) {
7018 // Fast-path evaluations of integer literals, since we sometimes see files
7019 // containing vast quantities of these.
7020 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7021 Result.Val = APValue(APSInt(L->getValue(),
7022 L->getType()->isUnsignedIntegerType()));
7023 IsConst = true;
7024 return true;
7025 }
7026
7027 // FIXME: Evaluating values of large array and record types can cause
7028 // performance problems. Only do so in C++11 for now.
7029 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7030 Exp->getType()->isRecordType()) &&
7031 !Ctx.getLangOpts().CPlusPlus11) {
7032 IsConst = false;
7033 return true;
7034 }
7035 return false;
7036}
7037
7038
Richard Smith7b553f12011-10-29 00:50:52 +00007039/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007040/// any crazy technique (that has nothing to do with language standards) that
7041/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007042/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7043/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007044bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007045 bool IsConst;
7046 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7047 return IsConst;
7048
Richard Smithf57d8cb2011-12-09 22:58:01 +00007049 EvalInfo Info(Ctx, Result);
7050 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007051}
7052
Jay Foad39c79802011-01-12 09:06:06 +00007053bool Expr::EvaluateAsBooleanCondition(bool &Result,
7054 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007055 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007056 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007057 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007058}
7059
Richard Smith5fab0c92011-12-28 19:48:30 +00007060bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7061 SideEffectsKind AllowSideEffects) const {
7062 if (!getType()->isIntegralOrEnumerationType())
7063 return false;
7064
Richard Smith11562c52011-10-28 17:51:58 +00007065 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007066 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7067 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007068 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007069
Richard Smith11562c52011-10-28 17:51:58 +00007070 Result = ExprResult.Val.getInt();
7071 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007072}
7073
Jay Foad39c79802011-01-12 09:06:06 +00007074bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007075 EvalInfo Info(Ctx, Result);
7076
John McCall45d55e42010-05-07 21:00:08 +00007077 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007078 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7079 !CheckLValueConstantExpression(Info, getExprLoc(),
7080 Ctx.getLValueReferenceType(getType()), LV))
7081 return false;
7082
Richard Smith2e312c82012-03-03 22:46:17 +00007083 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007084 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007085}
7086
Richard Smithd0b4dd62011-12-19 06:19:21 +00007087bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7088 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007089 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007090 // FIXME: Evaluating initializers for large array and record types can cause
7091 // performance problems. Only do so in C++11 for now.
7092 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007093 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007094 return false;
7095
Richard Smithd0b4dd62011-12-19 06:19:21 +00007096 Expr::EvalStatus EStatus;
7097 EStatus.Diag = &Notes;
7098
7099 EvalInfo InitInfo(Ctx, EStatus);
7100 InitInfo.setEvaluatingDecl(VD, Value);
7101
7102 LValue LVal;
7103 LVal.set(VD);
7104
Richard Smithfddd3842011-12-30 21:15:51 +00007105 // C++11 [basic.start.init]p2:
7106 // Variables with static storage duration or thread storage duration shall be
7107 // zero-initialized before any other initialization takes place.
7108 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007109 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007110 !VD->getType()->isReferenceType()) {
7111 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007112 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
7113 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007114 return false;
7115 }
7116
Richard Smithb228a862012-02-15 02:18:13 +00007117 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
7118 /*AllowNonLiteralTypes=*/true) ||
7119 EStatus.HasSideEffects)
7120 return false;
7121
7122 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7123 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007124}
7125
Richard Smith7b553f12011-10-29 00:50:52 +00007126/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7127/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007128bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007129 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007130 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007131}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007132
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007133APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007134 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007135 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007136 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007137 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007138 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007139 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007140 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007141
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007142 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007143}
John McCall864e3962010-05-07 05:32:02 +00007144
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007145void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7146 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7147 bool IsConst;
7148 EvalResult EvalResult;
7149 EvalResult.Diag = Diags;
7150 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7151 EvalInfo Info(Ctx, EvalResult, true);
7152 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7153 }
7154}
7155
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007156 bool Expr::EvalResult::isGlobalLValue() const {
7157 assert(Val.isLValue());
7158 return IsGlobalLValue(Val.getLValueBase());
7159 }
7160
7161
John McCall864e3962010-05-07 05:32:02 +00007162/// isIntegerConstantExpr - this recursive routine will test if an expression is
7163/// an integer constant expression.
7164
7165/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7166/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007167
7168// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007169// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7170// and a (possibly null) SourceLocation indicating the location of the problem.
7171//
John McCall864e3962010-05-07 05:32:02 +00007172// Note that to reduce code duplication, this helper does no evaluation
7173// itself; the caller checks whether the expression is evaluatable, and
7174// in the rare cases where CheckICE actually cares about the evaluated
7175// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007176
Dan Gohman28ade552010-07-26 21:25:24 +00007177namespace {
7178
Richard Smith9e575da2012-12-28 13:25:52 +00007179enum ICEKind {
7180 /// This expression is an ICE.
7181 IK_ICE,
7182 /// This expression is not an ICE, but if it isn't evaluated, it's
7183 /// a legal subexpression for an ICE. This return value is used to handle
7184 /// the comma operator in C99 mode, and non-constant subexpressions.
7185 IK_ICEIfUnevaluated,
7186 /// This expression is not an ICE, and is not a legal subexpression for one.
7187 IK_NotICE
7188};
7189
John McCall864e3962010-05-07 05:32:02 +00007190struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007191 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007192 SourceLocation Loc;
7193
Richard Smith9e575da2012-12-28 13:25:52 +00007194 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007195};
7196
Dan Gohman28ade552010-07-26 21:25:24 +00007197}
7198
Richard Smith9e575da2012-12-28 13:25:52 +00007199static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7200
7201static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007202
7203static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7204 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007205 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007206 !EVResult.Val.isInt())
7207 return ICEDiag(IK_NotICE, E->getLocStart());
7208
John McCall864e3962010-05-07 05:32:02 +00007209 return NoDiag();
7210}
7211
7212static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7213 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007214 if (!E->getType()->isIntegralOrEnumerationType())
7215 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007216
7217 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007218#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007219#define STMT(Node, Base) case Expr::Node##Class:
7220#define EXPR(Node, Base)
7221#include "clang/AST/StmtNodes.inc"
7222 case Expr::PredefinedExprClass:
7223 case Expr::FloatingLiteralClass:
7224 case Expr::ImaginaryLiteralClass:
7225 case Expr::StringLiteralClass:
7226 case Expr::ArraySubscriptExprClass:
7227 case Expr::MemberExprClass:
7228 case Expr::CompoundAssignOperatorClass:
7229 case Expr::CompoundLiteralExprClass:
7230 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007231 case Expr::DesignatedInitExprClass:
7232 case Expr::ImplicitValueInitExprClass:
7233 case Expr::ParenListExprClass:
7234 case Expr::VAArgExprClass:
7235 case Expr::AddrLabelExprClass:
7236 case Expr::StmtExprClass:
7237 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007238 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007239 case Expr::CXXDynamicCastExprClass:
7240 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007241 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007242 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007243 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007244 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007245 case Expr::CXXThisExprClass:
7246 case Expr::CXXThrowExprClass:
7247 case Expr::CXXNewExprClass:
7248 case Expr::CXXDeleteExprClass:
7249 case Expr::CXXPseudoDestructorExprClass:
7250 case Expr::UnresolvedLookupExprClass:
7251 case Expr::DependentScopeDeclRefExprClass:
7252 case Expr::CXXConstructExprClass:
7253 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007254 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007255 case Expr::CXXTemporaryObjectExprClass:
7256 case Expr::CXXUnresolvedConstructExprClass:
7257 case Expr::CXXDependentScopeMemberExprClass:
7258 case Expr::UnresolvedMemberExprClass:
7259 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007260 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007261 case Expr::ObjCArrayLiteralClass:
7262 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007263 case Expr::ObjCEncodeExprClass:
7264 case Expr::ObjCMessageExprClass:
7265 case Expr::ObjCSelectorExprClass:
7266 case Expr::ObjCProtocolExprClass:
7267 case Expr::ObjCIvarRefExprClass:
7268 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007269 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007270 case Expr::ObjCIsaExprClass:
7271 case Expr::ShuffleVectorExprClass:
7272 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007273 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007274 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007275 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007276 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007277 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007278 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007279 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007280 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007281 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007282 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007283 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007284 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007285 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007286
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007287 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007288 case Expr::GNUNullExprClass:
7289 // GCC considers the GNU __null value to be an integral constant expression.
7290 return NoDiag();
7291
John McCall7c454bb2011-07-15 05:09:51 +00007292 case Expr::SubstNonTypeTemplateParmExprClass:
7293 return
7294 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7295
John McCall864e3962010-05-07 05:32:02 +00007296 case Expr::ParenExprClass:
7297 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007298 case Expr::GenericSelectionExprClass:
7299 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007300 case Expr::IntegerLiteralClass:
7301 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007302 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007303 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007304 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007305 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007306 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007307 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007308 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007309 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007310 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007311 return NoDiag();
7312 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007313 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007314 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7315 // constant expressions, but they can never be ICEs because an ICE cannot
7316 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007317 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007318 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007319 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007320 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007321 }
Richard Smith6365c912012-02-24 22:12:32 +00007322 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007323 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7324 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007325 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007326 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007327 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007328 // Parameter variables are never constants. Without this check,
7329 // getAnyInitializer() can find a default argument, which leads
7330 // to chaos.
7331 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007332 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007333
7334 // C++ 7.1.5.1p2
7335 // A variable of non-volatile const-qualified integral or enumeration
7336 // type initialized by an ICE can be used in ICEs.
7337 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007338 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007339 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007340
Richard Smithd0b4dd62011-12-19 06:19:21 +00007341 const VarDecl *VD;
7342 // Look for a declaration of this variable that has an initializer, and
7343 // check whether it is an ICE.
7344 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7345 return NoDiag();
7346 else
Richard Smith9e575da2012-12-28 13:25:52 +00007347 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007348 }
7349 }
Richard Smith9e575da2012-12-28 13:25:52 +00007350 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007351 }
John McCall864e3962010-05-07 05:32:02 +00007352 case Expr::UnaryOperatorClass: {
7353 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7354 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007355 case UO_PostInc:
7356 case UO_PostDec:
7357 case UO_PreInc:
7358 case UO_PreDec:
7359 case UO_AddrOf:
7360 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007361 // C99 6.6/3 allows increment and decrement within unevaluated
7362 // subexpressions of constant expressions, but they can never be ICEs
7363 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007364 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007365 case UO_Extension:
7366 case UO_LNot:
7367 case UO_Plus:
7368 case UO_Minus:
7369 case UO_Not:
7370 case UO_Real:
7371 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007372 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007373 }
Richard Smith9e575da2012-12-28 13:25:52 +00007374
John McCall864e3962010-05-07 05:32:02 +00007375 // OffsetOf falls through here.
7376 }
7377 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007378 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7379 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7380 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7381 // compliance: we should warn earlier for offsetof expressions with
7382 // array subscripts that aren't ICEs, and if the array subscripts
7383 // are ICEs, the value of the offsetof must be an integer constant.
7384 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007385 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007386 case Expr::UnaryExprOrTypeTraitExprClass: {
7387 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7388 if ((Exp->getKind() == UETT_SizeOf) &&
7389 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007390 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007391 return NoDiag();
7392 }
7393 case Expr::BinaryOperatorClass: {
7394 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7395 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007396 case BO_PtrMemD:
7397 case BO_PtrMemI:
7398 case BO_Assign:
7399 case BO_MulAssign:
7400 case BO_DivAssign:
7401 case BO_RemAssign:
7402 case BO_AddAssign:
7403 case BO_SubAssign:
7404 case BO_ShlAssign:
7405 case BO_ShrAssign:
7406 case BO_AndAssign:
7407 case BO_XorAssign:
7408 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007409 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7410 // constant expressions, but they can never be ICEs because an ICE cannot
7411 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007412 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007413
John McCalle3027922010-08-25 11:45:40 +00007414 case BO_Mul:
7415 case BO_Div:
7416 case BO_Rem:
7417 case BO_Add:
7418 case BO_Sub:
7419 case BO_Shl:
7420 case BO_Shr:
7421 case BO_LT:
7422 case BO_GT:
7423 case BO_LE:
7424 case BO_GE:
7425 case BO_EQ:
7426 case BO_NE:
7427 case BO_And:
7428 case BO_Xor:
7429 case BO_Or:
7430 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007431 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7432 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007433 if (Exp->getOpcode() == BO_Div ||
7434 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007435 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007436 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007437 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007438 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007439 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007440 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007441 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007442 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007443 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007444 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007445 }
7446 }
7447 }
John McCalle3027922010-08-25 11:45:40 +00007448 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007449 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007450 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7451 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007452 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7453 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007454 } else {
7455 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007456 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007457 }
7458 }
Richard Smith9e575da2012-12-28 13:25:52 +00007459 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007460 }
John McCalle3027922010-08-25 11:45:40 +00007461 case BO_LAnd:
7462 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007463 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7464 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007465 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007466 // Rare case where the RHS has a comma "side-effect"; we need
7467 // to actually check the condition to see whether the side
7468 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007469 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007470 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007471 return RHSResult;
7472 return NoDiag();
7473 }
7474
Richard Smith9e575da2012-12-28 13:25:52 +00007475 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007476 }
7477 }
7478 }
7479 case Expr::ImplicitCastExprClass:
7480 case Expr::CStyleCastExprClass:
7481 case Expr::CXXFunctionalCastExprClass:
7482 case Expr::CXXStaticCastExprClass:
7483 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007484 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007485 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007486 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007487 if (isa<ExplicitCastExpr>(E)) {
7488 if (const FloatingLiteral *FL
7489 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7490 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7491 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7492 APSInt IgnoredVal(DestWidth, !DestSigned);
7493 bool Ignored;
7494 // If the value does not fit in the destination type, the behavior is
7495 // undefined, so we are not required to treat it as a constant
7496 // expression.
7497 if (FL->getValue().convertToInteger(IgnoredVal,
7498 llvm::APFloat::rmTowardZero,
7499 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007500 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007501 return NoDiag();
7502 }
7503 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007504 switch (cast<CastExpr>(E)->getCastKind()) {
7505 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007506 case CK_AtomicToNonAtomic:
7507 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007508 case CK_NoOp:
7509 case CK_IntegralToBoolean:
7510 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007511 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007512 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007513 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007514 }
John McCall864e3962010-05-07 05:32:02 +00007515 }
John McCallc07a0c72011-02-17 10:25:35 +00007516 case Expr::BinaryConditionalOperatorClass: {
7517 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7518 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007519 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007520 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007521 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7522 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7523 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007524 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007525 return FalseResult;
7526 }
John McCall864e3962010-05-07 05:32:02 +00007527 case Expr::ConditionalOperatorClass: {
7528 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7529 // If the condition (ignoring parens) is a __builtin_constant_p call,
7530 // then only the true side is actually considered in an integer constant
7531 // expression, and it is fully evaluated. This is an important GNU
7532 // extension. See GCC PR38377 for discussion.
7533 if (const CallExpr *CallCE
7534 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007535 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7536 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007537 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007538 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007539 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007540
Richard Smithf57d8cb2011-12-09 22:58:01 +00007541 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7542 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007543
Richard Smith9e575da2012-12-28 13:25:52 +00007544 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007545 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007546 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007547 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007548 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007549 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007550 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007551 return NoDiag();
7552 // Rare case where the diagnostics depend on which side is evaluated
7553 // Note that if we get here, CondResult is 0, and at least one of
7554 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007555 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007556 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007557 return TrueResult;
7558 }
7559 case Expr::CXXDefaultArgExprClass:
7560 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007561 case Expr::CXXDefaultInitExprClass:
7562 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007563 case Expr::ChooseExprClass: {
7564 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7565 }
7566 }
7567
David Blaikiee4d798f2012-01-20 21:50:17 +00007568 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007569}
7570
Richard Smithf57d8cb2011-12-09 22:58:01 +00007571/// Evaluate an expression as a C++11 integral constant expression.
7572static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7573 const Expr *E,
7574 llvm::APSInt *Value,
7575 SourceLocation *Loc) {
7576 if (!E->getType()->isIntegralOrEnumerationType()) {
7577 if (Loc) *Loc = E->getExprLoc();
7578 return false;
7579 }
7580
Richard Smith66e05fe2012-01-18 05:21:49 +00007581 APValue Result;
7582 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007583 return false;
7584
Richard Smith66e05fe2012-01-18 05:21:49 +00007585 assert(Result.isInt() && "pointer cast to int is not an ICE");
7586 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007587 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007588}
7589
Richard Smith92b1ce02011-12-12 09:28:41 +00007590bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007591 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007592 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7593
Richard Smith9e575da2012-12-28 13:25:52 +00007594 ICEDiag D = CheckICE(this, Ctx);
7595 if (D.Kind != IK_ICE) {
7596 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007597 return false;
7598 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007599 return true;
7600}
7601
7602bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7603 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007604 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007605 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7606
7607 if (!isIntegerConstantExpr(Ctx, Loc))
7608 return false;
7609 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007610 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007611 return true;
7612}
Richard Smith66e05fe2012-01-18 05:21:49 +00007613
Richard Smith98a0a492012-02-14 21:38:30 +00007614bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007615 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007616}
7617
Richard Smith66e05fe2012-01-18 05:21:49 +00007618bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7619 SourceLocation *Loc) const {
7620 // We support this checking in C++98 mode in order to diagnose compatibility
7621 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007622 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007623
Richard Smith98a0a492012-02-14 21:38:30 +00007624 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007625 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007626 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007627 Status.Diag = &Diags;
7628 EvalInfo Info(Ctx, Status);
7629
7630 APValue Scratch;
7631 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7632
7633 if (!Diags.empty()) {
7634 IsConstExpr = false;
7635 if (Loc) *Loc = Diags[0].first;
7636 } else if (!IsConstExpr) {
7637 // FIXME: This shouldn't happen.
7638 if (Loc) *Loc = getExprLoc();
7639 }
7640
7641 return IsConstExpr;
7642}
Richard Smith253c2a32012-01-27 01:14:48 +00007643
7644bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007645 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007646 PartialDiagnosticAt> &Diags) {
7647 // FIXME: It would be useful to check constexpr function templates, but at the
7648 // moment the constant expression evaluator cannot cope with the non-rigorous
7649 // ASTs which we build for dependent expressions.
7650 if (FD->isDependentContext())
7651 return true;
7652
7653 Expr::EvalStatus Status;
7654 Status.Diag = &Diags;
7655
7656 EvalInfo Info(FD->getASTContext(), Status);
7657 Info.CheckingPotentialConstantExpression = true;
7658
7659 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7660 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7661
7662 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7663 // is a temporary being used as the 'this' pointer.
7664 LValue This;
7665 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007666 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007667
Richard Smith253c2a32012-01-27 01:14:48 +00007668 ArrayRef<const Expr*> Args;
7669
7670 SourceLocation Loc = FD->getLocation();
7671
Richard Smith2e312c82012-03-03 22:46:17 +00007672 APValue Scratch;
7673 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00007674 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00007675 else
Richard Smith253c2a32012-01-27 01:14:48 +00007676 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7677 Args, FD->getBody(), Info, Scratch);
7678
7679 return Diags.empty();
7680}