blob: 5695af21ac45f294222d5cd57fc4ddccef9c3f98 [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 Smith43e77732013-05-07 04:50:00 +00001302/// Perform the given integer operation, which is known to need at most BitWidth
1303/// bits, and check for overflow in the original type (if that type was not an
1304/// unsigned type).
1305template<typename Operation>
1306static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1307 const APSInt &LHS, const APSInt &RHS,
1308 unsigned BitWidth, Operation Op) {
1309 if (LHS.isUnsigned())
1310 return Op(LHS, RHS);
1311
1312 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1313 APSInt Result = Value.trunc(LHS.getBitWidth());
1314 if (Result.extend(BitWidth) != Value) {
1315 if (Info.getIntOverflowCheckMode())
1316 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1317 diag::warn_integer_constant_overflow)
1318 << Result.toString(10) << E->getType();
1319 else
1320 HandleOverflow(Info, E, Value, E->getType());
1321 }
1322 return Result;
1323}
1324
1325/// Perform the given binary integer operation.
1326static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1327 BinaryOperatorKind Opcode, APSInt RHS,
1328 APSInt &Result) {
1329 switch (Opcode) {
1330 default:
1331 Info.Diag(E);
1332 return false;
1333 case BO_Mul:
1334 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1335 std::multiplies<APSInt>());
1336 return true;
1337 case BO_Add:
1338 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1339 std::plus<APSInt>());
1340 return true;
1341 case BO_Sub:
1342 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1343 std::minus<APSInt>());
1344 return true;
1345 case BO_And: Result = LHS & RHS; return true;
1346 case BO_Xor: Result = LHS ^ RHS; return true;
1347 case BO_Or: Result = LHS | RHS; return true;
1348 case BO_Div:
1349 case BO_Rem:
1350 if (RHS == 0) {
1351 Info.Diag(E, diag::note_expr_divide_by_zero);
1352 return false;
1353 }
1354 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1355 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1356 LHS.isSigned() && LHS.isMinSignedValue())
1357 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1358 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1359 return true;
1360 case BO_Shl: {
1361 if (Info.getLangOpts().OpenCL)
1362 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1363 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1364 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1365 RHS.isUnsigned());
1366 else if (RHS.isSigned() && RHS.isNegative()) {
1367 // During constant-folding, a negative shift is an opposite shift. Such
1368 // a shift is not a constant expression.
1369 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1370 RHS = -RHS;
1371 goto shift_right;
1372 }
1373 shift_left:
1374 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1375 // the shifted type.
1376 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1377 if (SA != RHS) {
1378 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1379 << RHS << E->getType() << LHS.getBitWidth();
1380 } else if (LHS.isSigned()) {
1381 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1382 // operand, and must not overflow the corresponding unsigned type.
1383 if (LHS.isNegative())
1384 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1385 else if (LHS.countLeadingZeros() < SA)
1386 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1387 }
1388 Result = LHS << SA;
1389 return true;
1390 }
1391 case BO_Shr: {
1392 if (Info.getLangOpts().OpenCL)
1393 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1394 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1395 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1396 RHS.isUnsigned());
1397 else if (RHS.isSigned() && RHS.isNegative()) {
1398 // During constant-folding, a negative shift is an opposite shift. Such a
1399 // shift is not a constant expression.
1400 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1401 RHS = -RHS;
1402 goto shift_left;
1403 }
1404 shift_right:
1405 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1406 // shifted type.
1407 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1408 if (SA != RHS)
1409 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1410 << RHS << E->getType() << LHS.getBitWidth();
1411 Result = LHS >> SA;
1412 return true;
1413 }
1414
1415 case BO_LT: Result = LHS < RHS; return true;
1416 case BO_GT: Result = LHS > RHS; return true;
1417 case BO_LE: Result = LHS <= RHS; return true;
1418 case BO_GE: Result = LHS >= RHS; return true;
1419 case BO_EQ: Result = LHS == RHS; return true;
1420 case BO_NE: Result = LHS != RHS; return true;
1421 }
1422}
1423
Richard Smitha8105bc2012-01-06 16:39:00 +00001424/// Cast an lvalue referring to a base subobject to a derived class, by
1425/// truncating the lvalue's path to the given length.
1426static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1427 const RecordDecl *TruncatedType,
1428 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001429 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001430
1431 // Check we actually point to a derived class object.
1432 if (TruncatedElements == D.Entries.size())
1433 return true;
1434 assert(TruncatedElements >= D.MostDerivedPathLength &&
1435 "not casting to a derived class");
1436 if (!Result.checkSubobject(Info, E, CSK_Derived))
1437 return false;
1438
1439 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001440 const RecordDecl *RD = TruncatedType;
1441 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001442 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001443 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1444 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001445 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001446 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001447 else
Richard Smithd62306a2011-11-10 06:34:14 +00001448 Result.Offset -= Layout.getBaseClassOffset(Base);
1449 RD = Base;
1450 }
Richard Smith027bf112011-11-17 22:56:20 +00001451 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001452 return true;
1453}
1454
John McCalld7bca762012-05-01 00:38:49 +00001455static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001456 const CXXRecordDecl *Derived,
1457 const CXXRecordDecl *Base,
1458 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001459 if (!RL) {
1460 if (Derived->isInvalidDecl()) return false;
1461 RL = &Info.Ctx.getASTRecordLayout(Derived);
1462 }
1463
Richard Smithd62306a2011-11-10 06:34:14 +00001464 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001465 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001466 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001467}
1468
Richard Smitha8105bc2012-01-06 16:39:00 +00001469static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001470 const CXXRecordDecl *DerivedDecl,
1471 const CXXBaseSpecifier *Base) {
1472 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1473
John McCalld7bca762012-05-01 00:38:49 +00001474 if (!Base->isVirtual())
1475 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001476
Richard Smitha8105bc2012-01-06 16:39:00 +00001477 SubobjectDesignator &D = Obj.Designator;
1478 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001479 return false;
1480
Richard Smitha8105bc2012-01-06 16:39:00 +00001481 // Extract most-derived object and corresponding type.
1482 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1483 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1484 return false;
1485
1486 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001487 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001488 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1489 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001490 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001491 return true;
1492}
1493
1494/// Update LVal to refer to the given field, which must be a member of the type
1495/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001496static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001497 const FieldDecl *FD,
1498 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001499 if (!RL) {
1500 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001501 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001502 }
Richard Smithd62306a2011-11-10 06:34:14 +00001503
1504 unsigned I = FD->getFieldIndex();
1505 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001506 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001507 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001508}
1509
Richard Smith1b78b3d2012-01-25 22:15:11 +00001510/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001511static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001512 LValue &LVal,
1513 const IndirectFieldDecl *IFD) {
1514 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1515 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001516 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1517 return false;
1518 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001519}
1520
Richard Smithd62306a2011-11-10 06:34:14 +00001521/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001522static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1523 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001524 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1525 // extension.
1526 if (Type->isVoidType() || Type->isFunctionType()) {
1527 Size = CharUnits::One();
1528 return true;
1529 }
1530
1531 if (!Type->isConstantSizeType()) {
1532 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001533 // FIXME: Better diagnostic.
1534 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001535 return false;
1536 }
1537
1538 Size = Info.Ctx.getTypeSizeInChars(Type);
1539 return true;
1540}
1541
1542/// Update a pointer value to model pointer arithmetic.
1543/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001544/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001545/// \param LVal - The pointer value to be updated.
1546/// \param EltTy - The pointee type represented by LVal.
1547/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001548static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1549 LValue &LVal, QualType EltTy,
1550 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001551 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001552 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001553 return false;
1554
1555 // Compute the new offset in the appropriate width.
1556 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001557 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001558 return true;
1559}
1560
Richard Smith66c96992012-02-18 22:04:06 +00001561/// Update an lvalue to refer to a component of a complex number.
1562/// \param Info - Information about the ongoing evaluation.
1563/// \param LVal - The lvalue to be updated.
1564/// \param EltTy - The complex number's component type.
1565/// \param Imag - False for the real component, true for the imaginary.
1566static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1567 LValue &LVal, QualType EltTy,
1568 bool Imag) {
1569 if (Imag) {
1570 CharUnits SizeOfComponent;
1571 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1572 return false;
1573 LVal.Offset += SizeOfComponent;
1574 }
1575 LVal.addComplex(Info, E, EltTy, Imag);
1576 return true;
1577}
1578
Richard Smith27908702011-10-24 17:54:18 +00001579/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001580///
1581/// \param Info Information about the ongoing evaluation.
1582/// \param E An expression to be used when printing diagnostics.
1583/// \param VD The variable whose initializer should be obtained.
1584/// \param Frame The frame in which the variable was created. Must be null
1585/// if this variable is not local to the evaluation.
1586/// \param Result Filled in with a pointer to the value of the variable.
1587static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1588 const VarDecl *VD, CallStackFrame *Frame,
1589 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001590 // If this is a parameter to an active constexpr function call, perform
1591 // argument substitution.
1592 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001593 // Assume arguments of a potential constant expression are unknown
1594 // constant expressions.
1595 if (Info.CheckingPotentialConstantExpression)
1596 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001597 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001598 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001599 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001600 }
Richard Smith3229b742013-05-05 21:17:10 +00001601 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001602 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001603 }
Richard Smith27908702011-10-24 17:54:18 +00001604
Richard Smithd9f663b2013-04-22 15:31:51 +00001605 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001606 if (Frame) {
1607 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001608 // If we've carried on past an unevaluatable local variable initializer,
1609 // we can't go any further. This can happen during potential constant
1610 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001611 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001612 }
1613
Richard Smithd0b4dd62011-12-19 06:19:21 +00001614 // Dig out the initializer, and use the declaration which it's attached to.
1615 const Expr *Init = VD->getAnyInitializer(VD);
1616 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001617 // If we're checking a potential constant expression, the variable could be
1618 // initialized later.
1619 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001620 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001621 return false;
1622 }
1623
Richard Smithd62306a2011-11-10 06:34:14 +00001624 // If we're currently evaluating the initializer of this declaration, use that
1625 // in-flight value.
1626 if (Info.EvaluatingDecl == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001627 Result = Info.EvaluatingDeclValue;
1628 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001629 }
1630
Richard Smithcecf1842011-11-01 21:06:14 +00001631 // Never evaluate the initializer of a weak variable. We can't be sure that
1632 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001633 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001634 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001635 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001636 }
Richard Smithcecf1842011-11-01 21:06:14 +00001637
Richard Smithd0b4dd62011-12-19 06:19:21 +00001638 // Check that we can fold the initializer. In C++, we will have already done
1639 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001640 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001641 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001642 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001643 Notes.size() + 1) << VD;
1644 Info.Note(VD->getLocation(), diag::note_declared_at);
1645 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001646 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001647 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001648 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001649 Notes.size() + 1) << VD;
1650 Info.Note(VD->getLocation(), diag::note_declared_at);
1651 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001652 }
Richard Smith27908702011-10-24 17:54:18 +00001653
Richard Smith3229b742013-05-05 21:17:10 +00001654 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001655 return true;
Richard Smith27908702011-10-24 17:54:18 +00001656}
1657
Richard Smith11562c52011-10-28 17:51:58 +00001658static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001659 Qualifiers Quals = T.getQualifiers();
1660 return Quals.hasConst() && !Quals.hasVolatile();
1661}
1662
Richard Smithe97cbd72011-11-11 04:05:33 +00001663/// Get the base index of the given base class within an APValue representing
1664/// the given derived class.
1665static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1666 const CXXRecordDecl *Base) {
1667 Base = Base->getCanonicalDecl();
1668 unsigned Index = 0;
1669 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1670 E = Derived->bases_end(); I != E; ++I, ++Index) {
1671 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1672 return Index;
1673 }
1674
1675 llvm_unreachable("base class missing from derived class's bases list");
1676}
1677
Richard Smith3da88fa2013-04-26 14:36:30 +00001678/// Extract the value of a character from a string literal.
1679static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1680 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001681 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001682 const StringLiteral *S = cast<StringLiteral>(Lit);
1683 const ConstantArrayType *CAT =
1684 Info.Ctx.getAsConstantArrayType(S->getType());
1685 assert(CAT && "string literal isn't an array");
1686 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001687 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001688
1689 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001690 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001691 if (Index < S->getLength())
1692 Value = S->getCodeUnit(Index);
1693 return Value;
1694}
1695
Richard Smith3da88fa2013-04-26 14:36:30 +00001696// Expand a string literal into an array of characters.
1697static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1698 APValue &Result) {
1699 const StringLiteral *S = cast<StringLiteral>(Lit);
1700 const ConstantArrayType *CAT =
1701 Info.Ctx.getAsConstantArrayType(S->getType());
1702 assert(CAT && "string literal isn't an array");
1703 QualType CharType = CAT->getElementType();
1704 assert(CharType->isIntegerType() && "unexpected character type");
1705
1706 unsigned Elts = CAT->getSize().getZExtValue();
1707 Result = APValue(APValue::UninitArray(),
1708 std::min(S->getLength(), Elts), Elts);
1709 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1710 CharType->isUnsignedIntegerType());
1711 if (Result.hasArrayFiller())
1712 Result.getArrayFiller() = APValue(Value);
1713 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1714 Value = S->getCodeUnit(I);
1715 Result.getArrayInitializedElt(I) = APValue(Value);
1716 }
1717}
1718
1719// Expand an array so that it has more than Index filled elements.
1720static void expandArray(APValue &Array, unsigned Index) {
1721 unsigned Size = Array.getArraySize();
1722 assert(Index < Size);
1723
1724 // Always at least double the number of elements for which we store a value.
1725 unsigned OldElts = Array.getArrayInitializedElts();
1726 unsigned NewElts = std::max(Index+1, OldElts * 2);
1727 NewElts = std::min(Size, std::max(NewElts, 8u));
1728
1729 // Copy the data across.
1730 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1731 for (unsigned I = 0; I != OldElts; ++I)
1732 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1733 for (unsigned I = OldElts; I != NewElts; ++I)
1734 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1735 if (NewValue.hasArrayFiller())
1736 NewValue.getArrayFiller() = Array.getArrayFiller();
1737 Array.swap(NewValue);
1738}
1739
1740/// Kinds of access we can perform on an object.
1741enum AccessKinds {
1742 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001743 AK_Assign,
1744 AK_Increment,
1745 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001746};
1747
Richard Smith3229b742013-05-05 21:17:10 +00001748/// A handle to a complete object (an object that is not a subobject of
1749/// another object).
1750struct CompleteObject {
1751 /// The value of the complete object.
1752 APValue *Value;
1753 /// The type of the complete object.
1754 QualType Type;
1755
1756 CompleteObject() : Value(0) {}
1757 CompleteObject(APValue *Value, QualType Type)
1758 : Value(Value), Type(Type) {
1759 assert(Value && "missing value for complete object");
1760 }
1761
1762 operator bool() const { return Value; }
1763};
1764
Richard Smith3da88fa2013-04-26 14:36:30 +00001765/// Find the designated sub-object of an rvalue.
1766template<typename SubobjectHandler>
1767typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001768findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001769 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001770 if (Sub.Invalid)
1771 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001772 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001773 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001774 if (Info.getLangOpts().CPlusPlus11)
1775 Info.Diag(E, diag::note_constexpr_access_past_end)
1776 << handler.AccessKind;
1777 else
1778 Info.Diag(E);
1779 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001780 }
Richard Smith6804be52011-11-11 08:28:03 +00001781 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001782 return handler.found(*Obj.Value, Obj.Type);
1783 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001784 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001785 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001786
Richard Smith3229b742013-05-05 21:17:10 +00001787 APValue *O = Obj.Value;
1788 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001789 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001790 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001791 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001792 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001793 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001794 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001795 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001796 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001797 // Note, it should not be possible to form a pointer with a valid
1798 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001799 if (Info.getLangOpts().CPlusPlus11)
1800 Info.Diag(E, diag::note_constexpr_access_past_end)
1801 << handler.AccessKind;
1802 else
1803 Info.Diag(E);
1804 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001805 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001806
1807 ObjType = CAT->getElementType();
1808
Richard Smith14a94132012-02-17 03:35:37 +00001809 // An array object is represented as either an Array APValue or as an
1810 // LValue which refers to a string literal.
1811 if (O->isLValue()) {
1812 assert(I == N - 1 && "extracting subobject of character?");
1813 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001814 if (handler.AccessKind != AK_Read)
1815 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1816 *O);
1817 else
1818 return handler.foundString(*O, ObjType, Index);
1819 }
1820
1821 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001822 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001823 else if (handler.AccessKind != AK_Read) {
1824 expandArray(*O, Index);
1825 O = &O->getArrayInitializedElt(Index);
1826 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001827 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001828 } else if (ObjType->isAnyComplexType()) {
1829 // Next subobject is a complex number.
1830 uint64_t Index = Sub.Entries[I].ArrayIndex;
1831 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001832 if (Info.getLangOpts().CPlusPlus11)
1833 Info.Diag(E, diag::note_constexpr_access_past_end)
1834 << handler.AccessKind;
1835 else
1836 Info.Diag(E);
1837 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001838 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001839
1840 bool WasConstQualified = ObjType.isConstQualified();
1841 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1842 if (WasConstQualified)
1843 ObjType.addConst();
1844
Richard Smith66c96992012-02-18 22:04:06 +00001845 assert(I == N - 1 && "extracting subobject of scalar?");
1846 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001847 return handler.found(Index ? O->getComplexIntImag()
1848 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001849 } else {
1850 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001851 return handler.found(Index ? O->getComplexFloatImag()
1852 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001853 }
Richard Smithd62306a2011-11-10 06:34:14 +00001854 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001855 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001856 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001857 << Field;
1858 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001859 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001860 }
1861
Richard Smithd62306a2011-11-10 06:34:14 +00001862 // Next subobject is a class, struct or union field.
1863 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1864 if (RD->isUnion()) {
1865 const FieldDecl *UnionField = O->getUnionField();
1866 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001867 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001868 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1869 << handler.AccessKind << Field << !UnionField << UnionField;
1870 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001871 }
Richard Smithd62306a2011-11-10 06:34:14 +00001872 O = &O->getUnionValue();
1873 } else
1874 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001875
1876 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001877 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001878 if (WasConstQualified && !Field->isMutable())
1879 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001880
1881 if (ObjType.isVolatileQualified()) {
1882 if (Info.getLangOpts().CPlusPlus) {
1883 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001884 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1885 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001886 Info.Note(Field->getLocation(), diag::note_declared_at);
1887 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001888 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001889 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001890 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001891 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001892 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001893 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001894 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1895 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1896 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001897
1898 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001899 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001900 if (WasConstQualified)
1901 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001902 }
Richard Smithd62306a2011-11-10 06:34:14 +00001903
Richard Smithf57d8cb2011-12-09 22:58:01 +00001904 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001905 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001906 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1907 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001908 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001909 }
1910
Richard Smith3da88fa2013-04-26 14:36:30 +00001911 return handler.found(*O, ObjType);
1912}
1913
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001914namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001915struct ExtractSubobjectHandler {
1916 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001917 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001918
1919 static const AccessKinds AccessKind = AK_Read;
1920
1921 typedef bool result_type;
1922 bool failed() { return false; }
1923 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001924 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001925 return true;
1926 }
1927 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001928 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001929 return true;
1930 }
1931 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001932 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001933 return true;
1934 }
1935 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001936 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001937 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1938 return true;
1939 }
1940};
Richard Smith3229b742013-05-05 21:17:10 +00001941} // end anonymous namespace
1942
Richard Smith3da88fa2013-04-26 14:36:30 +00001943const AccessKinds ExtractSubobjectHandler::AccessKind;
1944
1945/// Extract the designated sub-object of an rvalue.
1946static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001947 const CompleteObject &Obj,
1948 const SubobjectDesignator &Sub,
1949 APValue &Result) {
1950 ExtractSubobjectHandler Handler = { Info, Result };
1951 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00001952}
1953
Richard Smith3229b742013-05-05 21:17:10 +00001954namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001955struct ModifySubobjectHandler {
1956 EvalInfo &Info;
1957 APValue &NewVal;
1958 const Expr *E;
1959
1960 typedef bool result_type;
1961 static const AccessKinds AccessKind = AK_Assign;
1962
1963 bool checkConst(QualType QT) {
1964 // Assigning to a const object has undefined behavior.
1965 if (QT.isConstQualified()) {
1966 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
1967 return false;
1968 }
1969 return true;
1970 }
1971
1972 bool failed() { return false; }
1973 bool found(APValue &Subobj, QualType SubobjType) {
1974 if (!checkConst(SubobjType))
1975 return false;
1976 // We've been given ownership of NewVal, so just swap it in.
1977 Subobj.swap(NewVal);
1978 return true;
1979 }
1980 bool found(APSInt &Value, QualType SubobjType) {
1981 if (!checkConst(SubobjType))
1982 return false;
1983 if (!NewVal.isInt()) {
1984 // Maybe trying to write a cast pointer value into a complex?
1985 Info.Diag(E);
1986 return false;
1987 }
1988 Value = NewVal.getInt();
1989 return true;
1990 }
1991 bool found(APFloat &Value, QualType SubobjType) {
1992 if (!checkConst(SubobjType))
1993 return false;
1994 Value = NewVal.getFloat();
1995 return true;
1996 }
1997 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1998 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
1999 }
2000};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002001} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002002
Richard Smith3229b742013-05-05 21:17:10 +00002003const AccessKinds ModifySubobjectHandler::AccessKind;
2004
Richard Smith3da88fa2013-04-26 14:36:30 +00002005/// Update the designated sub-object of an rvalue to the given value.
2006static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002007 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002008 const SubobjectDesignator &Sub,
2009 APValue &NewVal) {
2010 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002011 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002012}
2013
Richard Smith84f6dcf2012-02-02 01:16:57 +00002014/// Find the position where two subobject designators diverge, or equivalently
2015/// the length of the common initial subsequence.
2016static unsigned FindDesignatorMismatch(QualType ObjType,
2017 const SubobjectDesignator &A,
2018 const SubobjectDesignator &B,
2019 bool &WasArrayIndex) {
2020 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2021 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002022 if (!ObjType.isNull() &&
2023 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002024 // Next subobject is an array element.
2025 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2026 WasArrayIndex = true;
2027 return I;
2028 }
Richard Smith66c96992012-02-18 22:04:06 +00002029 if (ObjType->isAnyComplexType())
2030 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2031 else
2032 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002033 } else {
2034 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2035 WasArrayIndex = false;
2036 return I;
2037 }
2038 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2039 // Next subobject is a field.
2040 ObjType = FD->getType();
2041 else
2042 // Next subobject is a base class.
2043 ObjType = QualType();
2044 }
2045 }
2046 WasArrayIndex = false;
2047 return I;
2048}
2049
2050/// Determine whether the given subobject designators refer to elements of the
2051/// same array object.
2052static bool AreElementsOfSameArray(QualType ObjType,
2053 const SubobjectDesignator &A,
2054 const SubobjectDesignator &B) {
2055 if (A.Entries.size() != B.Entries.size())
2056 return false;
2057
2058 bool IsArray = A.MostDerivedArraySize != 0;
2059 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2060 // A is a subobject of the array element.
2061 return false;
2062
2063 // If A (and B) designates an array element, the last entry will be the array
2064 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2065 // of length 1' case, and the entire path must match.
2066 bool WasArrayIndex;
2067 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2068 return CommonLength >= A.Entries.size() - IsArray;
2069}
2070
Richard Smith3229b742013-05-05 21:17:10 +00002071/// Find the complete object to which an LValue refers.
2072CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2073 const LValue &LVal, QualType LValType) {
2074 if (!LVal.Base) {
2075 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2076 return CompleteObject();
2077 }
2078
2079 CallStackFrame *Frame = 0;
2080 if (LVal.CallIndex) {
2081 Frame = Info.getCallFrame(LVal.CallIndex);
2082 if (!Frame) {
2083 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2084 << AK << LVal.Base.is<const ValueDecl*>();
2085 NoteLValueLocation(Info, LVal.Base);
2086 return CompleteObject();
2087 }
2088 } else if (AK != AK_Read) {
2089 Info.Diag(E, diag::note_constexpr_modify_global);
2090 return CompleteObject();
2091 }
2092
2093 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2094 // is not a constant expression (even if the object is non-volatile). We also
2095 // apply this rule to C++98, in order to conform to the expected 'volatile'
2096 // semantics.
2097 if (LValType.isVolatileQualified()) {
2098 if (Info.getLangOpts().CPlusPlus)
2099 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2100 << AK << LValType;
2101 else
2102 Info.Diag(E);
2103 return CompleteObject();
2104 }
2105
2106 // Compute value storage location and type of base object.
2107 APValue *BaseVal = 0;
2108 QualType BaseType;
2109
2110 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2111 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2112 // In C++11, constexpr, non-volatile variables initialized with constant
2113 // expressions are constant expressions too. Inside constexpr functions,
2114 // parameters are constant expressions even if they're non-const.
2115 // In C++1y, objects local to a constant expression (those with a Frame) are
2116 // both readable and writable inside constant expressions.
2117 // In C, such things can also be folded, although they are not ICEs.
2118 const VarDecl *VD = dyn_cast<VarDecl>(D);
2119 if (VD) {
2120 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2121 VD = VDef;
2122 }
2123 if (!VD || VD->isInvalidDecl()) {
2124 Info.Diag(E);
2125 return CompleteObject();
2126 }
2127
2128 // Accesses of volatile-qualified objects are not allowed.
2129 BaseType = VD->getType();
2130 if (BaseType.isVolatileQualified()) {
2131 if (Info.getLangOpts().CPlusPlus) {
2132 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2133 << AK << 1 << VD;
2134 Info.Note(VD->getLocation(), diag::note_declared_at);
2135 } else {
2136 Info.Diag(E);
2137 }
2138 return CompleteObject();
2139 }
2140
2141 // Unless we're looking at a local variable or argument in a constexpr call,
2142 // the variable we're reading must be const.
2143 if (!Frame) {
2144 assert(AK == AK_Read && "can't modify non-local");
2145 if (VD->isConstexpr()) {
2146 // OK, we can read this variable.
2147 } else if (BaseType->isIntegralOrEnumerationType()) {
2148 if (!BaseType.isConstQualified()) {
2149 if (Info.getLangOpts().CPlusPlus) {
2150 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2151 Info.Note(VD->getLocation(), diag::note_declared_at);
2152 } else {
2153 Info.Diag(E);
2154 }
2155 return CompleteObject();
2156 }
2157 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2158 // We support folding of const floating-point types, in order to make
2159 // static const data members of such types (supported as an extension)
2160 // more useful.
2161 if (Info.getLangOpts().CPlusPlus11) {
2162 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2163 Info.Note(VD->getLocation(), diag::note_declared_at);
2164 } else {
2165 Info.CCEDiag(E);
2166 }
2167 } else {
2168 // FIXME: Allow folding of values of any literal type in all languages.
2169 if (Info.getLangOpts().CPlusPlus11) {
2170 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2171 Info.Note(VD->getLocation(), diag::note_declared_at);
2172 } else {
2173 Info.Diag(E);
2174 }
2175 return CompleteObject();
2176 }
2177 }
2178
2179 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2180 return CompleteObject();
2181 } else {
2182 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2183
2184 if (!Frame) {
2185 Info.Diag(E);
2186 return CompleteObject();
2187 }
2188
2189 BaseType = Base->getType();
2190 BaseVal = &Frame->Temporaries[Base];
2191
2192 // Volatile temporary objects cannot be accessed in constant expressions.
2193 if (BaseType.isVolatileQualified()) {
2194 if (Info.getLangOpts().CPlusPlus) {
2195 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2196 << AK << 0;
2197 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2198 } else {
2199 Info.Diag(E);
2200 }
2201 return CompleteObject();
2202 }
2203 }
2204
2205 // In C++1y, we can't safely access any mutable state when checking a
2206 // potential constant expression.
2207 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2208 Info.CheckingPotentialConstantExpression)
2209 return CompleteObject();
2210
2211 return CompleteObject(BaseVal, BaseType);
2212}
2213
Richard Smith243ef902013-05-05 23:31:59 +00002214/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2215/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2216/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002217///
2218/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002219/// \param Conv - The expression for which we are performing the conversion.
2220/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002221/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2222/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002223/// \param LVal - The glvalue on which we are attempting to perform this action.
2224/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002225static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002226 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002227 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002228 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002229 return false;
2230
Richard Smith3229b742013-05-05 21:17:10 +00002231 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002232 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002233 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2234 !Type.isVolatileQualified()) {
2235 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2236 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2237 // initializer until now for such expressions. Such an expression can't be
2238 // an ICE in C, so this only matters for fold.
2239 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2240 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002241 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002242 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002243 }
Richard Smith3229b742013-05-05 21:17:10 +00002244 APValue Lit;
2245 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2246 return false;
2247 CompleteObject LitObj(&Lit, Base->getType());
2248 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2249 } else if (isa<StringLiteral>(Base)) {
2250 // We represent a string literal array as an lvalue pointing at the
2251 // corresponding expression, rather than building an array of chars.
2252 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2253 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2254 CompleteObject StrObj(&Str, Base->getType());
2255 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002256 }
Richard Smith11562c52011-10-28 17:51:58 +00002257 }
2258
Richard Smith3229b742013-05-05 21:17:10 +00002259 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2260 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002261}
2262
2263/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002264static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002265 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002266 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002267 return false;
2268
Richard Smith3229b742013-05-05 21:17:10 +00002269 if (!Info.getLangOpts().CPlusPlus1y) {
2270 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002271 return false;
2272 }
2273
Richard Smith3229b742013-05-05 21:17:10 +00002274 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2275 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002276}
2277
Richard Smith243ef902013-05-05 23:31:59 +00002278static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2279 return T->isSignedIntegerType() &&
2280 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2281}
2282
2283namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002284struct CompoundAssignSubobjectHandler {
2285 EvalInfo &Info;
2286 const Expr *E;
2287 QualType PromotedLHSType;
2288 BinaryOperatorKind Opcode;
2289 const APValue &RHS;
2290
2291 static const AccessKinds AccessKind = AK_Assign;
2292
2293 typedef bool result_type;
2294
2295 bool checkConst(QualType QT) {
2296 // Assigning to a const object has undefined behavior.
2297 if (QT.isConstQualified()) {
2298 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2299 return false;
2300 }
2301 return true;
2302 }
2303
2304 bool failed() { return false; }
2305 bool found(APValue &Subobj, QualType SubobjType) {
2306 switch (Subobj.getKind()) {
2307 case APValue::Int:
2308 return found(Subobj.getInt(), SubobjType);
2309 case APValue::Float:
2310 return found(Subobj.getFloat(), SubobjType);
2311 case APValue::ComplexInt:
2312 case APValue::ComplexFloat:
2313 // FIXME: Implement complex compound assignment.
2314 Info.Diag(E);
2315 return false;
2316 case APValue::LValue:
2317 return foundPointer(Subobj, SubobjType);
2318 default:
2319 // FIXME: can this happen?
2320 Info.Diag(E);
2321 return false;
2322 }
2323 }
2324 bool found(APSInt &Value, QualType SubobjType) {
2325 if (!checkConst(SubobjType))
2326 return false;
2327
2328 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2329 // We don't support compound assignment on integer-cast-to-pointer
2330 // values.
2331 Info.Diag(E);
2332 return false;
2333 }
2334
2335 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2336 SubobjType, Value);
2337 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2338 return false;
2339 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2340 return true;
2341 }
2342 bool found(APFloat &Value, QualType SubobjType) {
2343 if (!checkConst(SubobjType))
2344 return false;
2345
2346 // FIXME: Implement.
2347 Info.Diag(E);
2348 return false;
2349 }
2350 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2351 if (!checkConst(SubobjType))
2352 return false;
2353
2354 QualType PointeeType;
2355 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2356 PointeeType = PT->getPointeeType();
2357 else {
2358 Info.Diag(E);
2359 return false;
2360 }
2361
2362 // FIXME: Implement.
2363 Info.Diag(E);
2364 return false;
2365 }
2366 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2367 llvm_unreachable("shouldn't encounter string elements here");
2368 }
2369};
2370} // end anonymous namespace
2371
2372const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2373
2374/// Perform a compound assignment of LVal <op>= RVal.
2375static bool handleCompoundAssignment(
2376 EvalInfo &Info, const Expr *E,
2377 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2378 BinaryOperatorKind Opcode, const APValue &RVal) {
2379 if (LVal.Designator.Invalid)
2380 return false;
2381
2382 if (!Info.getLangOpts().CPlusPlus1y) {
2383 Info.Diag(E);
2384 return false;
2385 }
2386
2387 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2388 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2389 RVal };
2390 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2391}
2392
2393namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002394struct IncDecSubobjectHandler {
2395 EvalInfo &Info;
2396 const Expr *E;
2397 AccessKinds AccessKind;
2398 APValue *Old;
2399
2400 typedef bool result_type;
2401
2402 bool checkConst(QualType QT) {
2403 // Assigning to a const object has undefined behavior.
2404 if (QT.isConstQualified()) {
2405 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2406 return false;
2407 }
2408 return true;
2409 }
2410
2411 bool failed() { return false; }
2412 bool found(APValue &Subobj, QualType SubobjType) {
2413 // Stash the old value. Also clear Old, so we don't clobber it later
2414 // if we're post-incrementing a complex.
2415 if (Old) {
2416 *Old = Subobj;
2417 Old = 0;
2418 }
2419
2420 switch (Subobj.getKind()) {
2421 case APValue::Int:
2422 return found(Subobj.getInt(), SubobjType);
2423 case APValue::Float:
2424 return found(Subobj.getFloat(), SubobjType);
2425 case APValue::ComplexInt:
2426 return found(Subobj.getComplexIntReal(),
2427 SubobjType->castAs<ComplexType>()->getElementType()
2428 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2429 case APValue::ComplexFloat:
2430 return found(Subobj.getComplexFloatReal(),
2431 SubobjType->castAs<ComplexType>()->getElementType()
2432 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2433 case APValue::LValue:
2434 return foundPointer(Subobj, SubobjType);
2435 default:
2436 // FIXME: can this happen?
2437 Info.Diag(E);
2438 return false;
2439 }
2440 }
2441 bool found(APSInt &Value, QualType SubobjType) {
2442 if (!checkConst(SubobjType))
2443 return false;
2444
2445 if (!SubobjType->isIntegerType()) {
2446 // We don't support increment / decrement on integer-cast-to-pointer
2447 // values.
2448 Info.Diag(E);
2449 return false;
2450 }
2451
2452 if (Old) *Old = APValue(Value);
2453
2454 // bool arithmetic promotes to int, and the conversion back to bool
2455 // doesn't reduce mod 2^n, so special-case it.
2456 if (SubobjType->isBooleanType()) {
2457 if (AccessKind == AK_Increment)
2458 Value = 1;
2459 else
2460 Value = !Value;
2461 return true;
2462 }
2463
2464 bool WasNegative = Value.isNegative();
2465 if (AccessKind == AK_Increment) {
2466 ++Value;
2467
2468 if (!WasNegative && Value.isNegative() &&
2469 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2470 APSInt ActualValue(Value, /*IsUnsigned*/true);
2471 HandleOverflow(Info, E, ActualValue, SubobjType);
2472 }
2473 } else {
2474 --Value;
2475
2476 if (WasNegative && !Value.isNegative() &&
2477 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2478 unsigned BitWidth = Value.getBitWidth();
2479 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2480 ActualValue.setBit(BitWidth);
2481 HandleOverflow(Info, E, ActualValue, SubobjType);
2482 }
2483 }
2484 return true;
2485 }
2486 bool found(APFloat &Value, QualType SubobjType) {
2487 if (!checkConst(SubobjType))
2488 return false;
2489
2490 if (Old) *Old = APValue(Value);
2491
2492 APFloat One(Value.getSemantics(), 1);
2493 if (AccessKind == AK_Increment)
2494 Value.add(One, APFloat::rmNearestTiesToEven);
2495 else
2496 Value.subtract(One, APFloat::rmNearestTiesToEven);
2497 return true;
2498 }
2499 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2500 if (!checkConst(SubobjType))
2501 return false;
2502
2503 QualType PointeeType;
2504 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2505 PointeeType = PT->getPointeeType();
2506 else {
2507 Info.Diag(E);
2508 return false;
2509 }
2510
2511 LValue LVal;
2512 LVal.setFrom(Info.Ctx, Subobj);
2513 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2514 AccessKind == AK_Increment ? 1 : -1))
2515 return false;
2516 LVal.moveInto(Subobj);
2517 return true;
2518 }
2519 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2520 llvm_unreachable("shouldn't encounter string elements here");
2521 }
2522};
2523} // end anonymous namespace
2524
2525/// Perform an increment or decrement on LVal.
2526static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2527 QualType LValType, bool IsIncrement, APValue *Old) {
2528 if (LVal.Designator.Invalid)
2529 return false;
2530
2531 if (!Info.getLangOpts().CPlusPlus1y) {
2532 Info.Diag(E);
2533 return false;
2534 }
2535
2536 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2537 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2538 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2539 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2540}
2541
Richard Smithe97cbd72011-11-11 04:05:33 +00002542/// Build an lvalue for the object argument of a member function call.
2543static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2544 LValue &This) {
2545 if (Object->getType()->isPointerType())
2546 return EvaluatePointer(Object, This, Info);
2547
2548 if (Object->isGLValue())
2549 return EvaluateLValue(Object, This, Info);
2550
Richard Smithd9f663b2013-04-22 15:31:51 +00002551 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002552 return EvaluateTemporary(Object, This, Info);
2553
2554 return false;
2555}
2556
2557/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2558/// lvalue referring to the result.
2559///
2560/// \param Info - Information about the ongoing evaluation.
2561/// \param BO - The member pointer access operation.
2562/// \param LV - Filled in with a reference to the resulting object.
2563/// \param IncludeMember - Specifies whether the member itself is included in
2564/// the resulting LValue subobject designator. This is not possible when
2565/// creating a bound member function.
2566/// \return The field or method declaration to which the member pointer refers,
2567/// or 0 if evaluation fails.
2568static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2569 const BinaryOperator *BO,
2570 LValue &LV,
2571 bool IncludeMember = true) {
2572 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2573
Richard Smith253c2a32012-01-27 01:14:48 +00002574 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2575 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002576 return 0;
2577
2578 MemberPtr MemPtr;
2579 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2580 return 0;
2581
2582 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2583 // member value, the behavior is undefined.
2584 if (!MemPtr.getDecl())
2585 return 0;
2586
Richard Smith253c2a32012-01-27 01:14:48 +00002587 if (!EvalObjOK)
2588 return 0;
2589
Richard Smith027bf112011-11-17 22:56:20 +00002590 if (MemPtr.isDerivedMember()) {
2591 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002592 // The end of the derived-to-base path for the base object must match the
2593 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002594 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002595 LV.Designator.Entries.size())
2596 return 0;
2597 unsigned PathLengthToMember =
2598 LV.Designator.Entries.size() - MemPtr.Path.size();
2599 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2600 const CXXRecordDecl *LVDecl = getAsBaseClass(
2601 LV.Designator.Entries[PathLengthToMember + I]);
2602 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2603 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2604 return 0;
2605 }
2606
2607 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002608 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2609 PathLengthToMember))
2610 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002611 } else if (!MemPtr.Path.empty()) {
2612 // Extend the LValue path with the member pointer's path.
2613 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2614 MemPtr.Path.size() + IncludeMember);
2615
2616 // Walk down to the appropriate base class.
2617 QualType LVType = BO->getLHS()->getType();
2618 if (const PointerType *PT = LVType->getAs<PointerType>())
2619 LVType = PT->getPointeeType();
2620 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2621 assert(RD && "member pointer access on non-class-type expression");
2622 // The first class in the path is that of the lvalue.
2623 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2624 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002625 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2626 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002627 RD = Base;
2628 }
2629 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002630 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2631 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002632 }
2633
2634 // Add the member. Note that we cannot build bound member functions here.
2635 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002636 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2637 if (!HandleLValueMember(Info, BO, LV, FD))
2638 return 0;
2639 } else if (const IndirectFieldDecl *IFD =
2640 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2641 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2642 return 0;
2643 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002644 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002645 }
Richard Smith027bf112011-11-17 22:56:20 +00002646 }
2647
2648 return MemPtr.getDecl();
2649}
2650
2651/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2652/// the provided lvalue, which currently refers to the base object.
2653static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2654 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002655 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002656 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002657 return false;
2658
Richard Smitha8105bc2012-01-06 16:39:00 +00002659 QualType TargetQT = E->getType();
2660 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2661 TargetQT = PT->getPointeeType();
2662
2663 // Check this cast lands within the final derived-to-base subobject path.
2664 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002665 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002666 << D.MostDerivedType << TargetQT;
2667 return false;
2668 }
2669
Richard Smith027bf112011-11-17 22:56:20 +00002670 // Check the type of the final cast. We don't need to check the path,
2671 // since a cast can only be formed if the path is unique.
2672 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002673 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2674 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002675 if (NewEntriesSize == D.MostDerivedPathLength)
2676 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2677 else
Richard Smith027bf112011-11-17 22:56:20 +00002678 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002679 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002680 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002681 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002682 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002683 }
Richard Smith027bf112011-11-17 22:56:20 +00002684
2685 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002686 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002687}
2688
Mike Stump876387b2009-10-27 22:09:17 +00002689namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002690enum EvalStmtResult {
2691 /// Evaluation failed.
2692 ESR_Failed,
2693 /// Hit a 'return' statement.
2694 ESR_Returned,
2695 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002696 ESR_Succeeded,
2697 /// Hit a 'continue' statement.
2698 ESR_Continue,
2699 /// Hit a 'break' statement.
2700 ESR_Break
Richard Smith254a73d2011-10-28 22:34:42 +00002701};
2702}
2703
Richard Smithd9f663b2013-04-22 15:31:51 +00002704static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2705 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2706 // We don't need to evaluate the initializer for a static local.
2707 if (!VD->hasLocalStorage())
2708 return true;
2709
2710 LValue Result;
2711 Result.set(VD, Info.CurrentCall->Index);
2712 APValue &Val = Info.CurrentCall->Temporaries[VD];
2713
2714 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2715 // Wipe out any partially-computed value, to allow tracking that this
2716 // evaluation failed.
2717 Val = APValue();
2718 return false;
2719 }
2720 }
2721
2722 return true;
2723}
2724
Richard Smith4e18ca52013-05-06 05:56:11 +00002725/// Evaluate a condition (either a variable declaration or an expression).
2726static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2727 const Expr *Cond, bool &Result) {
2728 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2729 return false;
2730 return EvaluateAsBooleanCondition(Cond, Result, Info);
2731}
2732
2733static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2734 const Stmt *S);
2735
2736/// Evaluate the body of a loop, and translate the result as appropriate.
2737static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
2738 const Stmt *Body) {
2739 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body)) {
2740 case ESR_Break:
2741 return ESR_Succeeded;
2742 case ESR_Succeeded:
2743 case ESR_Continue:
2744 return ESR_Continue;
2745 case ESR_Failed:
2746 case ESR_Returned:
2747 return ESR;
2748 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002749 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002750}
2751
Richard Smith254a73d2011-10-28 22:34:42 +00002752// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002753static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002754 const Stmt *S) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002755 // FIXME: Mark all temporaries in the current frame as destroyed at
2756 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002757 switch (S->getStmtClass()) {
2758 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002759 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002760 // Don't bother evaluating beyond an expression-statement which couldn't
2761 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00002762 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00002763 return ESR_Failed;
2764 return ESR_Succeeded;
2765 }
2766
2767 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002768 return ESR_Failed;
2769
2770 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002771 return ESR_Succeeded;
2772
Richard Smithd9f663b2013-04-22 15:31:51 +00002773 case Stmt::DeclStmtClass: {
2774 const DeclStmt *DS = cast<DeclStmt>(S);
2775 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2776 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2777 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2778 return ESR_Failed;
2779 return ESR_Succeeded;
2780 }
2781
Richard Smith357362d2011-12-13 06:39:58 +00002782 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002783 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002784 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002785 return ESR_Failed;
2786 return ESR_Returned;
2787 }
Richard Smith254a73d2011-10-28 22:34:42 +00002788
2789 case Stmt::CompoundStmtClass: {
2790 const CompoundStmt *CS = cast<CompoundStmt>(S);
2791 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2792 BE = CS->body_end(); BI != BE; ++BI) {
2793 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2794 if (ESR != ESR_Succeeded)
2795 return ESR;
2796 }
2797 return ESR_Succeeded;
2798 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002799
2800 case Stmt::IfStmtClass: {
2801 const IfStmt *IS = cast<IfStmt>(S);
2802
2803 // Evaluate the condition, as either a var decl or as an expression.
2804 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00002805 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00002806 return ESR_Failed;
2807
2808 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2809 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2810 if (ESR != ESR_Succeeded)
2811 return ESR;
2812 }
2813 return ESR_Succeeded;
2814 }
Richard Smith4e18ca52013-05-06 05:56:11 +00002815
2816 case Stmt::WhileStmtClass: {
2817 const WhileStmt *WS = cast<WhileStmt>(S);
2818 while (true) {
2819 bool Continue;
2820 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
2821 Continue))
2822 return ESR_Failed;
2823 if (!Continue)
2824 break;
2825
2826 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
2827 if (ESR != ESR_Continue)
2828 return ESR;
2829 }
2830 return ESR_Succeeded;
2831 }
2832
2833 case Stmt::DoStmtClass: {
2834 const DoStmt *DS = cast<DoStmt>(S);
2835 bool Continue;
2836 do {
2837 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody());
2838 if (ESR != ESR_Continue)
2839 return ESR;
2840
2841 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
2842 return ESR_Failed;
2843 } while (Continue);
2844 return ESR_Succeeded;
2845 }
2846
2847 case Stmt::ForStmtClass: {
2848 const ForStmt *FS = cast<ForStmt>(S);
2849 if (FS->getInit()) {
2850 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
2851 if (ESR != ESR_Succeeded)
2852 return ESR;
2853 }
2854 while (true) {
2855 bool Continue = true;
2856 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
2857 FS->getCond(), Continue))
2858 return ESR_Failed;
2859 if (!Continue)
2860 break;
2861
2862 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2863 if (ESR != ESR_Continue)
2864 return ESR;
2865
2866 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2867 return ESR_Failed;
2868 }
2869 return ESR_Succeeded;
2870 }
2871
Richard Smith896e0d72013-05-06 06:51:17 +00002872 case Stmt::CXXForRangeStmtClass: {
2873 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
2874
2875 // Initialize the __range variable.
2876 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
2877 if (ESR != ESR_Succeeded)
2878 return ESR;
2879
2880 // Create the __begin and __end iterators.
2881 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
2882 if (ESR != ESR_Succeeded)
2883 return ESR;
2884
2885 while (true) {
2886 // Condition: __begin != __end.
2887 bool Continue = true;
2888 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
2889 return ESR_Failed;
2890 if (!Continue)
2891 break;
2892
2893 // User's variable declaration, initialized by *__begin.
2894 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
2895 if (ESR != ESR_Succeeded)
2896 return ESR;
2897
2898 // Loop body.
2899 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2900 if (ESR != ESR_Continue)
2901 return ESR;
2902
2903 // Increment: ++__begin
2904 if (!EvaluateIgnoredValue(Info, FS->getInc()))
2905 return ESR_Failed;
2906 }
2907
2908 return ESR_Succeeded;
2909 }
2910
Richard Smith4e18ca52013-05-06 05:56:11 +00002911 case Stmt::ContinueStmtClass:
2912 return ESR_Continue;
2913
2914 case Stmt::BreakStmtClass:
2915 return ESR_Break;
Richard Smith254a73d2011-10-28 22:34:42 +00002916 }
2917}
2918
Richard Smithcc36f692011-12-22 02:22:31 +00002919/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2920/// default constructor. If so, we'll fold it whether or not it's marked as
2921/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2922/// so we need special handling.
2923static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002924 const CXXConstructorDecl *CD,
2925 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002926 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2927 return false;
2928
Richard Smith66e05fe2012-01-18 05:21:49 +00002929 // Value-initialization does not call a trivial default constructor, so such a
2930 // call is a core constant expression whether or not the constructor is
2931 // constexpr.
2932 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002933 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002934 // FIXME: If DiagDecl is an implicitly-declared special member function,
2935 // we should be much more explicit about why it's not constexpr.
2936 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2937 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2938 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002939 } else {
2940 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2941 }
2942 }
2943 return true;
2944}
2945
Richard Smith357362d2011-12-13 06:39:58 +00002946/// CheckConstexprFunction - Check that a function can be called in a constant
2947/// expression.
2948static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2949 const FunctionDecl *Declaration,
2950 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002951 // Potential constant expressions can contain calls to declared, but not yet
2952 // defined, constexpr functions.
2953 if (Info.CheckingPotentialConstantExpression && !Definition &&
2954 Declaration->isConstexpr())
2955 return false;
2956
Richard Smith357362d2011-12-13 06:39:58 +00002957 // Can we evaluate this function call?
2958 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2959 return true;
2960
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002961 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002962 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002963 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2964 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002965 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2966 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2967 << DiagDecl;
2968 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2969 } else {
2970 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2971 }
2972 return false;
2973}
2974
Richard Smithd62306a2011-11-10 06:34:14 +00002975namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002976typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002977}
2978
2979/// EvaluateArgs - Evaluate the arguments to a function call.
2980static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2981 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002982 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002983 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002984 I != E; ++I) {
2985 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2986 // If we're checking for a potential constant expression, evaluate all
2987 // initializers even if some of them fail.
2988 if (!Info.keepEvaluatingAfterFailure())
2989 return false;
2990 Success = false;
2991 }
2992 }
2993 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002994}
2995
Richard Smith254a73d2011-10-28 22:34:42 +00002996/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002997static bool HandleFunctionCall(SourceLocation CallLoc,
2998 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002999 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003000 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003001 ArgVector ArgValues(Args.size());
3002 if (!EvaluateArgs(Args, ArgValues, Info))
3003 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003004
Richard Smith253c2a32012-01-27 01:14:48 +00003005 if (!Info.CheckCallLimit(CallLoc))
3006 return false;
3007
3008 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003009
3010 // For a trivial copy or move assignment, perform an APValue copy. This is
3011 // essential for unions, where the operations performed by the assignment
3012 // operator cannot be represented as statements.
3013 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3014 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3015 assert(This &&
3016 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3017 LValue RHS;
3018 RHS.setFrom(Info.Ctx, ArgValues[0]);
3019 APValue RHSValue;
3020 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3021 RHS, RHSValue))
3022 return false;
3023 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3024 RHSValue))
3025 return false;
3026 This->moveInto(Result);
3027 return true;
3028 }
3029
Richard Smithd9f663b2013-04-22 15:31:51 +00003030 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003031 if (ESR == ESR_Succeeded) {
3032 if (Callee->getResultType()->isVoidType())
3033 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003034 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003035 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003036 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003037}
3038
Richard Smithd62306a2011-11-10 06:34:14 +00003039/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003040static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003041 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003042 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003043 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003044 ArgVector ArgValues(Args.size());
3045 if (!EvaluateArgs(Args, ArgValues, Info))
3046 return false;
3047
Richard Smith253c2a32012-01-27 01:14:48 +00003048 if (!Info.CheckCallLimit(CallLoc))
3049 return false;
3050
Richard Smith3607ffe2012-02-13 03:54:03 +00003051 const CXXRecordDecl *RD = Definition->getParent();
3052 if (RD->getNumVBases()) {
3053 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3054 return false;
3055 }
3056
Richard Smith253c2a32012-01-27 01:14:48 +00003057 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003058
3059 // If it's a delegating constructor, just delegate.
3060 if (Definition->isDelegatingConstructor()) {
3061 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003062 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3063 return false;
3064 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003065 }
3066
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003067 // For a trivial copy or move constructor, perform an APValue copy. This is
3068 // essential for unions, where the operations performed by the constructor
3069 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003070 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003071 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3072 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003073 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003074 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003075 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003076 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003077 }
3078
3079 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003080 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003081 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3082 std::distance(RD->field_begin(), RD->field_end()));
3083
John McCalld7bca762012-05-01 00:38:49 +00003084 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003085 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3086
Richard Smith253c2a32012-01-27 01:14:48 +00003087 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003088 unsigned BasesSeen = 0;
3089#ifndef NDEBUG
3090 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3091#endif
3092 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3093 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003094 LValue Subobject = This;
3095 APValue *Value = &Result;
3096
3097 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003098 if ((*I)->isBaseInitializer()) {
3099 QualType BaseType((*I)->getBaseClass(), 0);
3100#ifndef NDEBUG
3101 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003102 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003103 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3104 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3105 "base class initializers not in expected order");
3106 ++BaseIt;
3107#endif
John McCalld7bca762012-05-01 00:38:49 +00003108 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3109 BaseType->getAsCXXRecordDecl(), &Layout))
3110 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003111 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003112 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003113 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3114 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003115 if (RD->isUnion()) {
3116 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003117 Value = &Result.getUnionValue();
3118 } else {
3119 Value = &Result.getStructField(FD->getFieldIndex());
3120 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003121 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003122 // Walk the indirect field decl's chain to find the object to initialize,
3123 // and make sure we've initialized every step along it.
3124 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3125 CE = IFD->chain_end();
3126 C != CE; ++C) {
3127 FieldDecl *FD = cast<FieldDecl>(*C);
3128 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3129 // Switch the union field if it differs. This happens if we had
3130 // preceding zero-initialization, and we're now initializing a union
3131 // subobject other than the first.
3132 // FIXME: In this case, the values of the other subobjects are
3133 // specified, since zero-initialization sets all padding bits to zero.
3134 if (Value->isUninit() ||
3135 (Value->isUnion() && Value->getUnionField() != FD)) {
3136 if (CD->isUnion())
3137 *Value = APValue(FD);
3138 else
3139 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3140 std::distance(CD->field_begin(), CD->field_end()));
3141 }
John McCalld7bca762012-05-01 00:38:49 +00003142 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3143 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003144 if (CD->isUnion())
3145 Value = &Value->getUnionValue();
3146 else
3147 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003148 }
Richard Smithd62306a2011-11-10 06:34:14 +00003149 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003150 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003151 }
Richard Smith253c2a32012-01-27 01:14:48 +00003152
Richard Smithb228a862012-02-15 02:18:13 +00003153 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
3154 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00003155 ? CCEK_Constant : CCEK_MemberInit)) {
3156 // If we're checking for a potential constant expression, evaluate all
3157 // initializers even if some of them fail.
3158 if (!Info.keepEvaluatingAfterFailure())
3159 return false;
3160 Success = false;
3161 }
Richard Smithd62306a2011-11-10 06:34:14 +00003162 }
3163
Richard Smithd9f663b2013-04-22 15:31:51 +00003164 return Success &&
3165 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003166}
3167
Eli Friedman9a156e52008-11-12 09:44:48 +00003168//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003169// Generic Evaluation
3170//===----------------------------------------------------------------------===//
3171namespace {
3172
Richard Smithf57d8cb2011-12-09 22:58:01 +00003173// FIXME: RetTy is always bool. Remove it.
3174template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003175class ExprEvaluatorBase
3176 : public ConstStmtVisitor<Derived, RetTy> {
3177private:
Richard Smith2e312c82012-03-03 22:46:17 +00003178 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003179 return static_cast<Derived*>(this)->Success(V, E);
3180 }
Richard Smithfddd3842011-12-30 21:15:51 +00003181 RetTy DerivedZeroInitialization(const Expr *E) {
3182 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003183 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003184
Richard Smith17100ba2012-02-16 02:46:34 +00003185 // Check whether a conditional operator with a non-constant condition is a
3186 // potential constant expression. If neither arm is a potential constant
3187 // expression, then the conditional operator is not either.
3188 template<typename ConditionalOperator>
3189 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3190 assert(Info.CheckingPotentialConstantExpression);
3191
3192 // Speculatively evaluate both arms.
3193 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003194 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003195 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3196
3197 StmtVisitorTy::Visit(E->getFalseExpr());
3198 if (Diag.empty())
3199 return;
3200
3201 Diag.clear();
3202 StmtVisitorTy::Visit(E->getTrueExpr());
3203 if (Diag.empty())
3204 return;
3205 }
3206
3207 Error(E, diag::note_constexpr_conditional_never_const);
3208 }
3209
3210
3211 template<typename ConditionalOperator>
3212 bool HandleConditionalOperator(const ConditionalOperator *E) {
3213 bool BoolResult;
3214 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3215 if (Info.CheckingPotentialConstantExpression)
3216 CheckPotentialConstantConditional(E);
3217 return false;
3218 }
3219
3220 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3221 return StmtVisitorTy::Visit(EvalExpr);
3222 }
3223
Peter Collingbournee9200682011-05-13 03:29:01 +00003224protected:
3225 EvalInfo &Info;
3226 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3227 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3228
Richard Smith92b1ce02011-12-12 09:28:41 +00003229 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003230 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003231 }
3232
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003233 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3234
3235public:
3236 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3237
3238 EvalInfo &getEvalInfo() { return Info; }
3239
Richard Smithf57d8cb2011-12-09 22:58:01 +00003240 /// Report an evaluation error. This should only be called when an error is
3241 /// first discovered. When propagating an error, just return false.
3242 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003243 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003244 return false;
3245 }
3246 bool Error(const Expr *E) {
3247 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3248 }
3249
Peter Collingbournee9200682011-05-13 03:29:01 +00003250 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003251 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003252 }
3253 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003254 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003255 }
3256
3257 RetTy VisitParenExpr(const ParenExpr *E)
3258 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3259 RetTy VisitUnaryExtension(const UnaryOperator *E)
3260 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3261 RetTy VisitUnaryPlus(const UnaryOperator *E)
3262 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3263 RetTy VisitChooseExpr(const ChooseExpr *E)
3264 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3265 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3266 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003267 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3268 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003269 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3270 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003271 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3272 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003273 // We cannot create any objects for which cleanups are required, so there is
3274 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3275 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3276 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003277
Richard Smith6d6ecc32011-12-12 12:46:16 +00003278 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3279 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3280 return static_cast<Derived*>(this)->VisitCastExpr(E);
3281 }
3282 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3283 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3284 return static_cast<Derived*>(this)->VisitCastExpr(E);
3285 }
3286
Richard Smith027bf112011-11-17 22:56:20 +00003287 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3288 switch (E->getOpcode()) {
3289 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003290 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003291
3292 case BO_Comma:
3293 VisitIgnoredValue(E->getLHS());
3294 return StmtVisitorTy::Visit(E->getRHS());
3295
3296 case BO_PtrMemD:
3297 case BO_PtrMemI: {
3298 LValue Obj;
3299 if (!HandleMemberPointerAccess(Info, E, Obj))
3300 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003301 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003302 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003303 return false;
3304 return DerivedSuccess(Result, E);
3305 }
3306 }
3307 }
3308
Peter Collingbournee9200682011-05-13 03:29:01 +00003309 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003310 // Evaluate and cache the common expression. We treat it as a temporary,
3311 // even though it's not quite the same thing.
3312 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3313 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003314 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003315
Richard Smith17100ba2012-02-16 02:46:34 +00003316 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003317 }
3318
3319 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003320 bool IsBcpCall = false;
3321 // If the condition (ignoring parens) is a __builtin_constant_p call,
3322 // the result is a constant expression if it can be folded without
3323 // side-effects. This is an important GNU extension. See GCC PR38377
3324 // for discussion.
3325 if (const CallExpr *CallCE =
3326 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3327 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3328 IsBcpCall = true;
3329
3330 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3331 // constant expression; we can't check whether it's potentially foldable.
3332 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3333 return false;
3334
3335 FoldConstant Fold(Info);
3336
Richard Smith17100ba2012-02-16 02:46:34 +00003337 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003338 return false;
3339
3340 if (IsBcpCall)
3341 Fold.Fold(Info);
3342
3343 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003344 }
3345
3346 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003347 APValue &Value = Info.CurrentCall->Temporaries[E];
3348 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003349 const Expr *Source = E->getSourceExpr();
3350 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003351 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003352 if (Source == E) { // sanity checking.
3353 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003354 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003355 }
3356 return StmtVisitorTy::Visit(Source);
3357 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003358 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003359 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003360
Richard Smith254a73d2011-10-28 22:34:42 +00003361 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003362 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003363 QualType CalleeType = Callee->getType();
3364
Richard Smith254a73d2011-10-28 22:34:42 +00003365 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003366 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003367 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003368 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003369
Richard Smithe97cbd72011-11-11 04:05:33 +00003370 // Extract function decl and 'this' pointer from the callee.
3371 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003372 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003373 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3374 // Explicit bound member calls, such as x.f() or p->g();
3375 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003376 return false;
3377 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003378 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003379 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003380 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3381 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003382 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3383 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003384 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003385 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003386 return Error(Callee);
3387
3388 FD = dyn_cast<FunctionDecl>(Member);
3389 if (!FD)
3390 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003391 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003392 LValue Call;
3393 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003394 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003395
Richard Smitha8105bc2012-01-06 16:39:00 +00003396 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003397 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003398 FD = dyn_cast_or_null<FunctionDecl>(
3399 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003400 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003401 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003402
3403 // Overloaded operator calls to member functions are represented as normal
3404 // calls with '*this' as the first argument.
3405 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3406 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003407 // FIXME: When selecting an implicit conversion for an overloaded
3408 // operator delete, we sometimes try to evaluate calls to conversion
3409 // operators without a 'this' parameter!
3410 if (Args.empty())
3411 return Error(E);
3412
Richard Smithe97cbd72011-11-11 04:05:33 +00003413 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3414 return false;
3415 This = &ThisVal;
3416 Args = Args.slice(1);
3417 }
3418
3419 // Don't call function pointers which have been cast to some other type.
3420 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003421 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003422 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003423 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003424
Richard Smith47b34932012-02-01 02:39:43 +00003425 if (This && !This->checkSubobject(Info, E, CSK_This))
3426 return false;
3427
Richard Smith3607ffe2012-02-13 03:54:03 +00003428 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3429 // calls to such functions in constant expressions.
3430 if (This && !HasQualifier &&
3431 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3432 return Error(E, diag::note_constexpr_virtual_call);
3433
Richard Smith357362d2011-12-13 06:39:58 +00003434 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003435 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003436 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003437
Richard Smith357362d2011-12-13 06:39:58 +00003438 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003439 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3440 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003441 return false;
3442
Richard Smithb228a862012-02-15 02:18:13 +00003443 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003444 }
3445
Richard Smith11562c52011-10-28 17:51:58 +00003446 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3447 return StmtVisitorTy::Visit(E->getInitializer());
3448 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003449 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003450 if (E->getNumInits() == 0)
3451 return DerivedZeroInitialization(E);
3452 if (E->getNumInits() == 1)
3453 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003454 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003455 }
3456 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003457 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003458 }
3459 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003460 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003461 }
Richard Smith027bf112011-11-17 22:56:20 +00003462 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003463 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003464 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003465
Richard Smithd62306a2011-11-10 06:34:14 +00003466 /// A member expression where the object is a prvalue is itself a prvalue.
3467 RetTy VisitMemberExpr(const MemberExpr *E) {
3468 assert(!E->isArrow() && "missing call to bound member function?");
3469
Richard Smith2e312c82012-03-03 22:46:17 +00003470 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003471 if (!Evaluate(Val, Info, E->getBase()))
3472 return false;
3473
3474 QualType BaseTy = E->getBase()->getType();
3475
3476 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003477 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003478 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003479 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003480 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3481
Richard Smith3229b742013-05-05 21:17:10 +00003482 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003483 SubobjectDesignator Designator(BaseTy);
3484 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003485
Richard Smith3229b742013-05-05 21:17:10 +00003486 APValue Result;
3487 return extractSubobject(Info, E, Obj, Designator, Result) &&
3488 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003489 }
3490
Richard Smith11562c52011-10-28 17:51:58 +00003491 RetTy VisitCastExpr(const CastExpr *E) {
3492 switch (E->getCastKind()) {
3493 default:
3494 break;
3495
David Chisnallfa35df62012-01-16 17:27:18 +00003496 case CK_AtomicToNonAtomic:
3497 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003498 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003499 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003500 return StmtVisitorTy::Visit(E->getSubExpr());
3501
3502 case CK_LValueToRValue: {
3503 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003504 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3505 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003506 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003507 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003508 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003509 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003510 return false;
3511 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003512 }
3513 }
3514
Richard Smithf57d8cb2011-12-09 22:58:01 +00003515 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003516 }
3517
Richard Smith243ef902013-05-05 23:31:59 +00003518 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3519 return VisitUnaryPostIncDec(UO);
3520 }
3521 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3522 return VisitUnaryPostIncDec(UO);
3523 }
3524 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3525 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3526 return Error(UO);
3527
3528 LValue LVal;
3529 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3530 return false;
3531 APValue RVal;
3532 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3533 UO->isIncrementOp(), &RVal))
3534 return false;
3535 return DerivedSuccess(RVal, UO);
3536 }
3537
Richard Smith4a678122011-10-24 18:44:57 +00003538 /// Visit a value which is evaluated, but whose value is ignored.
3539 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003540 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003541 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003542};
3543
3544}
3545
3546//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003547// Common base class for lvalue and temporary evaluation.
3548//===----------------------------------------------------------------------===//
3549namespace {
3550template<class Derived>
3551class LValueExprEvaluatorBase
3552 : public ExprEvaluatorBase<Derived, bool> {
3553protected:
3554 LValue &Result;
3555 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3556 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3557
3558 bool Success(APValue::LValueBase B) {
3559 Result.set(B);
3560 return true;
3561 }
3562
3563public:
3564 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3565 ExprEvaluatorBaseTy(Info), Result(Result) {}
3566
Richard Smith2e312c82012-03-03 22:46:17 +00003567 bool Success(const APValue &V, const Expr *E) {
3568 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003569 return true;
3570 }
Richard Smith027bf112011-11-17 22:56:20 +00003571
Richard Smith027bf112011-11-17 22:56:20 +00003572 bool VisitMemberExpr(const MemberExpr *E) {
3573 // Handle non-static data members.
3574 QualType BaseTy;
3575 if (E->isArrow()) {
3576 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3577 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003578 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003579 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003580 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003581 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3582 return false;
3583 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003584 } else {
3585 if (!this->Visit(E->getBase()))
3586 return false;
3587 BaseTy = E->getBase()->getType();
3588 }
Richard Smith027bf112011-11-17 22:56:20 +00003589
Richard Smith1b78b3d2012-01-25 22:15:11 +00003590 const ValueDecl *MD = E->getMemberDecl();
3591 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3592 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3593 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3594 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003595 if (!HandleLValueMember(this->Info, E, Result, FD))
3596 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003597 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003598 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3599 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003600 } else
3601 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003602
Richard Smith1b78b3d2012-01-25 22:15:11 +00003603 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003604 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003605 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003606 RefValue))
3607 return false;
3608 return Success(RefValue, E);
3609 }
3610 return true;
3611 }
3612
3613 bool VisitBinaryOperator(const BinaryOperator *E) {
3614 switch (E->getOpcode()) {
3615 default:
3616 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3617
3618 case BO_PtrMemD:
3619 case BO_PtrMemI:
3620 return HandleMemberPointerAccess(this->Info, E, Result);
3621 }
3622 }
3623
3624 bool VisitCastExpr(const CastExpr *E) {
3625 switch (E->getCastKind()) {
3626 default:
3627 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3628
3629 case CK_DerivedToBase:
3630 case CK_UncheckedDerivedToBase: {
3631 if (!this->Visit(E->getSubExpr()))
3632 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003633
3634 // Now figure out the necessary offset to add to the base LV to get from
3635 // the derived class to the base class.
3636 QualType Type = E->getSubExpr()->getType();
3637
3638 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3639 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003640 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003641 *PathI))
3642 return false;
3643 Type = (*PathI)->getType();
3644 }
3645
3646 return true;
3647 }
3648 }
3649 }
3650};
3651}
3652
3653//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003654// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003655//
3656// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3657// function designators (in C), decl references to void objects (in C), and
3658// temporaries (if building with -Wno-address-of-temporary).
3659//
3660// LValue evaluation produces values comprising a base expression of one of the
3661// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003662// - Declarations
3663// * VarDecl
3664// * FunctionDecl
3665// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003666// * CompoundLiteralExpr in C
3667// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003668// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003669// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003670// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003671// * ObjCEncodeExpr
3672// * AddrLabelExpr
3673// * BlockExpr
3674// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003675// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003676// * Any Expr, with a CallIndex indicating the function in which the temporary
3677// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003678// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003679//===----------------------------------------------------------------------===//
3680namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003681class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003682 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003683public:
Richard Smith027bf112011-11-17 22:56:20 +00003684 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3685 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003686
Richard Smith11562c52011-10-28 17:51:58 +00003687 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003688 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003689
Peter Collingbournee9200682011-05-13 03:29:01 +00003690 bool VisitDeclRefExpr(const DeclRefExpr *E);
3691 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003692 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003693 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3694 bool VisitMemberExpr(const MemberExpr *E);
3695 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3696 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003697 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003698 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003699 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3700 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003701 bool VisitUnaryReal(const UnaryOperator *E);
3702 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003703 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3704 return VisitUnaryPreIncDec(UO);
3705 }
3706 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3707 return VisitUnaryPreIncDec(UO);
3708 }
Richard Smith3229b742013-05-05 21:17:10 +00003709 bool VisitBinAssign(const BinaryOperator *BO);
3710 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003711
Peter Collingbournee9200682011-05-13 03:29:01 +00003712 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003713 switch (E->getCastKind()) {
3714 default:
Richard Smith027bf112011-11-17 22:56:20 +00003715 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003716
Eli Friedmance3e02a2011-10-11 00:13:24 +00003717 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003718 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003719 if (!Visit(E->getSubExpr()))
3720 return false;
3721 Result.Designator.setInvalid();
3722 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003723
Richard Smith027bf112011-11-17 22:56:20 +00003724 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003725 if (!Visit(E->getSubExpr()))
3726 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003727 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003728 }
3729 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003730};
3731} // end anonymous namespace
3732
Richard Smith11562c52011-10-28 17:51:58 +00003733/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003734/// expressions which are not glvalues, in two cases:
3735/// * function designators in C, and
3736/// * "extern void" objects
3737static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3738 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3739 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003740 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003741}
3742
Peter Collingbournee9200682011-05-13 03:29:01 +00003743bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003744 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3745 return Success(FD);
3746 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003747 return VisitVarDecl(E, VD);
3748 return Error(E);
3749}
Richard Smith733237d2011-10-24 23:14:33 +00003750
Richard Smith11562c52011-10-28 17:51:58 +00003751bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003752 CallStackFrame *Frame = 0;
3753 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3754 Frame = Info.CurrentCall;
3755
Richard Smithfec09922011-11-01 16:57:24 +00003756 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003757 if (Frame) {
3758 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003759 return true;
3760 }
Richard Smithce40ad62011-11-12 22:28:03 +00003761 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003762 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003763
Richard Smith3229b742013-05-05 21:17:10 +00003764 APValue *V;
3765 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003766 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003767 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003768}
3769
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003770bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3771 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003772 if (E->getType()->isRecordType())
3773 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003774
Richard Smithb228a862012-02-15 02:18:13 +00003775 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003776 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3777 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003778}
3779
Peter Collingbournee9200682011-05-13 03:29:01 +00003780bool
3781LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003782 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3783 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3784 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003785 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003786}
3787
Richard Smith6e525142011-12-27 12:18:28 +00003788bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003789 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003790 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003791
3792 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3793 << E->getExprOperand()->getType()
3794 << E->getExprOperand()->getSourceRange();
3795 return false;
Richard Smith6e525142011-12-27 12:18:28 +00003796}
3797
Francois Pichet0066db92012-04-16 04:08:35 +00003798bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3799 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00003800}
Francois Pichet0066db92012-04-16 04:08:35 +00003801
Peter Collingbournee9200682011-05-13 03:29:01 +00003802bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003803 // Handle static data members.
3804 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3805 VisitIgnoredValue(E->getBase());
3806 return VisitVarDecl(E, VD);
3807 }
3808
Richard Smith254a73d2011-10-28 22:34:42 +00003809 // Handle static member functions.
3810 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3811 if (MD->isStatic()) {
3812 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003813 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003814 }
3815 }
3816
Richard Smithd62306a2011-11-10 06:34:14 +00003817 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003818 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003819}
3820
Peter Collingbournee9200682011-05-13 03:29:01 +00003821bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003822 // FIXME: Deal with vectors as array subscript bases.
3823 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003824 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003825
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003826 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003827 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003828
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003829 APSInt Index;
3830 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003831 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003832 int64_t IndexValue
3833 = Index.isSigned() ? Index.getSExtValue()
3834 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003835
Richard Smitha8105bc2012-01-06 16:39:00 +00003836 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003837}
Eli Friedman9a156e52008-11-12 09:44:48 +00003838
Peter Collingbournee9200682011-05-13 03:29:01 +00003839bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003840 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003841}
3842
Richard Smith66c96992012-02-18 22:04:06 +00003843bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3844 if (!Visit(E->getSubExpr()))
3845 return false;
3846 // __real is a no-op on scalar lvalues.
3847 if (E->getSubExpr()->getType()->isAnyComplexType())
3848 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3849 return true;
3850}
3851
3852bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3853 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3854 "lvalue __imag__ on scalar?");
3855 if (!Visit(E->getSubExpr()))
3856 return false;
3857 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3858 return true;
3859}
3860
Richard Smith243ef902013-05-05 23:31:59 +00003861bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
3862 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003863 return Error(UO);
3864
3865 if (!this->Visit(UO->getSubExpr()))
3866 return false;
3867
Richard Smith243ef902013-05-05 23:31:59 +00003868 return handleIncDec(
3869 this->Info, UO, Result, UO->getSubExpr()->getType(),
3870 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00003871}
3872
3873bool LValueExprEvaluator::VisitCompoundAssignOperator(
3874 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00003875 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003876 return Error(CAO);
3877
Richard Smith3229b742013-05-05 21:17:10 +00003878 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00003879
3880 // The overall lvalue result is the result of evaluating the LHS.
3881 if (!this->Visit(CAO->getLHS())) {
3882 if (Info.keepEvaluatingAfterFailure())
3883 Evaluate(RHS, this->Info, CAO->getRHS());
3884 return false;
3885 }
3886
Richard Smith3229b742013-05-05 21:17:10 +00003887 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
3888 return false;
3889
Richard Smith43e77732013-05-07 04:50:00 +00003890 return handleCompoundAssignment(
3891 this->Info, CAO,
3892 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
3893 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00003894}
3895
3896bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00003897 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3898 return Error(E);
3899
Richard Smith3229b742013-05-05 21:17:10 +00003900 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00003901
3902 if (!this->Visit(E->getLHS())) {
3903 if (Info.keepEvaluatingAfterFailure())
3904 Evaluate(NewVal, this->Info, E->getRHS());
3905 return false;
3906 }
3907
Richard Smith3229b742013-05-05 21:17:10 +00003908 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3909 return false;
Richard Smith243ef902013-05-05 23:31:59 +00003910
3911 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00003912 NewVal);
3913}
3914
Eli Friedman9a156e52008-11-12 09:44:48 +00003915//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003916// Pointer Evaluation
3917//===----------------------------------------------------------------------===//
3918
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003919namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003920class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003921 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003922 LValue &Result;
3923
Peter Collingbournee9200682011-05-13 03:29:01 +00003924 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003925 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003926 return true;
3927 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003928public:
Mike Stump11289f42009-09-09 15:08:12 +00003929
John McCall45d55e42010-05-07 21:00:08 +00003930 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003931 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003932
Richard Smith2e312c82012-03-03 22:46:17 +00003933 bool Success(const APValue &V, const Expr *E) {
3934 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00003935 return true;
3936 }
Richard Smithfddd3842011-12-30 21:15:51 +00003937 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003938 return Success((Expr*)0);
3939 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003940
John McCall45d55e42010-05-07 21:00:08 +00003941 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003942 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003943 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003944 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003945 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003946 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003947 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003948 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003949 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003950 bool VisitCallExpr(const CallExpr *E);
3951 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003952 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003953 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003954 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003955 }
Richard Smithd62306a2011-11-10 06:34:14 +00003956 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3957 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003958 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003959 Result = *Info.CurrentCall->This;
3960 return true;
3961 }
John McCallc07a0c72011-02-17 10:25:35 +00003962
Eli Friedman449fe542009-03-23 04:56:01 +00003963 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003964};
Chris Lattner05706e882008-07-11 18:11:29 +00003965} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003966
John McCall45d55e42010-05-07 21:00:08 +00003967static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003968 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003969 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003970}
3971
John McCall45d55e42010-05-07 21:00:08 +00003972bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003973 if (E->getOpcode() != BO_Add &&
3974 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003975 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003976
Chris Lattner05706e882008-07-11 18:11:29 +00003977 const Expr *PExp = E->getLHS();
3978 const Expr *IExp = E->getRHS();
3979 if (IExp->getType()->isPointerType())
3980 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003981
Richard Smith253c2a32012-01-27 01:14:48 +00003982 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3983 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003984 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003985
John McCall45d55e42010-05-07 21:00:08 +00003986 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003987 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003988 return false;
3989 int64_t AdditionalOffset
3990 = Offset.isSigned() ? Offset.getSExtValue()
3991 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003992 if (E->getOpcode() == BO_Sub)
3993 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003994
Ted Kremenek28831752012-08-23 20:46:57 +00003995 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003996 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3997 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003998}
Eli Friedman9a156e52008-11-12 09:44:48 +00003999
John McCall45d55e42010-05-07 21:00:08 +00004000bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4001 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004002}
Mike Stump11289f42009-09-09 15:08:12 +00004003
Peter Collingbournee9200682011-05-13 03:29:01 +00004004bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4005 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004006
Eli Friedman847a2bc2009-12-27 05:43:15 +00004007 switch (E->getCastKind()) {
4008 default:
4009 break;
4010
John McCalle3027922010-08-25 11:45:40 +00004011 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004012 case CK_CPointerToObjCPointerCast:
4013 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004014 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004015 if (!Visit(SubExpr))
4016 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004017 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4018 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4019 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004020 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004021 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004022 if (SubExpr->getType()->isVoidPointerType())
4023 CCEDiag(E, diag::note_constexpr_invalid_cast)
4024 << 3 << SubExpr->getType();
4025 else
4026 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4027 }
Richard Smith96e0c102011-11-04 02:25:55 +00004028 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004029
Anders Carlsson18275092010-10-31 20:41:46 +00004030 case CK_DerivedToBase:
4031 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004032 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004033 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004034 if (!Result.Base && Result.Offset.isZero())
4035 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004036
Richard Smithd62306a2011-11-10 06:34:14 +00004037 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004038 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00004039 QualType Type =
4040 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00004041
Richard Smithd62306a2011-11-10 06:34:14 +00004042 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00004043 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004044 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
4045 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00004046 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004047 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00004048 }
4049
Anders Carlsson18275092010-10-31 20:41:46 +00004050 return true;
4051 }
4052
Richard Smith027bf112011-11-17 22:56:20 +00004053 case CK_BaseToDerived:
4054 if (!Visit(E->getSubExpr()))
4055 return false;
4056 if (!Result.Base && Result.Offset.isZero())
4057 return true;
4058 return HandleBaseToDerivedCast(Info, E, Result);
4059
Richard Smith0b0a0b62011-10-29 20:57:55 +00004060 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004061 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004062 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004063
John McCalle3027922010-08-25 11:45:40 +00004064 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004065 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4066
Richard Smith2e312c82012-03-03 22:46:17 +00004067 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004068 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004069 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004070
John McCall45d55e42010-05-07 21:00:08 +00004071 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004072 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4073 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004074 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004075 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004076 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004077 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004078 return true;
4079 } else {
4080 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004081 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004082 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004083 }
4084 }
John McCalle3027922010-08-25 11:45:40 +00004085 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004086 if (SubExpr->isGLValue()) {
4087 if (!EvaluateLValue(SubExpr, Result, Info))
4088 return false;
4089 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004090 Result.set(SubExpr, Info.CurrentCall->Index);
4091 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4092 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004093 return false;
4094 }
Richard Smith96e0c102011-11-04 02:25:55 +00004095 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004096 if (const ConstantArrayType *CAT
4097 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4098 Result.addArray(Info, E, CAT);
4099 else
4100 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004101 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004102
John McCalle3027922010-08-25 11:45:40 +00004103 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004104 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004105 }
4106
Richard Smith11562c52011-10-28 17:51:58 +00004107 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004108}
Chris Lattner05706e882008-07-11 18:11:29 +00004109
Peter Collingbournee9200682011-05-13 03:29:01 +00004110bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004111 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004112 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004113
Peter Collingbournee9200682011-05-13 03:29:01 +00004114 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004115}
Chris Lattner05706e882008-07-11 18:11:29 +00004116
4117//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004118// Member Pointer Evaluation
4119//===----------------------------------------------------------------------===//
4120
4121namespace {
4122class MemberPointerExprEvaluator
4123 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4124 MemberPtr &Result;
4125
4126 bool Success(const ValueDecl *D) {
4127 Result = MemberPtr(D);
4128 return true;
4129 }
4130public:
4131
4132 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4133 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4134
Richard Smith2e312c82012-03-03 22:46:17 +00004135 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004136 Result.setFrom(V);
4137 return true;
4138 }
Richard Smithfddd3842011-12-30 21:15:51 +00004139 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004140 return Success((const ValueDecl*)0);
4141 }
4142
4143 bool VisitCastExpr(const CastExpr *E);
4144 bool VisitUnaryAddrOf(const UnaryOperator *E);
4145};
4146} // end anonymous namespace
4147
4148static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4149 EvalInfo &Info) {
4150 assert(E->isRValue() && E->getType()->isMemberPointerType());
4151 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4152}
4153
4154bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4155 switch (E->getCastKind()) {
4156 default:
4157 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4158
4159 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004160 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004161 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004162
4163 case CK_BaseToDerivedMemberPointer: {
4164 if (!Visit(E->getSubExpr()))
4165 return false;
4166 if (E->path_empty())
4167 return true;
4168 // Base-to-derived member pointer casts store the path in derived-to-base
4169 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4170 // the wrong end of the derived->base arc, so stagger the path by one class.
4171 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4172 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4173 PathI != PathE; ++PathI) {
4174 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4175 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4176 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004177 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004178 }
4179 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4180 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004181 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004182 return true;
4183 }
4184
4185 case CK_DerivedToBaseMemberPointer:
4186 if (!Visit(E->getSubExpr()))
4187 return false;
4188 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4189 PathE = E->path_end(); PathI != PathE; ++PathI) {
4190 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4191 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4192 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004193 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004194 }
4195 return true;
4196 }
4197}
4198
4199bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4200 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4201 // member can be formed.
4202 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4203}
4204
4205//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004206// Record Evaluation
4207//===----------------------------------------------------------------------===//
4208
4209namespace {
4210 class RecordExprEvaluator
4211 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4212 const LValue &This;
4213 APValue &Result;
4214 public:
4215
4216 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4217 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4218
Richard Smith2e312c82012-03-03 22:46:17 +00004219 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004220 Result = V;
4221 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004222 }
Richard Smithfddd3842011-12-30 21:15:51 +00004223 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004224
Richard Smithe97cbd72011-11-11 04:05:33 +00004225 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004226 bool VisitInitListExpr(const InitListExpr *E);
4227 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4228 };
4229}
4230
Richard Smithfddd3842011-12-30 21:15:51 +00004231/// Perform zero-initialization on an object of non-union class type.
4232/// C++11 [dcl.init]p5:
4233/// To zero-initialize an object or reference of type T means:
4234/// [...]
4235/// -- if T is a (possibly cv-qualified) non-union class type,
4236/// each non-static data member and each base-class subobject is
4237/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004238static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4239 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004240 const LValue &This, APValue &Result) {
4241 assert(!RD->isUnion() && "Expected non-union class type");
4242 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4243 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4244 std::distance(RD->field_begin(), RD->field_end()));
4245
John McCalld7bca762012-05-01 00:38:49 +00004246 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004247 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4248
4249 if (CD) {
4250 unsigned Index = 0;
4251 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004252 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004253 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4254 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004255 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4256 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004257 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004258 Result.getStructBase(Index)))
4259 return false;
4260 }
4261 }
4262
Richard Smitha8105bc2012-01-06 16:39:00 +00004263 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4264 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004265 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004266 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004267 continue;
4268
4269 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004270 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004271 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004272
David Blaikie2d7c57e2012-04-30 02:36:29 +00004273 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004274 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004275 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004276 return false;
4277 }
4278
4279 return true;
4280}
4281
4282bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4283 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004284 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004285 if (RD->isUnion()) {
4286 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4287 // object's first non-static named data member is zero-initialized
4288 RecordDecl::field_iterator I = RD->field_begin();
4289 if (I == RD->field_end()) {
4290 Result = APValue((const FieldDecl*)0);
4291 return true;
4292 }
4293
4294 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004295 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004296 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004297 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004298 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004299 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004300 }
4301
Richard Smith5d108602012-02-17 00:44:16 +00004302 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004303 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004304 return false;
4305 }
4306
Richard Smitha8105bc2012-01-06 16:39:00 +00004307 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004308}
4309
Richard Smithe97cbd72011-11-11 04:05:33 +00004310bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4311 switch (E->getCastKind()) {
4312 default:
4313 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4314
4315 case CK_ConstructorConversion:
4316 return Visit(E->getSubExpr());
4317
4318 case CK_DerivedToBase:
4319 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004320 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004321 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004322 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004323 if (!DerivedObject.isStruct())
4324 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004325
4326 // Derived-to-base rvalue conversion: just slice off the derived part.
4327 APValue *Value = &DerivedObject;
4328 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4329 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4330 PathE = E->path_end(); PathI != PathE; ++PathI) {
4331 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4332 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4333 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4334 RD = Base;
4335 }
4336 Result = *Value;
4337 return true;
4338 }
4339 }
4340}
4341
Richard Smithd62306a2011-11-10 06:34:14 +00004342bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004343 // Cannot constant-evaluate std::initializer_list inits.
4344 if (E->initializesStdInitializerList())
4345 return false;
4346
Richard Smithd62306a2011-11-10 06:34:14 +00004347 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004348 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004349 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4350
4351 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004352 const FieldDecl *Field = E->getInitializedFieldInUnion();
4353 Result = APValue(Field);
4354 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004355 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004356
4357 // If the initializer list for a union does not contain any elements, the
4358 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004359 // FIXME: The element should be initialized from an initializer list.
4360 // Is this difference ever observable for initializer lists which
4361 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004362 ImplicitValueInitExpr VIE(Field->getType());
4363 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4364
Richard Smithd62306a2011-11-10 06:34:14 +00004365 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004366 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4367 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004368
4369 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4370 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4371 isa<CXXDefaultInitExpr>(InitExpr));
4372
Richard Smithb228a862012-02-15 02:18:13 +00004373 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004374 }
4375
4376 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4377 "initializer list for class with base classes");
4378 Result = APValue(APValue::UninitStruct(), 0,
4379 std::distance(RD->field_begin(), RD->field_end()));
4380 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004381 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004382 for (RecordDecl::field_iterator Field = RD->field_begin(),
4383 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4384 // Anonymous bit-fields are not considered members of the class for
4385 // purposes of aggregate initialization.
4386 if (Field->isUnnamedBitfield())
4387 continue;
4388
4389 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004390
Richard Smith253c2a32012-01-27 01:14:48 +00004391 bool HaveInit = ElementNo < E->getNumInits();
4392
4393 // FIXME: Diagnostics here should point to the end of the initializer
4394 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004395 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004396 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004397 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004398
4399 // Perform an implicit value-initialization for members beyond the end of
4400 // the initializer list.
4401 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004402 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004403
Richard Smith852c9db2013-04-20 22:23:05 +00004404 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4405 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4406 isa<CXXDefaultInitExpr>(Init));
4407
4408 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4409 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004410 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004411 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004412 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004413 }
4414 }
4415
Richard Smith253c2a32012-01-27 01:14:48 +00004416 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004417}
4418
4419bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4420 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004421 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4422
Richard Smithfddd3842011-12-30 21:15:51 +00004423 bool ZeroInit = E->requiresZeroInitialization();
4424 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004425 // If we've already performed zero-initialization, we're already done.
4426 if (!Result.isUninit())
4427 return true;
4428
Richard Smithfddd3842011-12-30 21:15:51 +00004429 if (ZeroInit)
4430 return ZeroInitialization(E);
4431
Richard Smithcc36f692011-12-22 02:22:31 +00004432 const CXXRecordDecl *RD = FD->getParent();
4433 if (RD->isUnion())
4434 Result = APValue((FieldDecl*)0);
4435 else
4436 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4437 std::distance(RD->field_begin(), RD->field_end()));
4438 return true;
4439 }
4440
Richard Smithd62306a2011-11-10 06:34:14 +00004441 const FunctionDecl *Definition = 0;
4442 FD->getBody(Definition);
4443
Richard Smith357362d2011-12-13 06:39:58 +00004444 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4445 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004446
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004447 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004448 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004449 if (const MaterializeTemporaryExpr *ME
4450 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4451 return Visit(ME->GetTemporaryExpr());
4452
Richard Smithfddd3842011-12-30 21:15:51 +00004453 if (ZeroInit && !ZeroInitialization(E))
4454 return false;
4455
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004456 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004457 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004458 cast<CXXConstructorDecl>(Definition), Info,
4459 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004460}
4461
4462static bool EvaluateRecord(const Expr *E, const LValue &This,
4463 APValue &Result, EvalInfo &Info) {
4464 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004465 "can't evaluate expression as a record rvalue");
4466 return RecordExprEvaluator(Info, This, Result).Visit(E);
4467}
4468
4469//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004470// Temporary Evaluation
4471//
4472// Temporaries are represented in the AST as rvalues, but generally behave like
4473// lvalues. The full-object of which the temporary is a subobject is implicitly
4474// materialized so that a reference can bind to it.
4475//===----------------------------------------------------------------------===//
4476namespace {
4477class TemporaryExprEvaluator
4478 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4479public:
4480 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4481 LValueExprEvaluatorBaseTy(Info, Result) {}
4482
4483 /// Visit an expression which constructs the value of this temporary.
4484 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004485 Result.set(E, Info.CurrentCall->Index);
4486 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004487 }
4488
4489 bool VisitCastExpr(const CastExpr *E) {
4490 switch (E->getCastKind()) {
4491 default:
4492 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4493
4494 case CK_ConstructorConversion:
4495 return VisitConstructExpr(E->getSubExpr());
4496 }
4497 }
4498 bool VisitInitListExpr(const InitListExpr *E) {
4499 return VisitConstructExpr(E);
4500 }
4501 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4502 return VisitConstructExpr(E);
4503 }
4504 bool VisitCallExpr(const CallExpr *E) {
4505 return VisitConstructExpr(E);
4506 }
4507};
4508} // end anonymous namespace
4509
4510/// Evaluate an expression of record type as a temporary.
4511static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004512 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004513 return TemporaryExprEvaluator(Info, Result).Visit(E);
4514}
4515
4516//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004517// Vector Evaluation
4518//===----------------------------------------------------------------------===//
4519
4520namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004521 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004522 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4523 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004524 public:
Mike Stump11289f42009-09-09 15:08:12 +00004525
Richard Smith2d406342011-10-22 21:10:00 +00004526 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4527 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004528
Richard Smith2d406342011-10-22 21:10:00 +00004529 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4530 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4531 // FIXME: remove this APValue copy.
4532 Result = APValue(V.data(), V.size());
4533 return true;
4534 }
Richard Smith2e312c82012-03-03 22:46:17 +00004535 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004536 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004537 Result = V;
4538 return true;
4539 }
Richard Smithfddd3842011-12-30 21:15:51 +00004540 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004541
Richard Smith2d406342011-10-22 21:10:00 +00004542 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004543 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004544 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004545 bool VisitInitListExpr(const InitListExpr *E);
4546 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004547 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004548 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004549 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004550 };
4551} // end anonymous namespace
4552
4553static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004554 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004555 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004556}
4557
Richard Smith2d406342011-10-22 21:10:00 +00004558bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4559 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004560 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004561
Richard Smith161f09a2011-12-06 22:44:34 +00004562 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004563 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004564
Eli Friedmanc757de22011-03-25 00:43:55 +00004565 switch (E->getCastKind()) {
4566 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004567 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004568 if (SETy->isIntegerType()) {
4569 APSInt IntResult;
4570 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004571 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004572 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004573 } else if (SETy->isRealFloatingType()) {
4574 APFloat F(0.0);
4575 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004576 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004577 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004578 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004579 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004580 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004581
4582 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004583 SmallVector<APValue, 4> Elts(NElts, Val);
4584 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004585 }
Eli Friedman803acb32011-12-22 03:51:45 +00004586 case CK_BitCast: {
4587 // Evaluate the operand into an APInt we can extract from.
4588 llvm::APInt SValInt;
4589 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4590 return false;
4591 // Extract the elements
4592 QualType EltTy = VTy->getElementType();
4593 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4594 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4595 SmallVector<APValue, 4> Elts;
4596 if (EltTy->isRealFloatingType()) {
4597 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004598 unsigned FloatEltSize = EltSize;
4599 if (&Sem == &APFloat::x87DoubleExtended)
4600 FloatEltSize = 80;
4601 for (unsigned i = 0; i < NElts; i++) {
4602 llvm::APInt Elt;
4603 if (BigEndian)
4604 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4605 else
4606 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004607 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004608 }
4609 } else if (EltTy->isIntegerType()) {
4610 for (unsigned i = 0; i < NElts; i++) {
4611 llvm::APInt Elt;
4612 if (BigEndian)
4613 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4614 else
4615 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4616 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4617 }
4618 } else {
4619 return Error(E);
4620 }
4621 return Success(Elts, E);
4622 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004623 default:
Richard Smith11562c52011-10-28 17:51:58 +00004624 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004625 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004626}
4627
Richard Smith2d406342011-10-22 21:10:00 +00004628bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004629VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004630 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004631 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004632 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004633
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004634 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004635 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004636
Eli Friedmanb9c71292012-01-03 23:24:20 +00004637 // The number of initializers can be less than the number of
4638 // vector elements. For OpenCL, this can be due to nested vector
4639 // initialization. For GCC compatibility, missing trailing elements
4640 // should be initialized with zeroes.
4641 unsigned CountInits = 0, CountElts = 0;
4642 while (CountElts < NumElements) {
4643 // Handle nested vector initialization.
4644 if (CountInits < NumInits
4645 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4646 APValue v;
4647 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4648 return Error(E);
4649 unsigned vlen = v.getVectorLength();
4650 for (unsigned j = 0; j < vlen; j++)
4651 Elements.push_back(v.getVectorElt(j));
4652 CountElts += vlen;
4653 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004654 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004655 if (CountInits < NumInits) {
4656 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004657 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004658 } else // trailing integer zero.
4659 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4660 Elements.push_back(APValue(sInt));
4661 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004662 } else {
4663 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004664 if (CountInits < NumInits) {
4665 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004666 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004667 } else // trailing float zero.
4668 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4669 Elements.push_back(APValue(f));
4670 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004671 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004672 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004673 }
Richard Smith2d406342011-10-22 21:10:00 +00004674 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004675}
4676
Richard Smith2d406342011-10-22 21:10:00 +00004677bool
Richard Smithfddd3842011-12-30 21:15:51 +00004678VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004679 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004680 QualType EltTy = VT->getElementType();
4681 APValue ZeroElement;
4682 if (EltTy->isIntegerType())
4683 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4684 else
4685 ZeroElement =
4686 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4687
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004688 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004689 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004690}
4691
Richard Smith2d406342011-10-22 21:10:00 +00004692bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004693 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004694 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004695}
4696
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004697//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004698// Array Evaluation
4699//===----------------------------------------------------------------------===//
4700
4701namespace {
4702 class ArrayExprEvaluator
4703 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004704 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004705 APValue &Result;
4706 public:
4707
Richard Smithd62306a2011-11-10 06:34:14 +00004708 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4709 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004710
4711 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004712 assert((V.isArray() || V.isLValue()) &&
4713 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004714 Result = V;
4715 return true;
4716 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004717
Richard Smithfddd3842011-12-30 21:15:51 +00004718 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004719 const ConstantArrayType *CAT =
4720 Info.Ctx.getAsConstantArrayType(E->getType());
4721 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004722 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004723
4724 Result = APValue(APValue::UninitArray(), 0,
4725 CAT->getSize().getZExtValue());
4726 if (!Result.hasArrayFiller()) return true;
4727
Richard Smithfddd3842011-12-30 21:15:51 +00004728 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004729 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004730 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004731 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004732 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004733 }
4734
Richard Smithf3e9e432011-11-07 09:22:26 +00004735 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004736 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004737 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4738 const LValue &Subobject,
4739 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004740 };
4741} // end anonymous namespace
4742
Richard Smithd62306a2011-11-10 06:34:14 +00004743static bool EvaluateArray(const Expr *E, const LValue &This,
4744 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004745 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004746 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004747}
4748
4749bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4750 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4751 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004752 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004753
Richard Smithca2cfbf2011-12-22 01:07:19 +00004754 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4755 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004756 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004757 LValue LV;
4758 if (!EvaluateLValue(E->getInit(0), LV, Info))
4759 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004760 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004761 LV.moveInto(Val);
4762 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004763 }
4764
Richard Smith253c2a32012-01-27 01:14:48 +00004765 bool Success = true;
4766
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004767 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4768 "zero-initialized array shouldn't have any initialized elts");
4769 APValue Filler;
4770 if (Result.isArray() && Result.hasArrayFiller())
4771 Filler = Result.getArrayFiller();
4772
Richard Smith9543c5e2013-04-22 14:44:29 +00004773 unsigned NumEltsToInit = E->getNumInits();
4774 unsigned NumElts = CAT->getSize().getZExtValue();
4775 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4776
4777 // If the initializer might depend on the array index, run it for each
4778 // array element. For now, just whitelist non-class value-initialization.
4779 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4780 NumEltsToInit = NumElts;
4781
4782 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004783
4784 // If the array was previously zero-initialized, preserve the
4785 // zero-initialized values.
4786 if (!Filler.isUninit()) {
4787 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4788 Result.getArrayInitializedElt(I) = Filler;
4789 if (Result.hasArrayFiller())
4790 Result.getArrayFiller() = Filler;
4791 }
4792
Richard Smithd62306a2011-11-10 06:34:14 +00004793 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004794 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004795 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4796 const Expr *Init =
4797 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00004798 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00004799 Info, Subobject, Init) ||
4800 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00004801 CAT->getElementType(), 1)) {
4802 if (!Info.keepEvaluatingAfterFailure())
4803 return false;
4804 Success = false;
4805 }
Richard Smithd62306a2011-11-10 06:34:14 +00004806 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004807
Richard Smith9543c5e2013-04-22 14:44:29 +00004808 if (!Result.hasArrayFiller())
4809 return Success;
4810
4811 // If we get here, we have a trivial filler, which we can just evaluate
4812 // once and splat over the rest of the array elements.
4813 assert(FillerExpr && "no array filler for incomplete init list");
4814 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4815 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00004816}
4817
Richard Smith027bf112011-11-17 22:56:20 +00004818bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004819 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4820}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004821
Richard Smith9543c5e2013-04-22 14:44:29 +00004822bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4823 const LValue &Subobject,
4824 APValue *Value,
4825 QualType Type) {
4826 bool HadZeroInit = !Value->isUninit();
4827
4828 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4829 unsigned N = CAT->getSize().getZExtValue();
4830
4831 // Preserve the array filler if we had prior zero-initialization.
4832 APValue Filler =
4833 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4834 : APValue();
4835
4836 *Value = APValue(APValue::UninitArray(), N, N);
4837
4838 if (HadZeroInit)
4839 for (unsigned I = 0; I != N; ++I)
4840 Value->getArrayInitializedElt(I) = Filler;
4841
4842 // Initialize the elements.
4843 LValue ArrayElt = Subobject;
4844 ArrayElt.addArray(Info, E, CAT);
4845 for (unsigned I = 0; I != N; ++I)
4846 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4847 CAT->getElementType()) ||
4848 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4849 CAT->getElementType(), 1))
4850 return false;
4851
4852 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004853 }
Richard Smith027bf112011-11-17 22:56:20 +00004854
Richard Smith9543c5e2013-04-22 14:44:29 +00004855 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004856 return Error(E);
4857
Richard Smith027bf112011-11-17 22:56:20 +00004858 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004859
Richard Smithfddd3842011-12-30 21:15:51 +00004860 bool ZeroInit = E->requiresZeroInitialization();
4861 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004862 if (HadZeroInit)
4863 return true;
4864
Richard Smithfddd3842011-12-30 21:15:51 +00004865 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004866 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004867 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004868 }
4869
Richard Smithcc36f692011-12-22 02:22:31 +00004870 const CXXRecordDecl *RD = FD->getParent();
4871 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004872 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004873 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004874 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004875 APValue(APValue::UninitStruct(), RD->getNumBases(),
4876 std::distance(RD->field_begin(), RD->field_end()));
4877 return true;
4878 }
4879
Richard Smith027bf112011-11-17 22:56:20 +00004880 const FunctionDecl *Definition = 0;
4881 FD->getBody(Definition);
4882
Richard Smith357362d2011-12-13 06:39:58 +00004883 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4884 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004885
Richard Smith9eae7232012-01-12 18:54:33 +00004886 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004887 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004888 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004889 return false;
4890 }
4891
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004892 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004893 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004894 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004895 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004896}
4897
Richard Smithf3e9e432011-11-07 09:22:26 +00004898//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004899// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004900//
4901// As a GNU extension, we support casting pointers to sufficiently-wide integer
4902// types and back in constant folding. Integer values are thus represented
4903// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004904//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004905
4906namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004907class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004908 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004909 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004910public:
Richard Smith2e312c82012-03-03 22:46:17 +00004911 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004912 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004913
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004914 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004915 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004916 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004917 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004918 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004919 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004920 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004921 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004922 return true;
4923 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004924 bool Success(const llvm::APSInt &SI, const Expr *E) {
4925 return Success(SI, E, Result);
4926 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004927
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004928 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004929 assert(E->getType()->isIntegralOrEnumerationType() &&
4930 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004931 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004932 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004933 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004934 Result.getInt().setIsUnsigned(
4935 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004936 return true;
4937 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004938 bool Success(const llvm::APInt &I, const Expr *E) {
4939 return Success(I, E, Result);
4940 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004941
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004942 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004943 assert(E->getType()->isIntegralOrEnumerationType() &&
4944 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004945 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004946 return true;
4947 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004948 bool Success(uint64_t Value, const Expr *E) {
4949 return Success(Value, E, Result);
4950 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004951
Ken Dyckdbc01912011-03-11 02:13:43 +00004952 bool Success(CharUnits Size, const Expr *E) {
4953 return Success(Size.getQuantity(), E);
4954 }
4955
Richard Smith2e312c82012-03-03 22:46:17 +00004956 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004957 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00004958 Result = V;
4959 return true;
4960 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004961 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004962 }
Mike Stump11289f42009-09-09 15:08:12 +00004963
Richard Smithfddd3842011-12-30 21:15:51 +00004964 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00004965
Peter Collingbournee9200682011-05-13 03:29:01 +00004966 //===--------------------------------------------------------------------===//
4967 // Visitor Methods
4968 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004969
Chris Lattner7174bf32008-07-12 00:38:25 +00004970 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004971 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004972 }
4973 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004974 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004975 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004976
4977 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4978 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004979 if (CheckReferencedDecl(E, E->getDecl()))
4980 return true;
4981
4982 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004983 }
4984 bool VisitMemberExpr(const MemberExpr *E) {
4985 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004986 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004987 return true;
4988 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004989
4990 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004991 }
4992
Peter Collingbournee9200682011-05-13 03:29:01 +00004993 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004994 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004995 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004996 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004997
Peter Collingbournee9200682011-05-13 03:29:01 +00004998 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004999 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005000
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005001 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005002 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005003 }
Mike Stump11289f42009-09-09 15:08:12 +00005004
Ted Kremeneke65b0862012-03-06 20:05:56 +00005005 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5006 return Success(E->getValue(), E);
5007 }
5008
Richard Smith4ce706a2011-10-11 21:43:33 +00005009 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005010 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005011 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005012 }
5013
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005014 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005015 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005016 }
5017
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005018 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5019 return Success(E->getValue(), E);
5020 }
5021
Douglas Gregor29c42f22012-02-24 07:38:34 +00005022 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5023 return Success(E->getValue(), E);
5024 }
5025
John Wiegley6242b6a2011-04-28 00:16:57 +00005026 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5027 return Success(E->getValue(), E);
5028 }
5029
John Wiegleyf9f65842011-04-25 06:54:41 +00005030 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5031 return Success(E->getValue(), E);
5032 }
5033
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005034 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005035 bool VisitUnaryImag(const UnaryOperator *E);
5036
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005037 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005038 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005039
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005040private:
Ken Dyck160146e2010-01-27 17:10:57 +00005041 CharUnits GetAlignOfExpr(const Expr *E);
5042 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005043 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005044 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005045 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005046};
Chris Lattner05706e882008-07-11 18:11:29 +00005047} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005048
Richard Smith11562c52011-10-28 17:51:58 +00005049/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5050/// produce either the integer value or a pointer.
5051///
5052/// GCC has a heinous extension which folds casts between pointer types and
5053/// pointer-sized integral types. We support this by allowing the evaluation of
5054/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5055/// Some simple arithmetic on such values is supported (they are treated much
5056/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005057static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005058 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005059 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005060 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005061}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005062
Richard Smithf57d8cb2011-12-09 22:58:01 +00005063static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005064 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005065 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005066 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005067 if (!Val.isInt()) {
5068 // FIXME: It would be better to produce the diagnostic for casting
5069 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005070 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005071 return false;
5072 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005073 Result = Val.getInt();
5074 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005075}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005076
Richard Smithf57d8cb2011-12-09 22:58:01 +00005077/// Check whether the given declaration can be directly converted to an integral
5078/// rvalue. If not, no diagnostic is produced; there are other things we can
5079/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005080bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005081 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005082 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005083 // Check for signedness/width mismatches between E type and ECD value.
5084 bool SameSign = (ECD->getInitVal().isSigned()
5085 == E->getType()->isSignedIntegerOrEnumerationType());
5086 bool SameWidth = (ECD->getInitVal().getBitWidth()
5087 == Info.Ctx.getIntWidth(E->getType()));
5088 if (SameSign && SameWidth)
5089 return Success(ECD->getInitVal(), E);
5090 else {
5091 // Get rid of mismatch (otherwise Success assertions will fail)
5092 // by computing a new value matching the type of E.
5093 llvm::APSInt Val = ECD->getInitVal();
5094 if (!SameSign)
5095 Val.setIsSigned(!ECD->getInitVal().isSigned());
5096 if (!SameWidth)
5097 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5098 return Success(Val, E);
5099 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005100 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005101 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005102}
5103
Chris Lattner86ee2862008-10-06 06:40:35 +00005104/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5105/// as GCC.
5106static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5107 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005108 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005109 enum gcc_type_class {
5110 no_type_class = -1,
5111 void_type_class, integer_type_class, char_type_class,
5112 enumeral_type_class, boolean_type_class,
5113 pointer_type_class, reference_type_class, offset_type_class,
5114 real_type_class, complex_type_class,
5115 function_type_class, method_type_class,
5116 record_type_class, union_type_class,
5117 array_type_class, string_type_class,
5118 lang_type_class
5119 };
Mike Stump11289f42009-09-09 15:08:12 +00005120
5121 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005122 // ideal, however it is what gcc does.
5123 if (E->getNumArgs() == 0)
5124 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005125
Chris Lattner86ee2862008-10-06 06:40:35 +00005126 QualType ArgTy = E->getArg(0)->getType();
5127 if (ArgTy->isVoidType())
5128 return void_type_class;
5129 else if (ArgTy->isEnumeralType())
5130 return enumeral_type_class;
5131 else if (ArgTy->isBooleanType())
5132 return boolean_type_class;
5133 else if (ArgTy->isCharType())
5134 return string_type_class; // gcc doesn't appear to use char_type_class
5135 else if (ArgTy->isIntegerType())
5136 return integer_type_class;
5137 else if (ArgTy->isPointerType())
5138 return pointer_type_class;
5139 else if (ArgTy->isReferenceType())
5140 return reference_type_class;
5141 else if (ArgTy->isRealType())
5142 return real_type_class;
5143 else if (ArgTy->isComplexType())
5144 return complex_type_class;
5145 else if (ArgTy->isFunctionType())
5146 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005147 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005148 return record_type_class;
5149 else if (ArgTy->isUnionType())
5150 return union_type_class;
5151 else if (ArgTy->isArrayType())
5152 return array_type_class;
5153 else if (ArgTy->isUnionType())
5154 return union_type_class;
5155 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005156 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005157}
5158
Richard Smith5fab0c92011-12-28 19:48:30 +00005159/// EvaluateBuiltinConstantPForLValue - Determine the result of
5160/// __builtin_constant_p when applied to the given lvalue.
5161///
5162/// An lvalue is only "constant" if it is a pointer or reference to the first
5163/// character of a string literal.
5164template<typename LValue>
5165static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005166 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005167 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5168}
5169
5170/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5171/// GCC as we can manage.
5172static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5173 QualType ArgType = Arg->getType();
5174
5175 // __builtin_constant_p always has one operand. The rules which gcc follows
5176 // are not precisely documented, but are as follows:
5177 //
5178 // - If the operand is of integral, floating, complex or enumeration type,
5179 // and can be folded to a known value of that type, it returns 1.
5180 // - If the operand and can be folded to a pointer to the first character
5181 // of a string literal (or such a pointer cast to an integral type), it
5182 // returns 1.
5183 //
5184 // Otherwise, it returns 0.
5185 //
5186 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5187 // its support for this does not currently work.
5188 if (ArgType->isIntegralOrEnumerationType()) {
5189 Expr::EvalResult Result;
5190 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5191 return false;
5192
5193 APValue &V = Result.Val;
5194 if (V.getKind() == APValue::Int)
5195 return true;
5196
5197 return EvaluateBuiltinConstantPForLValue(V);
5198 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5199 return Arg->isEvaluatable(Ctx);
5200 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5201 LValue LV;
5202 Expr::EvalStatus Status;
5203 EvalInfo Info(Ctx, Status);
5204 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5205 : EvaluatePointer(Arg, LV, Info)) &&
5206 !Status.HasSideEffects)
5207 return EvaluateBuiltinConstantPForLValue(LV);
5208 }
5209
5210 // Anything else isn't considered to be sufficiently constant.
5211 return false;
5212}
5213
John McCall95007602010-05-10 23:27:23 +00005214/// Retrieves the "underlying object type" of the given expression,
5215/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005216QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5217 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5218 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005219 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005220 } else if (const Expr *E = B.get<const Expr*>()) {
5221 if (isa<CompoundLiteralExpr>(E))
5222 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005223 }
5224
5225 return QualType();
5226}
5227
Peter Collingbournee9200682011-05-13 03:29:01 +00005228bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005229 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005230
5231 {
5232 // The operand of __builtin_object_size is never evaluated for side-effects.
5233 // If there are any, but we can determine the pointed-to object anyway, then
5234 // ignore the side-effects.
5235 SpeculativeEvaluationRAII SpeculativeEval(Info);
5236 if (!EvaluatePointer(E->getArg(0), Base, Info))
5237 return false;
5238 }
John McCall95007602010-05-10 23:27:23 +00005239
5240 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005241 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005242
Richard Smithce40ad62011-11-12 22:28:03 +00005243 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005244 if (T.isNull() ||
5245 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005246 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005247 T->isVariablyModifiedType() ||
5248 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005249 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005250
5251 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5252 CharUnits Offset = Base.getLValueOffset();
5253
5254 if (!Offset.isNegative() && Offset <= Size)
5255 Size -= Offset;
5256 else
5257 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005258 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005259}
5260
Peter Collingbournee9200682011-05-13 03:29:01 +00005261bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005262 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005263 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005264 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005265
5266 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005267 if (TryEvaluateBuiltinObjectSize(E))
5268 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005269
Richard Smith0421ce72012-08-07 04:16:51 +00005270 // If evaluating the argument has side-effects, we can't determine the size
5271 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5272 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005273 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005274 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005275 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005276 return Success(0, E);
5277 }
Mike Stump876387b2009-10-27 22:09:17 +00005278
Richard Smith01ade172012-05-23 04:13:20 +00005279 // Expression had no side effects, but we couldn't statically determine the
5280 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005281 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005282 }
5283
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005284 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005285 case Builtin::BI__builtin_bswap32:
5286 case Builtin::BI__builtin_bswap64: {
5287 APSInt Val;
5288 if (!EvaluateInteger(E->getArg(0), Val, Info))
5289 return false;
5290
5291 return Success(Val.byteSwap(), E);
5292 }
5293
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005294 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005295 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005296
Richard Smith5fab0c92011-12-28 19:48:30 +00005297 case Builtin::BI__builtin_constant_p:
5298 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005299
Chris Lattnerd545ad12009-09-23 06:06:36 +00005300 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005301 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005302 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005303 return Success(Operand, E);
5304 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005305
5306 case Builtin::BI__builtin_expect:
5307 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005308
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005309 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005310 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005311 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005312 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005313 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5314 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005315 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005316 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005317 case Builtin::BI__builtin_strlen:
5318 // As an extension, we support strlen() and __builtin_strlen() as constant
5319 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005320 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005321 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5322 // The string literal may have embedded null characters. Find the first
5323 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005324 StringRef Str = S->getString();
5325 StringRef::size_type Pos = Str.find(0);
5326 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005327 Str = Str.substr(0, Pos);
5328
5329 return Success(Str.size(), E);
5330 }
5331
Richard Smithf57d8cb2011-12-09 22:58:01 +00005332 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005333
Richard Smith01ba47d2012-04-13 00:45:38 +00005334 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005335 case Builtin::BI__atomic_is_lock_free:
5336 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005337 APSInt SizeVal;
5338 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5339 return false;
5340
5341 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5342 // of two less than the maximum inline atomic width, we know it is
5343 // lock-free. If the size isn't a power of two, or greater than the
5344 // maximum alignment where we promote atomics, we know it is not lock-free
5345 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5346 // the answer can only be determined at runtime; for example, 16-byte
5347 // atomics have lock-free implementations on some, but not all,
5348 // x86-64 processors.
5349
5350 // Check power-of-two.
5351 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005352 if (Size.isPowerOfTwo()) {
5353 // Check against inlining width.
5354 unsigned InlineWidthBits =
5355 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5356 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5357 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5358 Size == CharUnits::One() ||
5359 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5360 Expr::NPC_NeverValueDependent))
5361 // OK, we will inline appropriately-aligned operations of this size,
5362 // and _Atomic(T) is appropriately-aligned.
5363 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005364
Richard Smith01ba47d2012-04-13 00:45:38 +00005365 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5366 castAs<PointerType>()->getPointeeType();
5367 if (!PointeeType->isIncompleteType() &&
5368 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5369 // OK, we will inline operations on this object.
5370 return Success(1, E);
5371 }
5372 }
5373 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005374
Richard Smith01ba47d2012-04-13 00:45:38 +00005375 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5376 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005377 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005378 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005379}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005380
Richard Smith8b3497e2011-10-31 01:37:14 +00005381static bool HasSameBase(const LValue &A, const LValue &B) {
5382 if (!A.getLValueBase())
5383 return !B.getLValueBase();
5384 if (!B.getLValueBase())
5385 return false;
5386
Richard Smithce40ad62011-11-12 22:28:03 +00005387 if (A.getLValueBase().getOpaqueValue() !=
5388 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005389 const Decl *ADecl = GetLValueBaseDecl(A);
5390 if (!ADecl)
5391 return false;
5392 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005393 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005394 return false;
5395 }
5396
5397 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005398 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005399}
5400
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005401namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005402
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005403/// \brief Data recursive integer evaluator of certain binary operators.
5404///
5405/// We use a data recursive algorithm for binary operators so that we are able
5406/// to handle extreme cases of chained binary operators without causing stack
5407/// overflow.
5408class DataRecursiveIntBinOpEvaluator {
5409 struct EvalResult {
5410 APValue Val;
5411 bool Failed;
5412
5413 EvalResult() : Failed(false) { }
5414
5415 void swap(EvalResult &RHS) {
5416 Val.swap(RHS.Val);
5417 Failed = RHS.Failed;
5418 RHS.Failed = false;
5419 }
5420 };
5421
5422 struct Job {
5423 const Expr *E;
5424 EvalResult LHSResult; // meaningful only for binary operator expression.
5425 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5426
5427 Job() : StoredInfo(0) { }
5428 void startSpeculativeEval(EvalInfo &Info) {
5429 OldEvalStatus = Info.EvalStatus;
5430 Info.EvalStatus.Diag = 0;
5431 StoredInfo = &Info;
5432 }
5433 ~Job() {
5434 if (StoredInfo) {
5435 StoredInfo->EvalStatus = OldEvalStatus;
5436 }
5437 }
5438 private:
5439 EvalInfo *StoredInfo; // non-null if status changed.
5440 Expr::EvalStatus OldEvalStatus;
5441 };
5442
5443 SmallVector<Job, 16> Queue;
5444
5445 IntExprEvaluator &IntEval;
5446 EvalInfo &Info;
5447 APValue &FinalResult;
5448
5449public:
5450 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5451 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5452
5453 /// \brief True if \param E is a binary operator that we are going to handle
5454 /// data recursively.
5455 /// We handle binary operators that are comma, logical, or that have operands
5456 /// with integral or enumeration type.
5457 static bool shouldEnqueue(const BinaryOperator *E) {
5458 return E->getOpcode() == BO_Comma ||
5459 E->isLogicalOp() ||
5460 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5461 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005462 }
5463
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005464 bool Traverse(const BinaryOperator *E) {
5465 enqueue(E);
5466 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005467 while (!Queue.empty())
5468 process(PrevResult);
5469
5470 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005471
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005472 FinalResult.swap(PrevResult.Val);
5473 return true;
5474 }
5475
5476private:
5477 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5478 return IntEval.Success(Value, E, Result);
5479 }
5480 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5481 return IntEval.Success(Value, E, Result);
5482 }
5483 bool Error(const Expr *E) {
5484 return IntEval.Error(E);
5485 }
5486 bool Error(const Expr *E, diag::kind D) {
5487 return IntEval.Error(E, D);
5488 }
5489
5490 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5491 return Info.CCEDiag(E, D);
5492 }
5493
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005494 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5495 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005496 bool &SuppressRHSDiags);
5497
5498 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5499 const BinaryOperator *E, APValue &Result);
5500
5501 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5502 Result.Failed = !Evaluate(Result.Val, Info, E);
5503 if (Result.Failed)
5504 Result.Val = APValue();
5505 }
5506
Richard Trieuba4d0872012-03-21 23:30:30 +00005507 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005508
5509 void enqueue(const Expr *E) {
5510 E = E->IgnoreParens();
5511 Queue.resize(Queue.size()+1);
5512 Queue.back().E = E;
5513 Queue.back().Kind = Job::AnyExprKind;
5514 }
5515};
5516
5517}
5518
5519bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005520 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005521 bool &SuppressRHSDiags) {
5522 if (E->getOpcode() == BO_Comma) {
5523 // Ignore LHS but note if we could not evaluate it.
5524 if (LHSResult.Failed)
5525 Info.EvalStatus.HasSideEffects = true;
5526 return true;
5527 }
5528
5529 if (E->isLogicalOp()) {
5530 bool lhsResult;
5531 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005532 // We were able to evaluate the LHS, see if we can get away with not
5533 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005534 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005535 Success(lhsResult, E, LHSResult.Val);
5536 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005537 }
5538 } else {
5539 // Since we weren't able to evaluate the left hand side, it
5540 // must have had side effects.
5541 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005542
5543 // We can't evaluate the LHS; however, sometimes the result
5544 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5545 // Don't ignore RHS and suppress diagnostics from this arm.
5546 SuppressRHSDiags = true;
5547 }
5548
5549 return true;
5550 }
5551
5552 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5553 E->getRHS()->getType()->isIntegralOrEnumerationType());
5554
5555 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005556 return false; // Ignore RHS;
5557
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005558 return true;
5559}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005560
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005561bool DataRecursiveIntBinOpEvaluator::
5562 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5563 const BinaryOperator *E, APValue &Result) {
5564 if (E->getOpcode() == BO_Comma) {
5565 if (RHSResult.Failed)
5566 return false;
5567 Result = RHSResult.Val;
5568 return true;
5569 }
5570
5571 if (E->isLogicalOp()) {
5572 bool lhsResult, rhsResult;
5573 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5574 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5575
5576 if (LHSIsOK) {
5577 if (RHSIsOK) {
5578 if (E->getOpcode() == BO_LOr)
5579 return Success(lhsResult || rhsResult, E, Result);
5580 else
5581 return Success(lhsResult && rhsResult, E, Result);
5582 }
5583 } else {
5584 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005585 // We can't evaluate the LHS; however, sometimes the result
5586 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5587 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005588 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005589 }
5590 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005591
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005592 return false;
5593 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005594
5595 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5596 E->getRHS()->getType()->isIntegralOrEnumerationType());
5597
5598 if (LHSResult.Failed || RHSResult.Failed)
5599 return false;
5600
5601 const APValue &LHSVal = LHSResult.Val;
5602 const APValue &RHSVal = RHSResult.Val;
5603
5604 // Handle cases like (unsigned long)&a + 4.
5605 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5606 Result = LHSVal;
5607 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5608 RHSVal.getInt().getZExtValue());
5609 if (E->getOpcode() == BO_Add)
5610 Result.getLValueOffset() += AdditionalOffset;
5611 else
5612 Result.getLValueOffset() -= AdditionalOffset;
5613 return true;
5614 }
5615
5616 // Handle cases like 4 + (unsigned long)&a
5617 if (E->getOpcode() == BO_Add &&
5618 RHSVal.isLValue() && LHSVal.isInt()) {
5619 Result = RHSVal;
5620 Result.getLValueOffset() += CharUnits::fromQuantity(
5621 LHSVal.getInt().getZExtValue());
5622 return true;
5623 }
5624
5625 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5626 // Handle (intptr_t)&&A - (intptr_t)&&B.
5627 if (!LHSVal.getLValueOffset().isZero() ||
5628 !RHSVal.getLValueOffset().isZero())
5629 return false;
5630 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5631 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5632 if (!LHSExpr || !RHSExpr)
5633 return false;
5634 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5635 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5636 if (!LHSAddrExpr || !RHSAddrExpr)
5637 return false;
5638 // Make sure both labels come from the same function.
5639 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5640 RHSAddrExpr->getLabel()->getDeclContext())
5641 return false;
5642 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5643 return true;
5644 }
Richard Smith43e77732013-05-07 04:50:00 +00005645
5646 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005647 if (!LHSVal.isInt() || !RHSVal.isInt())
5648 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00005649
5650 // Set up the width and signedness manually, in case it can't be deduced
5651 // from the operation we're performing.
5652 // FIXME: Don't do this in the cases where we can deduce it.
5653 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
5654 E->getType()->isUnsignedIntegerOrEnumerationType());
5655 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
5656 RHSVal.getInt(), Value))
5657 return false;
5658 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005659}
5660
Richard Trieuba4d0872012-03-21 23:30:30 +00005661void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005662 Job &job = Queue.back();
5663
5664 switch (job.Kind) {
5665 case Job::AnyExprKind: {
5666 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5667 if (shouldEnqueue(Bop)) {
5668 job.Kind = Job::BinOpKind;
5669 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005670 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005671 }
5672 }
5673
5674 EvaluateExpr(job.E, Result);
5675 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005676 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005677 }
5678
5679 case Job::BinOpKind: {
5680 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005681 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005682 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005683 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005684 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005685 }
5686 if (SuppressRHSDiags)
5687 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005688 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005689 job.Kind = Job::BinOpVisitedLHSKind;
5690 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005691 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005692 }
5693
5694 case Job::BinOpVisitedLHSKind: {
5695 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5696 EvalResult RHS;
5697 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005698 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005699 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005700 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005701 }
5702 }
5703
5704 llvm_unreachable("Invalid Job::Kind!");
5705}
5706
5707bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5708 if (E->isAssignmentOp())
5709 return Error(E);
5710
5711 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5712 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005713
Anders Carlssonacc79812008-11-16 07:17:21 +00005714 QualType LHSTy = E->getLHS()->getType();
5715 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005716
5717 if (LHSTy->isAnyComplexType()) {
5718 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005719 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005720
Richard Smith253c2a32012-01-27 01:14:48 +00005721 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5722 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005723 return false;
5724
Richard Smith253c2a32012-01-27 01:14:48 +00005725 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005726 return false;
5727
5728 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005729 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005730 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005731 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005732 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5733
John McCalle3027922010-08-25 11:45:40 +00005734 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005735 return Success((CR_r == APFloat::cmpEqual &&
5736 CR_i == APFloat::cmpEqual), E);
5737 else {
John McCalle3027922010-08-25 11:45:40 +00005738 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005739 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005740 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005741 CR_r == APFloat::cmpLessThan ||
5742 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005743 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005744 CR_i == APFloat::cmpLessThan ||
5745 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005746 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005747 } else {
John McCalle3027922010-08-25 11:45:40 +00005748 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005749 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5750 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5751 else {
John McCalle3027922010-08-25 11:45:40 +00005752 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005753 "Invalid compex comparison.");
5754 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5755 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5756 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005757 }
5758 }
Mike Stump11289f42009-09-09 15:08:12 +00005759
Anders Carlssonacc79812008-11-16 07:17:21 +00005760 if (LHSTy->isRealFloatingType() &&
5761 RHSTy->isRealFloatingType()) {
5762 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005763
Richard Smith253c2a32012-01-27 01:14:48 +00005764 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5765 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005766 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005767
Richard Smith253c2a32012-01-27 01:14:48 +00005768 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005769 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005770
Anders Carlssonacc79812008-11-16 07:17:21 +00005771 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005772
Anders Carlssonacc79812008-11-16 07:17:21 +00005773 switch (E->getOpcode()) {
5774 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005775 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005776 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005777 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005778 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005779 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005780 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005781 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005782 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005783 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005784 E);
John McCalle3027922010-08-25 11:45:40 +00005785 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005786 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005787 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005788 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005789 || CR == APFloat::cmpLessThan
5790 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005791 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005792 }
Mike Stump11289f42009-09-09 15:08:12 +00005793
Eli Friedmana38da572009-04-28 19:17:36 +00005794 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005795 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005796 LValue LHSValue, RHSValue;
5797
5798 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5799 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005800 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005801
Richard Smith253c2a32012-01-27 01:14:48 +00005802 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005803 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005804
Richard Smith8b3497e2011-10-31 01:37:14 +00005805 // Reject differing bases from the normal codepath; we special-case
5806 // comparisons to null.
5807 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005808 if (E->getOpcode() == BO_Sub) {
5809 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005810 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5811 return false;
5812 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005813 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005814 if (!LHSExpr || !RHSExpr)
5815 return false;
5816 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5817 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5818 if (!LHSAddrExpr || !RHSAddrExpr)
5819 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005820 // Make sure both labels come from the same function.
5821 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5822 RHSAddrExpr->getLabel()->getDeclContext())
5823 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005824 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005825 return true;
5826 }
Richard Smith83c68212011-10-31 05:11:32 +00005827 // Inequalities and subtractions between unrelated pointers have
5828 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005829 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005830 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005831 // A constant address may compare equal to the address of a symbol.
5832 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005833 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005834 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5835 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005836 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005837 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005838 // distinct addresses. In clang, the result of such a comparison is
5839 // unspecified, so it is not a constant expression. However, we do know
5840 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005841 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5842 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005843 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005844 // We can't tell whether weak symbols will end up pointing to the same
5845 // object.
5846 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005847 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005848 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005849 // (Note that clang defaults to -fmerge-all-constants, which can
5850 // lead to inconsistent results for comparisons involving the address
5851 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005852 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005853 }
Eli Friedman64004332009-03-23 04:38:34 +00005854
Richard Smith1b470412012-02-01 08:10:20 +00005855 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5856 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5857
Richard Smith84f6dcf2012-02-02 01:16:57 +00005858 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5859 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5860
John McCalle3027922010-08-25 11:45:40 +00005861 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005862 // C++11 [expr.add]p6:
5863 // Unless both pointers point to elements of the same array object, or
5864 // one past the last element of the array object, the behavior is
5865 // undefined.
5866 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5867 !AreElementsOfSameArray(getType(LHSValue.Base),
5868 LHSDesignator, RHSDesignator))
5869 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5870
Chris Lattner882bdf22010-04-20 17:13:14 +00005871 QualType Type = E->getLHS()->getType();
5872 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005873
Richard Smithd62306a2011-11-10 06:34:14 +00005874 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005875 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005876 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005877
Richard Smith1b470412012-02-01 08:10:20 +00005878 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5879 // and produce incorrect results when it overflows. Such behavior
5880 // appears to be non-conforming, but is common, so perhaps we should
5881 // assume the standard intended for such cases to be undefined behavior
5882 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005883
Richard Smith1b470412012-02-01 08:10:20 +00005884 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5885 // overflow in the final conversion to ptrdiff_t.
5886 APSInt LHS(
5887 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5888 APSInt RHS(
5889 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5890 APSInt ElemSize(
5891 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5892 APSInt TrueResult = (LHS - RHS) / ElemSize;
5893 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5894
5895 if (Result.extend(65) != TrueResult)
5896 HandleOverflow(Info, E, TrueResult, E->getType());
5897 return Success(Result, E);
5898 }
Richard Smithde21b242012-01-31 06:41:30 +00005899
5900 // C++11 [expr.rel]p3:
5901 // Pointers to void (after pointer conversions) can be compared, with a
5902 // result defined as follows: If both pointers represent the same
5903 // address or are both the null pointer value, the result is true if the
5904 // operator is <= or >= and false otherwise; otherwise the result is
5905 // unspecified.
5906 // We interpret this as applying to pointers to *cv* void.
5907 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005908 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005909 CCEDiag(E, diag::note_constexpr_void_comparison);
5910
Richard Smith84f6dcf2012-02-02 01:16:57 +00005911 // C++11 [expr.rel]p2:
5912 // - If two pointers point to non-static data members of the same object,
5913 // or to subobjects or array elements fo such members, recursively, the
5914 // pointer to the later declared member compares greater provided the
5915 // two members have the same access control and provided their class is
5916 // not a union.
5917 // [...]
5918 // - Otherwise pointer comparisons are unspecified.
5919 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5920 E->isRelationalOp()) {
5921 bool WasArrayIndex;
5922 unsigned Mismatch =
5923 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5924 RHSDesignator, WasArrayIndex);
5925 // At the point where the designators diverge, the comparison has a
5926 // specified value if:
5927 // - we are comparing array indices
5928 // - we are comparing fields of a union, or fields with the same access
5929 // Otherwise, the result is unspecified and thus the comparison is not a
5930 // constant expression.
5931 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5932 Mismatch < RHSDesignator.Entries.size()) {
5933 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5934 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5935 if (!LF && !RF)
5936 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5937 else if (!LF)
5938 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5939 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5940 << RF->getParent() << RF;
5941 else if (!RF)
5942 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5943 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5944 << LF->getParent() << LF;
5945 else if (!LF->getParent()->isUnion() &&
5946 LF->getAccess() != RF->getAccess())
5947 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5948 << LF << LF->getAccess() << RF << RF->getAccess()
5949 << LF->getParent();
5950 }
5951 }
5952
Eli Friedman6c31cb42012-04-16 04:30:08 +00005953 // The comparison here must be unsigned, and performed with the same
5954 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005955 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5956 uint64_t CompareLHS = LHSOffset.getQuantity();
5957 uint64_t CompareRHS = RHSOffset.getQuantity();
5958 assert(PtrSize <= 64 && "Unexpected pointer width");
5959 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5960 CompareLHS &= Mask;
5961 CompareRHS &= Mask;
5962
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005963 // If there is a base and this is a relational operator, we can only
5964 // compare pointers within the object in question; otherwise, the result
5965 // depends on where the object is located in memory.
5966 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5967 QualType BaseTy = getType(LHSValue.Base);
5968 if (BaseTy->isIncompleteType())
5969 return Error(E);
5970 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5971 uint64_t OffsetLimit = Size.getQuantity();
5972 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5973 return Error(E);
5974 }
5975
Richard Smith8b3497e2011-10-31 01:37:14 +00005976 switch (E->getOpcode()) {
5977 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005978 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5979 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5980 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5981 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5982 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5983 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005984 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005985 }
5986 }
Richard Smith7bb00672012-02-01 01:42:44 +00005987
5988 if (LHSTy->isMemberPointerType()) {
5989 assert(E->isEqualityOp() && "unexpected member pointer operation");
5990 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5991
5992 MemberPtr LHSValue, RHSValue;
5993
5994 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5995 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5996 return false;
5997
5998 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5999 return false;
6000
6001 // C++11 [expr.eq]p2:
6002 // If both operands are null, they compare equal. Otherwise if only one is
6003 // null, they compare unequal.
6004 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6005 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6006 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6007 }
6008
6009 // Otherwise if either is a pointer to a virtual member function, the
6010 // result is unspecified.
6011 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6012 if (MD->isVirtual())
6013 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6014 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6015 if (MD->isVirtual())
6016 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6017
6018 // Otherwise they compare equal if and only if they would refer to the
6019 // same member of the same most derived object or the same subobject if
6020 // they were dereferenced with a hypothetical object of the associated
6021 // class type.
6022 bool Equal = LHSValue == RHSValue;
6023 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6024 }
6025
Richard Smithab44d9b2012-02-14 22:35:28 +00006026 if (LHSTy->isNullPtrType()) {
6027 assert(E->isComparisonOp() && "unexpected nullptr operation");
6028 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6029 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6030 // are compared, the result is true of the operator is <=, >= or ==, and
6031 // false otherwise.
6032 BinaryOperator::Opcode Opcode = E->getOpcode();
6033 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6034 }
6035
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006036 assert((!LHSTy->isIntegralOrEnumerationType() ||
6037 !RHSTy->isIntegralOrEnumerationType()) &&
6038 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6039 // We can't continue from here for non-integral types.
6040 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006041}
6042
Ken Dyck160146e2010-01-27 17:10:57 +00006043CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006044 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6045 // result shall be the alignment of the referenced type."
6046 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6047 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006048
6049 // __alignof is defined to return the preferred alignment.
6050 return Info.Ctx.toCharUnitsFromBits(
6051 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006052}
6053
Ken Dyck160146e2010-01-27 17:10:57 +00006054CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006055 E = E->IgnoreParens();
6056
John McCall768439e2013-05-06 07:40:34 +00006057 // The kinds of expressions that we have special-case logic here for
6058 // should be kept up to date with the special checks for those
6059 // expressions in Sema.
6060
Chris Lattner68061312009-01-24 21:53:27 +00006061 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006062 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006063 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006064 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6065 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006066
Chris Lattner68061312009-01-24 21:53:27 +00006067 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006068 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6069 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006070
Chris Lattner24aeeab2009-01-24 21:09:06 +00006071 return GetAlignOfType(E->getType());
6072}
6073
6074
Peter Collingbournee190dee2011-03-11 19:24:49 +00006075/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6076/// a result as the expression's type.
6077bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6078 const UnaryExprOrTypeTraitExpr *E) {
6079 switch(E->getKind()) {
6080 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006081 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006082 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006083 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006084 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006085 }
Eli Friedman64004332009-03-23 04:38:34 +00006086
Peter Collingbournee190dee2011-03-11 19:24:49 +00006087 case UETT_VecStep: {
6088 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006089
Peter Collingbournee190dee2011-03-11 19:24:49 +00006090 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006091 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006092
Peter Collingbournee190dee2011-03-11 19:24:49 +00006093 // The vec_step built-in functions that take a 3-component
6094 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6095 if (n == 3)
6096 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006097
Peter Collingbournee190dee2011-03-11 19:24:49 +00006098 return Success(n, E);
6099 } else
6100 return Success(1, E);
6101 }
6102
6103 case UETT_SizeOf: {
6104 QualType SrcTy = E->getTypeOfArgument();
6105 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6106 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006107 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6108 SrcTy = Ref->getPointeeType();
6109
Richard Smithd62306a2011-11-10 06:34:14 +00006110 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006111 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006112 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006113 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006114 }
6115 }
6116
6117 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006118}
6119
Peter Collingbournee9200682011-05-13 03:29:01 +00006120bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006121 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006122 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006123 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006124 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006125 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006126 for (unsigned i = 0; i != n; ++i) {
6127 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6128 switch (ON.getKind()) {
6129 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006130 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006131 APSInt IdxResult;
6132 if (!EvaluateInteger(Idx, IdxResult, Info))
6133 return false;
6134 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6135 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006136 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006137 CurrentType = AT->getElementType();
6138 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6139 Result += IdxResult.getSExtValue() * ElementSize;
6140 break;
6141 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006142
Douglas Gregor882211c2010-04-28 22:16:22 +00006143 case OffsetOfExpr::OffsetOfNode::Field: {
6144 FieldDecl *MemberDecl = ON.getField();
6145 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006146 if (!RT)
6147 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006148 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006149 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006150 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006151 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006152 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006153 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006154 CurrentType = MemberDecl->getType().getNonReferenceType();
6155 break;
6156 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006157
Douglas Gregor882211c2010-04-28 22:16:22 +00006158 case OffsetOfExpr::OffsetOfNode::Identifier:
6159 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006160
Douglas Gregord1702062010-04-29 00:18:15 +00006161 case OffsetOfExpr::OffsetOfNode::Base: {
6162 CXXBaseSpecifier *BaseSpec = ON.getBase();
6163 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006164 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006165
6166 // Find the layout of the class whose base we are looking into.
6167 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006168 if (!RT)
6169 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006170 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006171 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006172 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6173
6174 // Find the base class itself.
6175 CurrentType = BaseSpec->getType();
6176 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6177 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006178 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006179
6180 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006181 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006182 break;
6183 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006184 }
6185 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006186 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006187}
6188
Chris Lattnere13042c2008-07-11 19:10:17 +00006189bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006190 switch (E->getOpcode()) {
6191 default:
6192 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6193 // See C99 6.6p3.
6194 return Error(E);
6195 case UO_Extension:
6196 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6197 // If so, we could clear the diagnostic ID.
6198 return Visit(E->getSubExpr());
6199 case UO_Plus:
6200 // The result is just the value.
6201 return Visit(E->getSubExpr());
6202 case UO_Minus: {
6203 if (!Visit(E->getSubExpr()))
6204 return false;
6205 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006206 const APSInt &Value = Result.getInt();
6207 if (Value.isSigned() && Value.isMinSignedValue())
6208 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6209 E->getType());
6210 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006211 }
6212 case UO_Not: {
6213 if (!Visit(E->getSubExpr()))
6214 return false;
6215 if (!Result.isInt()) return Error(E);
6216 return Success(~Result.getInt(), E);
6217 }
6218 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006219 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006220 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006221 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006222 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006223 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006224 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006225}
Mike Stump11289f42009-09-09 15:08:12 +00006226
Chris Lattner477c4be2008-07-12 01:15:53 +00006227/// HandleCast - This is used to evaluate implicit or explicit casts where the
6228/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006229bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6230 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006231 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006232 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006233
Eli Friedmanc757de22011-03-25 00:43:55 +00006234 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006235 case CK_BaseToDerived:
6236 case CK_DerivedToBase:
6237 case CK_UncheckedDerivedToBase:
6238 case CK_Dynamic:
6239 case CK_ToUnion:
6240 case CK_ArrayToPointerDecay:
6241 case CK_FunctionToPointerDecay:
6242 case CK_NullToPointer:
6243 case CK_NullToMemberPointer:
6244 case CK_BaseToDerivedMemberPointer:
6245 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006246 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006247 case CK_ConstructorConversion:
6248 case CK_IntegralToPointer:
6249 case CK_ToVoid:
6250 case CK_VectorSplat:
6251 case CK_IntegralToFloating:
6252 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006253 case CK_CPointerToObjCPointerCast:
6254 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006255 case CK_AnyPointerToBlockPointerCast:
6256 case CK_ObjCObjectLValueCast:
6257 case CK_FloatingRealToComplex:
6258 case CK_FloatingComplexToReal:
6259 case CK_FloatingComplexCast:
6260 case CK_FloatingComplexToIntegralComplex:
6261 case CK_IntegralRealToComplex:
6262 case CK_IntegralComplexCast:
6263 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006264 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006265 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006266 llvm_unreachable("invalid cast kind for integral value");
6267
Eli Friedman9faf2f92011-03-25 19:07:11 +00006268 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006269 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006270 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006271 case CK_ARCProduceObject:
6272 case CK_ARCConsumeObject:
6273 case CK_ARCReclaimReturnedObject:
6274 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006275 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006276 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006277
Richard Smith4ef685b2012-01-17 21:17:26 +00006278 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006279 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006280 case CK_AtomicToNonAtomic:
6281 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006282 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006283 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006284
6285 case CK_MemberPointerToBoolean:
6286 case CK_PointerToBoolean:
6287 case CK_IntegralToBoolean:
6288 case CK_FloatingToBoolean:
6289 case CK_FloatingComplexToBoolean:
6290 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006291 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006292 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006293 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006294 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006295 }
6296
Eli Friedmanc757de22011-03-25 00:43:55 +00006297 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006298 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006299 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006300
Eli Friedman742421e2009-02-20 01:15:07 +00006301 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006302 // Allow casts of address-of-label differences if they are no-ops
6303 // or narrowing. (The narrowing case isn't actually guaranteed to
6304 // be constant-evaluatable except in some narrow cases which are hard
6305 // to detect here. We let it through on the assumption the user knows
6306 // what they are doing.)
6307 if (Result.isAddrLabelDiff())
6308 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006309 // Only allow casts of lvalues if they are lossless.
6310 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6311 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006312
Richard Smith911e1422012-01-30 22:27:01 +00006313 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6314 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006315 }
Mike Stump11289f42009-09-09 15:08:12 +00006316
Eli Friedmanc757de22011-03-25 00:43:55 +00006317 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006318 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6319
John McCall45d55e42010-05-07 21:00:08 +00006320 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006321 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006322 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006323
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006324 if (LV.getLValueBase()) {
6325 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006326 // FIXME: Allow a larger integer size than the pointer size, and allow
6327 // narrowing back down to pointer width in subsequent integral casts.
6328 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006329 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006330 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006331
Richard Smithcf74da72011-11-16 07:18:12 +00006332 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006333 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006334 return true;
6335 }
6336
Ken Dyck02990832010-01-15 12:37:54 +00006337 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6338 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006339 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006340 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006341
Eli Friedmanc757de22011-03-25 00:43:55 +00006342 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006343 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006344 if (!EvaluateComplex(SubExpr, C, Info))
6345 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006346 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006347 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006348
Eli Friedmanc757de22011-03-25 00:43:55 +00006349 case CK_FloatingToIntegral: {
6350 APFloat F(0.0);
6351 if (!EvaluateFloat(SubExpr, F, Info))
6352 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006353
Richard Smith357362d2011-12-13 06:39:58 +00006354 APSInt Value;
6355 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6356 return false;
6357 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006358 }
6359 }
Mike Stump11289f42009-09-09 15:08:12 +00006360
Eli Friedmanc757de22011-03-25 00:43:55 +00006361 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006362}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006363
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006364bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6365 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006366 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006367 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6368 return false;
6369 if (!LV.isComplexInt())
6370 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006371 return Success(LV.getComplexIntReal(), E);
6372 }
6373
6374 return Visit(E->getSubExpr());
6375}
6376
Eli Friedman4e7a2412009-02-27 04:45:43 +00006377bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006378 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006379 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006380 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6381 return false;
6382 if (!LV.isComplexInt())
6383 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006384 return Success(LV.getComplexIntImag(), E);
6385 }
6386
Richard Smith4a678122011-10-24 18:44:57 +00006387 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006388 return Success(0, E);
6389}
6390
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006391bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6392 return Success(E->getPackLength(), E);
6393}
6394
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006395bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6396 return Success(E->getValue(), E);
6397}
6398
Chris Lattner05706e882008-07-11 18:11:29 +00006399//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006400// Float Evaluation
6401//===----------------------------------------------------------------------===//
6402
6403namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006404class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006405 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006406 APFloat &Result;
6407public:
6408 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006409 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006410
Richard Smith2e312c82012-03-03 22:46:17 +00006411 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006412 Result = V.getFloat();
6413 return true;
6414 }
Eli Friedman24c01542008-08-22 00:06:13 +00006415
Richard Smithfddd3842011-12-30 21:15:51 +00006416 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006417 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6418 return true;
6419 }
6420
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006421 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006422
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006423 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006424 bool VisitBinaryOperator(const BinaryOperator *E);
6425 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006426 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006427
John McCallb1fb0d32010-05-07 22:08:54 +00006428 bool VisitUnaryReal(const UnaryOperator *E);
6429 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006430
Richard Smithfddd3842011-12-30 21:15:51 +00006431 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006432};
6433} // end anonymous namespace
6434
6435static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006436 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006437 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006438}
6439
Jay Foad39c79802011-01-12 09:06:06 +00006440static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006441 QualType ResultTy,
6442 const Expr *Arg,
6443 bool SNaN,
6444 llvm::APFloat &Result) {
6445 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6446 if (!S) return false;
6447
6448 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6449
6450 llvm::APInt fill;
6451
6452 // Treat empty strings as if they were zero.
6453 if (S->getString().empty())
6454 fill = llvm::APInt(32, 0);
6455 else if (S->getString().getAsInteger(0, fill))
6456 return false;
6457
6458 if (SNaN)
6459 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6460 else
6461 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6462 return true;
6463}
6464
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006465bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006466 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006467 default:
6468 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6469
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006470 case Builtin::BI__builtin_huge_val:
6471 case Builtin::BI__builtin_huge_valf:
6472 case Builtin::BI__builtin_huge_vall:
6473 case Builtin::BI__builtin_inf:
6474 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006475 case Builtin::BI__builtin_infl: {
6476 const llvm::fltSemantics &Sem =
6477 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006478 Result = llvm::APFloat::getInf(Sem);
6479 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006480 }
Mike Stump11289f42009-09-09 15:08:12 +00006481
John McCall16291492010-02-28 13:00:19 +00006482 case Builtin::BI__builtin_nans:
6483 case Builtin::BI__builtin_nansf:
6484 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006485 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6486 true, Result))
6487 return Error(E);
6488 return true;
John McCall16291492010-02-28 13:00:19 +00006489
Chris Lattner0b7282e2008-10-06 06:31:58 +00006490 case Builtin::BI__builtin_nan:
6491 case Builtin::BI__builtin_nanf:
6492 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006493 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006494 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006495 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6496 false, Result))
6497 return Error(E);
6498 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006499
6500 case Builtin::BI__builtin_fabs:
6501 case Builtin::BI__builtin_fabsf:
6502 case Builtin::BI__builtin_fabsl:
6503 if (!EvaluateFloat(E->getArg(0), Result, Info))
6504 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006505
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006506 if (Result.isNegative())
6507 Result.changeSign();
6508 return true;
6509
Mike Stump11289f42009-09-09 15:08:12 +00006510 case Builtin::BI__builtin_copysign:
6511 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006512 case Builtin::BI__builtin_copysignl: {
6513 APFloat RHS(0.);
6514 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6515 !EvaluateFloat(E->getArg(1), RHS, Info))
6516 return false;
6517 Result.copySign(RHS);
6518 return true;
6519 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006520 }
6521}
6522
John McCallb1fb0d32010-05-07 22:08:54 +00006523bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006524 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6525 ComplexValue CV;
6526 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6527 return false;
6528 Result = CV.FloatReal;
6529 return true;
6530 }
6531
6532 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006533}
6534
6535bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006536 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6537 ComplexValue CV;
6538 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6539 return false;
6540 Result = CV.FloatImag;
6541 return true;
6542 }
6543
Richard Smith4a678122011-10-24 18:44:57 +00006544 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006545 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6546 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006547 return true;
6548}
6549
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006550bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006551 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006552 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006553 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006554 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006555 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006556 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6557 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006558 Result.changeSign();
6559 return true;
6560 }
6561}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006562
Eli Friedman24c01542008-08-22 00:06:13 +00006563bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006564 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6565 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006566
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006567 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006568 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6569 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006570 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006571 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00006572 return false;
6573
6574 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006575 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006576 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00006577 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006578 break;
John McCalle3027922010-08-25 11:45:40 +00006579 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00006580 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006581 break;
John McCalle3027922010-08-25 11:45:40 +00006582 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00006583 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006584 break;
John McCalle3027922010-08-25 11:45:40 +00006585 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00006586 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006587 break;
Eli Friedman24c01542008-08-22 00:06:13 +00006588 }
Richard Smithc8042322012-02-01 05:53:12 +00006589
6590 if (Result.isInfinity() || Result.isNaN())
6591 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
6592 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00006593}
6594
6595bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6596 Result = E->getValue();
6597 return true;
6598}
6599
Peter Collingbournee9200682011-05-13 03:29:01 +00006600bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6601 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006602
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006603 switch (E->getCastKind()) {
6604 default:
Richard Smith11562c52011-10-28 17:51:58 +00006605 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006606
6607 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006608 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006609 return EvaluateInteger(SubExpr, IntResult, Info) &&
6610 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6611 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006612 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006613
6614 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006615 if (!Visit(SubExpr))
6616 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006617 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6618 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006619 }
John McCalld7646252010-11-14 08:17:51 +00006620
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006621 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006622 ComplexValue V;
6623 if (!EvaluateComplex(SubExpr, V, Info))
6624 return false;
6625 Result = V.getComplexFloatReal();
6626 return true;
6627 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006628 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006629}
6630
Eli Friedman24c01542008-08-22 00:06:13 +00006631//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006632// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006633//===----------------------------------------------------------------------===//
6634
6635namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006636class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006637 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006638 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006639
Anders Carlsson537969c2008-11-16 20:27:53 +00006640public:
John McCall93d91dc2010-05-07 17:22:02 +00006641 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006642 : ExprEvaluatorBaseTy(info), Result(Result) {}
6643
Richard Smith2e312c82012-03-03 22:46:17 +00006644 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006645 Result.setFrom(V);
6646 return true;
6647 }
Mike Stump11289f42009-09-09 15:08:12 +00006648
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006649 bool ZeroInitialization(const Expr *E);
6650
Anders Carlsson537969c2008-11-16 20:27:53 +00006651 //===--------------------------------------------------------------------===//
6652 // Visitor Methods
6653 //===--------------------------------------------------------------------===//
6654
Peter Collingbournee9200682011-05-13 03:29:01 +00006655 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006656 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006657 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006658 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006659 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006660};
6661} // end anonymous namespace
6662
John McCall93d91dc2010-05-07 17:22:02 +00006663static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6664 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006665 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006666 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006667}
6668
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006669bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006670 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006671 if (ElemTy->isRealFloatingType()) {
6672 Result.makeComplexFloat();
6673 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6674 Result.FloatReal = Zero;
6675 Result.FloatImag = Zero;
6676 } else {
6677 Result.makeComplexInt();
6678 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6679 Result.IntReal = Zero;
6680 Result.IntImag = Zero;
6681 }
6682 return true;
6683}
6684
Peter Collingbournee9200682011-05-13 03:29:01 +00006685bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6686 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006687
6688 if (SubExpr->getType()->isRealFloatingType()) {
6689 Result.makeComplexFloat();
6690 APFloat &Imag = Result.FloatImag;
6691 if (!EvaluateFloat(SubExpr, Imag, Info))
6692 return false;
6693
6694 Result.FloatReal = APFloat(Imag.getSemantics());
6695 return true;
6696 } else {
6697 assert(SubExpr->getType()->isIntegerType() &&
6698 "Unexpected imaginary literal.");
6699
6700 Result.makeComplexInt();
6701 APSInt &Imag = Result.IntImag;
6702 if (!EvaluateInteger(SubExpr, Imag, Info))
6703 return false;
6704
6705 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6706 return true;
6707 }
6708}
6709
Peter Collingbournee9200682011-05-13 03:29:01 +00006710bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006711
John McCallfcef3cf2010-12-14 17:51:41 +00006712 switch (E->getCastKind()) {
6713 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006714 case CK_BaseToDerived:
6715 case CK_DerivedToBase:
6716 case CK_UncheckedDerivedToBase:
6717 case CK_Dynamic:
6718 case CK_ToUnion:
6719 case CK_ArrayToPointerDecay:
6720 case CK_FunctionToPointerDecay:
6721 case CK_NullToPointer:
6722 case CK_NullToMemberPointer:
6723 case CK_BaseToDerivedMemberPointer:
6724 case CK_DerivedToBaseMemberPointer:
6725 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006726 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006727 case CK_ConstructorConversion:
6728 case CK_IntegralToPointer:
6729 case CK_PointerToIntegral:
6730 case CK_PointerToBoolean:
6731 case CK_ToVoid:
6732 case CK_VectorSplat:
6733 case CK_IntegralCast:
6734 case CK_IntegralToBoolean:
6735 case CK_IntegralToFloating:
6736 case CK_FloatingToIntegral:
6737 case CK_FloatingToBoolean:
6738 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006739 case CK_CPointerToObjCPointerCast:
6740 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006741 case CK_AnyPointerToBlockPointerCast:
6742 case CK_ObjCObjectLValueCast:
6743 case CK_FloatingComplexToReal:
6744 case CK_FloatingComplexToBoolean:
6745 case CK_IntegralComplexToReal:
6746 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006747 case CK_ARCProduceObject:
6748 case CK_ARCConsumeObject:
6749 case CK_ARCReclaimReturnedObject:
6750 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006751 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006752 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006753 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006754 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006755
John McCallfcef3cf2010-12-14 17:51:41 +00006756 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006757 case CK_AtomicToNonAtomic:
6758 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006759 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006760 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006761
6762 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006763 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006764 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006765 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006766
6767 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006768 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006769 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006770 return false;
6771
John McCallfcef3cf2010-12-14 17:51:41 +00006772 Result.makeComplexFloat();
6773 Result.FloatImag = APFloat(Real.getSemantics());
6774 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006775 }
6776
John McCallfcef3cf2010-12-14 17:51:41 +00006777 case CK_FloatingComplexCast: {
6778 if (!Visit(E->getSubExpr()))
6779 return false;
6780
6781 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6782 QualType From
6783 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6784
Richard Smith357362d2011-12-13 06:39:58 +00006785 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6786 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006787 }
6788
6789 case CK_FloatingComplexToIntegralComplex: {
6790 if (!Visit(E->getSubExpr()))
6791 return false;
6792
6793 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6794 QualType From
6795 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6796 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006797 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6798 To, Result.IntReal) &&
6799 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6800 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006801 }
6802
6803 case CK_IntegralRealToComplex: {
6804 APSInt &Real = Result.IntReal;
6805 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6806 return false;
6807
6808 Result.makeComplexInt();
6809 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6810 return true;
6811 }
6812
6813 case CK_IntegralComplexCast: {
6814 if (!Visit(E->getSubExpr()))
6815 return false;
6816
6817 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6818 QualType From
6819 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6820
Richard Smith911e1422012-01-30 22:27:01 +00006821 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6822 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006823 return true;
6824 }
6825
6826 case CK_IntegralComplexToFloatingComplex: {
6827 if (!Visit(E->getSubExpr()))
6828 return false;
6829
Ted Kremenek28831752012-08-23 20:46:57 +00006830 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006831 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006832 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006833 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006834 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6835 To, Result.FloatReal) &&
6836 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6837 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006838 }
6839 }
6840
6841 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006842}
6843
John McCall93d91dc2010-05-07 17:22:02 +00006844bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006845 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006846 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6847
Richard Smith253c2a32012-01-27 01:14:48 +00006848 bool LHSOK = Visit(E->getLHS());
6849 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006850 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006851
John McCall93d91dc2010-05-07 17:22:02 +00006852 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006853 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006854 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006855
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006856 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6857 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006858 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006859 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006860 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006861 if (Result.isComplexFloat()) {
6862 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6863 APFloat::rmNearestTiesToEven);
6864 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6865 APFloat::rmNearestTiesToEven);
6866 } else {
6867 Result.getComplexIntReal() += RHS.getComplexIntReal();
6868 Result.getComplexIntImag() += RHS.getComplexIntImag();
6869 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006870 break;
John McCalle3027922010-08-25 11:45:40 +00006871 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006872 if (Result.isComplexFloat()) {
6873 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6874 APFloat::rmNearestTiesToEven);
6875 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6876 APFloat::rmNearestTiesToEven);
6877 } else {
6878 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6879 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6880 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006881 break;
John McCalle3027922010-08-25 11:45:40 +00006882 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006883 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006884 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006885 APFloat &LHS_r = LHS.getComplexFloatReal();
6886 APFloat &LHS_i = LHS.getComplexFloatImag();
6887 APFloat &RHS_r = RHS.getComplexFloatReal();
6888 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006889
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006890 APFloat Tmp = LHS_r;
6891 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6892 Result.getComplexFloatReal() = Tmp;
6893 Tmp = LHS_i;
6894 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6895 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6896
6897 Tmp = LHS_r;
6898 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6899 Result.getComplexFloatImag() = Tmp;
6900 Tmp = LHS_i;
6901 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6902 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6903 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006904 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006905 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006906 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6907 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006908 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006909 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6910 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6911 }
6912 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006913 case BO_Div:
6914 if (Result.isComplexFloat()) {
6915 ComplexValue LHS = Result;
6916 APFloat &LHS_r = LHS.getComplexFloatReal();
6917 APFloat &LHS_i = LHS.getComplexFloatImag();
6918 APFloat &RHS_r = RHS.getComplexFloatReal();
6919 APFloat &RHS_i = RHS.getComplexFloatImag();
6920 APFloat &Res_r = Result.getComplexFloatReal();
6921 APFloat &Res_i = Result.getComplexFloatImag();
6922
6923 APFloat Den = RHS_r;
6924 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6925 APFloat Tmp = RHS_i;
6926 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6927 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6928
6929 Res_r = LHS_r;
6930 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6931 Tmp = LHS_i;
6932 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6933 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6934 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6935
6936 Res_i = LHS_i;
6937 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6938 Tmp = LHS_r;
6939 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6940 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6941 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6942 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006943 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6944 return Error(E, diag::note_expr_divide_by_zero);
6945
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006946 ComplexValue LHS = Result;
6947 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6948 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6949 Result.getComplexIntReal() =
6950 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6951 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6952 Result.getComplexIntImag() =
6953 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6954 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6955 }
6956 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006957 }
6958
John McCall93d91dc2010-05-07 17:22:02 +00006959 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006960}
6961
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006962bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6963 // Get the operand value into 'Result'.
6964 if (!Visit(E->getSubExpr()))
6965 return false;
6966
6967 switch (E->getOpcode()) {
6968 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006969 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006970 case UO_Extension:
6971 return true;
6972 case UO_Plus:
6973 // The result is always just the subexpr.
6974 return true;
6975 case UO_Minus:
6976 if (Result.isComplexFloat()) {
6977 Result.getComplexFloatReal().changeSign();
6978 Result.getComplexFloatImag().changeSign();
6979 }
6980 else {
6981 Result.getComplexIntReal() = -Result.getComplexIntReal();
6982 Result.getComplexIntImag() = -Result.getComplexIntImag();
6983 }
6984 return true;
6985 case UO_Not:
6986 if (Result.isComplexFloat())
6987 Result.getComplexFloatImag().changeSign();
6988 else
6989 Result.getComplexIntImag() = -Result.getComplexIntImag();
6990 return true;
6991 }
6992}
6993
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006994bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6995 if (E->getNumInits() == 2) {
6996 if (E->getType()->isComplexType()) {
6997 Result.makeComplexFloat();
6998 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6999 return false;
7000 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7001 return false;
7002 } else {
7003 Result.makeComplexInt();
7004 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7005 return false;
7006 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7007 return false;
7008 }
7009 return true;
7010 }
7011 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7012}
7013
Anders Carlsson537969c2008-11-16 20:27:53 +00007014//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007015// Void expression evaluation, primarily for a cast to void on the LHS of a
7016// comma operator
7017//===----------------------------------------------------------------------===//
7018
7019namespace {
7020class VoidExprEvaluator
7021 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7022public:
7023 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7024
Richard Smith2e312c82012-03-03 22:46:17 +00007025 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007026
7027 bool VisitCastExpr(const CastExpr *E) {
7028 switch (E->getCastKind()) {
7029 default:
7030 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7031 case CK_ToVoid:
7032 VisitIgnoredValue(E->getSubExpr());
7033 return true;
7034 }
7035 }
7036};
7037} // end anonymous namespace
7038
7039static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7040 assert(E->isRValue() && E->getType()->isVoidType());
7041 return VoidExprEvaluator(Info).Visit(E);
7042}
7043
7044//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007045// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007046//===----------------------------------------------------------------------===//
7047
Richard Smith2e312c82012-03-03 22:46:17 +00007048static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007049 // In C, function designators are not lvalues, but we evaluate them as if they
7050 // are.
7051 if (E->isGLValue() || E->getType()->isFunctionType()) {
7052 LValue LV;
7053 if (!EvaluateLValue(E, LV, Info))
7054 return false;
7055 LV.moveInto(Result);
7056 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007057 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007058 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007059 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007060 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007061 return false;
John McCall45d55e42010-05-07 21:00:08 +00007062 } else if (E->getType()->hasPointerRepresentation()) {
7063 LValue LV;
7064 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007065 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007066 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00007067 } else if (E->getType()->isRealFloatingType()) {
7068 llvm::APFloat F(0.0);
7069 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007070 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007071 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00007072 } else if (E->getType()->isAnyComplexType()) {
7073 ComplexValue C;
7074 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007075 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007076 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00007077 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007078 MemberPtr P;
7079 if (!EvaluateMemberPointer(E, P, Info))
7080 return false;
7081 P.moveInto(Result);
7082 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00007083 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007084 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007085 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007086 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007087 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007088 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00007089 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007090 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007091 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007092 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7093 return false;
7094 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00007095 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007096 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007097 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007098 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007099 if (!EvaluateVoid(E, Info))
7100 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007101 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007102 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007103 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007104 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007105 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007106 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007107 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007108
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007109 return true;
7110}
7111
Richard Smithb228a862012-02-15 02:18:13 +00007112/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7113/// cases, the in-place evaluation is essential, since later initializers for
7114/// an object can indirectly refer to subobjects which were initialized earlier.
7115static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
7116 const Expr *E, CheckConstantExpressionKind CCEK,
7117 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00007118 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00007119 return false;
7120
7121 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007122 // Evaluate arrays and record types in-place, so that later initializers can
7123 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007124 if (E->getType()->isArrayType())
7125 return EvaluateArray(E, This, Result, Info);
7126 else if (E->getType()->isRecordType())
7127 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007128 }
7129
7130 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007131 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007132}
7133
Richard Smithf57d8cb2011-12-09 22:58:01 +00007134/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7135/// lvalue-to-rvalue cast if it is an lvalue.
7136static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007137 if (!CheckLiteralType(Info, E))
7138 return false;
7139
Richard Smith2e312c82012-03-03 22:46:17 +00007140 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007141 return false;
7142
7143 if (E->isGLValue()) {
7144 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007145 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007146 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007147 return false;
7148 }
7149
Richard Smith2e312c82012-03-03 22:46:17 +00007150 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007151 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007152}
Richard Smith11562c52011-10-28 17:51:58 +00007153
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007154static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7155 const ASTContext &Ctx, bool &IsConst) {
7156 // Fast-path evaluations of integer literals, since we sometimes see files
7157 // containing vast quantities of these.
7158 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7159 Result.Val = APValue(APSInt(L->getValue(),
7160 L->getType()->isUnsignedIntegerType()));
7161 IsConst = true;
7162 return true;
7163 }
7164
7165 // FIXME: Evaluating values of large array and record types can cause
7166 // performance problems. Only do so in C++11 for now.
7167 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7168 Exp->getType()->isRecordType()) &&
7169 !Ctx.getLangOpts().CPlusPlus11) {
7170 IsConst = false;
7171 return true;
7172 }
7173 return false;
7174}
7175
7176
Richard Smith7b553f12011-10-29 00:50:52 +00007177/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007178/// any crazy technique (that has nothing to do with language standards) that
7179/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007180/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7181/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007182bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007183 bool IsConst;
7184 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7185 return IsConst;
7186
Richard Smithf57d8cb2011-12-09 22:58:01 +00007187 EvalInfo Info(Ctx, Result);
7188 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007189}
7190
Jay Foad39c79802011-01-12 09:06:06 +00007191bool Expr::EvaluateAsBooleanCondition(bool &Result,
7192 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007193 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007194 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007195 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007196}
7197
Richard Smith5fab0c92011-12-28 19:48:30 +00007198bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7199 SideEffectsKind AllowSideEffects) const {
7200 if (!getType()->isIntegralOrEnumerationType())
7201 return false;
7202
Richard Smith11562c52011-10-28 17:51:58 +00007203 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007204 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7205 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007206 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007207
Richard Smith11562c52011-10-28 17:51:58 +00007208 Result = ExprResult.Val.getInt();
7209 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007210}
7211
Jay Foad39c79802011-01-12 09:06:06 +00007212bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007213 EvalInfo Info(Ctx, Result);
7214
John McCall45d55e42010-05-07 21:00:08 +00007215 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007216 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7217 !CheckLValueConstantExpression(Info, getExprLoc(),
7218 Ctx.getLValueReferenceType(getType()), LV))
7219 return false;
7220
Richard Smith2e312c82012-03-03 22:46:17 +00007221 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007222 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007223}
7224
Richard Smithd0b4dd62011-12-19 06:19:21 +00007225bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7226 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007227 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007228 // FIXME: Evaluating initializers for large array and record types can cause
7229 // performance problems. Only do so in C++11 for now.
7230 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007231 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007232 return false;
7233
Richard Smithd0b4dd62011-12-19 06:19:21 +00007234 Expr::EvalStatus EStatus;
7235 EStatus.Diag = &Notes;
7236
7237 EvalInfo InitInfo(Ctx, EStatus);
7238 InitInfo.setEvaluatingDecl(VD, Value);
7239
7240 LValue LVal;
7241 LVal.set(VD);
7242
Richard Smithfddd3842011-12-30 21:15:51 +00007243 // C++11 [basic.start.init]p2:
7244 // Variables with static storage duration or thread storage duration shall be
7245 // zero-initialized before any other initialization takes place.
7246 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007247 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007248 !VD->getType()->isReferenceType()) {
7249 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007250 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
7251 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007252 return false;
7253 }
7254
Richard Smithb228a862012-02-15 02:18:13 +00007255 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
7256 /*AllowNonLiteralTypes=*/true) ||
7257 EStatus.HasSideEffects)
7258 return false;
7259
7260 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7261 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007262}
7263
Richard Smith7b553f12011-10-29 00:50:52 +00007264/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7265/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007266bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007267 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007268 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007269}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007270
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007271APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007272 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007273 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007274 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007275 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007276 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007277 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007278 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007279
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007280 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007281}
John McCall864e3962010-05-07 05:32:02 +00007282
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007283void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7284 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7285 bool IsConst;
7286 EvalResult EvalResult;
7287 EvalResult.Diag = Diags;
7288 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7289 EvalInfo Info(Ctx, EvalResult, true);
7290 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7291 }
7292}
7293
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007294 bool Expr::EvalResult::isGlobalLValue() const {
7295 assert(Val.isLValue());
7296 return IsGlobalLValue(Val.getLValueBase());
7297 }
7298
7299
John McCall864e3962010-05-07 05:32:02 +00007300/// isIntegerConstantExpr - this recursive routine will test if an expression is
7301/// an integer constant expression.
7302
7303/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7304/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007305
7306// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007307// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7308// and a (possibly null) SourceLocation indicating the location of the problem.
7309//
John McCall864e3962010-05-07 05:32:02 +00007310// Note that to reduce code duplication, this helper does no evaluation
7311// itself; the caller checks whether the expression is evaluatable, and
7312// in the rare cases where CheckICE actually cares about the evaluated
7313// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007314
Dan Gohman28ade552010-07-26 21:25:24 +00007315namespace {
7316
Richard Smith9e575da2012-12-28 13:25:52 +00007317enum ICEKind {
7318 /// This expression is an ICE.
7319 IK_ICE,
7320 /// This expression is not an ICE, but if it isn't evaluated, it's
7321 /// a legal subexpression for an ICE. This return value is used to handle
7322 /// the comma operator in C99 mode, and non-constant subexpressions.
7323 IK_ICEIfUnevaluated,
7324 /// This expression is not an ICE, and is not a legal subexpression for one.
7325 IK_NotICE
7326};
7327
John McCall864e3962010-05-07 05:32:02 +00007328struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007329 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007330 SourceLocation Loc;
7331
Richard Smith9e575da2012-12-28 13:25:52 +00007332 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007333};
7334
Dan Gohman28ade552010-07-26 21:25:24 +00007335}
7336
Richard Smith9e575da2012-12-28 13:25:52 +00007337static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7338
7339static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007340
7341static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7342 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007343 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007344 !EVResult.Val.isInt())
7345 return ICEDiag(IK_NotICE, E->getLocStart());
7346
John McCall864e3962010-05-07 05:32:02 +00007347 return NoDiag();
7348}
7349
7350static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7351 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007352 if (!E->getType()->isIntegralOrEnumerationType())
7353 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007354
7355 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007356#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007357#define STMT(Node, Base) case Expr::Node##Class:
7358#define EXPR(Node, Base)
7359#include "clang/AST/StmtNodes.inc"
7360 case Expr::PredefinedExprClass:
7361 case Expr::FloatingLiteralClass:
7362 case Expr::ImaginaryLiteralClass:
7363 case Expr::StringLiteralClass:
7364 case Expr::ArraySubscriptExprClass:
7365 case Expr::MemberExprClass:
7366 case Expr::CompoundAssignOperatorClass:
7367 case Expr::CompoundLiteralExprClass:
7368 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007369 case Expr::DesignatedInitExprClass:
7370 case Expr::ImplicitValueInitExprClass:
7371 case Expr::ParenListExprClass:
7372 case Expr::VAArgExprClass:
7373 case Expr::AddrLabelExprClass:
7374 case Expr::StmtExprClass:
7375 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007376 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007377 case Expr::CXXDynamicCastExprClass:
7378 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007379 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007380 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007381 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007382 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007383 case Expr::CXXThisExprClass:
7384 case Expr::CXXThrowExprClass:
7385 case Expr::CXXNewExprClass:
7386 case Expr::CXXDeleteExprClass:
7387 case Expr::CXXPseudoDestructorExprClass:
7388 case Expr::UnresolvedLookupExprClass:
7389 case Expr::DependentScopeDeclRefExprClass:
7390 case Expr::CXXConstructExprClass:
7391 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007392 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007393 case Expr::CXXTemporaryObjectExprClass:
7394 case Expr::CXXUnresolvedConstructExprClass:
7395 case Expr::CXXDependentScopeMemberExprClass:
7396 case Expr::UnresolvedMemberExprClass:
7397 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007398 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007399 case Expr::ObjCArrayLiteralClass:
7400 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007401 case Expr::ObjCEncodeExprClass:
7402 case Expr::ObjCMessageExprClass:
7403 case Expr::ObjCSelectorExprClass:
7404 case Expr::ObjCProtocolExprClass:
7405 case Expr::ObjCIvarRefExprClass:
7406 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007407 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007408 case Expr::ObjCIsaExprClass:
7409 case Expr::ShuffleVectorExprClass:
7410 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007411 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007412 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007413 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007414 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007415 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007416 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007417 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007418 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007419 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007420 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007421 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007422 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007423 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007424
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007425 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007426 case Expr::GNUNullExprClass:
7427 // GCC considers the GNU __null value to be an integral constant expression.
7428 return NoDiag();
7429
John McCall7c454bb2011-07-15 05:09:51 +00007430 case Expr::SubstNonTypeTemplateParmExprClass:
7431 return
7432 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7433
John McCall864e3962010-05-07 05:32:02 +00007434 case Expr::ParenExprClass:
7435 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007436 case Expr::GenericSelectionExprClass:
7437 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007438 case Expr::IntegerLiteralClass:
7439 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007440 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007441 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007442 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007443 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007444 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007445 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007446 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007447 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007448 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007449 return NoDiag();
7450 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007451 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007452 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7453 // constant expressions, but they can never be ICEs because an ICE cannot
7454 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007455 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007456 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007457 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007458 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007459 }
Richard Smith6365c912012-02-24 22:12:32 +00007460 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007461 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7462 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007463 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007464 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007465 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007466 // Parameter variables are never constants. Without this check,
7467 // getAnyInitializer() can find a default argument, which leads
7468 // to chaos.
7469 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007470 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007471
7472 // C++ 7.1.5.1p2
7473 // A variable of non-volatile const-qualified integral or enumeration
7474 // type initialized by an ICE can be used in ICEs.
7475 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007476 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007477 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007478
Richard Smithd0b4dd62011-12-19 06:19:21 +00007479 const VarDecl *VD;
7480 // Look for a declaration of this variable that has an initializer, and
7481 // check whether it is an ICE.
7482 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7483 return NoDiag();
7484 else
Richard Smith9e575da2012-12-28 13:25:52 +00007485 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007486 }
7487 }
Richard Smith9e575da2012-12-28 13:25:52 +00007488 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007489 }
John McCall864e3962010-05-07 05:32:02 +00007490 case Expr::UnaryOperatorClass: {
7491 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7492 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007493 case UO_PostInc:
7494 case UO_PostDec:
7495 case UO_PreInc:
7496 case UO_PreDec:
7497 case UO_AddrOf:
7498 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007499 // C99 6.6/3 allows increment and decrement within unevaluated
7500 // subexpressions of constant expressions, but they can never be ICEs
7501 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007502 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007503 case UO_Extension:
7504 case UO_LNot:
7505 case UO_Plus:
7506 case UO_Minus:
7507 case UO_Not:
7508 case UO_Real:
7509 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007510 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007511 }
Richard Smith9e575da2012-12-28 13:25:52 +00007512
John McCall864e3962010-05-07 05:32:02 +00007513 // OffsetOf falls through here.
7514 }
7515 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007516 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7517 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7518 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7519 // compliance: we should warn earlier for offsetof expressions with
7520 // array subscripts that aren't ICEs, and if the array subscripts
7521 // are ICEs, the value of the offsetof must be an integer constant.
7522 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007523 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007524 case Expr::UnaryExprOrTypeTraitExprClass: {
7525 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7526 if ((Exp->getKind() == UETT_SizeOf) &&
7527 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007528 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007529 return NoDiag();
7530 }
7531 case Expr::BinaryOperatorClass: {
7532 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7533 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007534 case BO_PtrMemD:
7535 case BO_PtrMemI:
7536 case BO_Assign:
7537 case BO_MulAssign:
7538 case BO_DivAssign:
7539 case BO_RemAssign:
7540 case BO_AddAssign:
7541 case BO_SubAssign:
7542 case BO_ShlAssign:
7543 case BO_ShrAssign:
7544 case BO_AndAssign:
7545 case BO_XorAssign:
7546 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007547 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7548 // constant expressions, but they can never be ICEs because an ICE cannot
7549 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007550 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007551
John McCalle3027922010-08-25 11:45:40 +00007552 case BO_Mul:
7553 case BO_Div:
7554 case BO_Rem:
7555 case BO_Add:
7556 case BO_Sub:
7557 case BO_Shl:
7558 case BO_Shr:
7559 case BO_LT:
7560 case BO_GT:
7561 case BO_LE:
7562 case BO_GE:
7563 case BO_EQ:
7564 case BO_NE:
7565 case BO_And:
7566 case BO_Xor:
7567 case BO_Or:
7568 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007569 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7570 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007571 if (Exp->getOpcode() == BO_Div ||
7572 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007573 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007574 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007575 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007576 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007577 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007578 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007579 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007580 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007581 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007582 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007583 }
7584 }
7585 }
John McCalle3027922010-08-25 11:45:40 +00007586 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007587 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007588 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7589 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007590 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7591 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007592 } else {
7593 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007594 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007595 }
7596 }
Richard Smith9e575da2012-12-28 13:25:52 +00007597 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007598 }
John McCalle3027922010-08-25 11:45:40 +00007599 case BO_LAnd:
7600 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007601 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7602 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007603 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007604 // Rare case where the RHS has a comma "side-effect"; we need
7605 // to actually check the condition to see whether the side
7606 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007607 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007608 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007609 return RHSResult;
7610 return NoDiag();
7611 }
7612
Richard Smith9e575da2012-12-28 13:25:52 +00007613 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007614 }
7615 }
7616 }
7617 case Expr::ImplicitCastExprClass:
7618 case Expr::CStyleCastExprClass:
7619 case Expr::CXXFunctionalCastExprClass:
7620 case Expr::CXXStaticCastExprClass:
7621 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007622 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007623 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007624 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007625 if (isa<ExplicitCastExpr>(E)) {
7626 if (const FloatingLiteral *FL
7627 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7628 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7629 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7630 APSInt IgnoredVal(DestWidth, !DestSigned);
7631 bool Ignored;
7632 // If the value does not fit in the destination type, the behavior is
7633 // undefined, so we are not required to treat it as a constant
7634 // expression.
7635 if (FL->getValue().convertToInteger(IgnoredVal,
7636 llvm::APFloat::rmTowardZero,
7637 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007638 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007639 return NoDiag();
7640 }
7641 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007642 switch (cast<CastExpr>(E)->getCastKind()) {
7643 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007644 case CK_AtomicToNonAtomic:
7645 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007646 case CK_NoOp:
7647 case CK_IntegralToBoolean:
7648 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007649 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007650 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007651 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007652 }
John McCall864e3962010-05-07 05:32:02 +00007653 }
John McCallc07a0c72011-02-17 10:25:35 +00007654 case Expr::BinaryConditionalOperatorClass: {
7655 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7656 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007657 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007658 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007659 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7660 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7661 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007662 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007663 return FalseResult;
7664 }
John McCall864e3962010-05-07 05:32:02 +00007665 case Expr::ConditionalOperatorClass: {
7666 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7667 // If the condition (ignoring parens) is a __builtin_constant_p call,
7668 // then only the true side is actually considered in an integer constant
7669 // expression, and it is fully evaluated. This is an important GNU
7670 // extension. See GCC PR38377 for discussion.
7671 if (const CallExpr *CallCE
7672 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007673 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7674 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007675 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007676 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007677 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007678
Richard Smithf57d8cb2011-12-09 22:58:01 +00007679 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7680 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007681
Richard Smith9e575da2012-12-28 13:25:52 +00007682 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007683 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007684 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007685 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007686 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007687 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007688 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007689 return NoDiag();
7690 // Rare case where the diagnostics depend on which side is evaluated
7691 // Note that if we get here, CondResult is 0, and at least one of
7692 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007693 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007694 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007695 return TrueResult;
7696 }
7697 case Expr::CXXDefaultArgExprClass:
7698 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007699 case Expr::CXXDefaultInitExprClass:
7700 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007701 case Expr::ChooseExprClass: {
7702 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7703 }
7704 }
7705
David Blaikiee4d798f2012-01-20 21:50:17 +00007706 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007707}
7708
Richard Smithf57d8cb2011-12-09 22:58:01 +00007709/// Evaluate an expression as a C++11 integral constant expression.
7710static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7711 const Expr *E,
7712 llvm::APSInt *Value,
7713 SourceLocation *Loc) {
7714 if (!E->getType()->isIntegralOrEnumerationType()) {
7715 if (Loc) *Loc = E->getExprLoc();
7716 return false;
7717 }
7718
Richard Smith66e05fe2012-01-18 05:21:49 +00007719 APValue Result;
7720 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007721 return false;
7722
Richard Smith66e05fe2012-01-18 05:21:49 +00007723 assert(Result.isInt() && "pointer cast to int is not an ICE");
7724 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007725 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007726}
7727
Richard Smith92b1ce02011-12-12 09:28:41 +00007728bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007729 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007730 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7731
Richard Smith9e575da2012-12-28 13:25:52 +00007732 ICEDiag D = CheckICE(this, Ctx);
7733 if (D.Kind != IK_ICE) {
7734 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007735 return false;
7736 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007737 return true;
7738}
7739
7740bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7741 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007742 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007743 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7744
7745 if (!isIntegerConstantExpr(Ctx, Loc))
7746 return false;
7747 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007748 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007749 return true;
7750}
Richard Smith66e05fe2012-01-18 05:21:49 +00007751
Richard Smith98a0a492012-02-14 21:38:30 +00007752bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007753 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007754}
7755
Richard Smith66e05fe2012-01-18 05:21:49 +00007756bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7757 SourceLocation *Loc) const {
7758 // We support this checking in C++98 mode in order to diagnose compatibility
7759 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007760 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007761
Richard Smith98a0a492012-02-14 21:38:30 +00007762 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007763 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007764 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007765 Status.Diag = &Diags;
7766 EvalInfo Info(Ctx, Status);
7767
7768 APValue Scratch;
7769 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7770
7771 if (!Diags.empty()) {
7772 IsConstExpr = false;
7773 if (Loc) *Loc = Diags[0].first;
7774 } else if (!IsConstExpr) {
7775 // FIXME: This shouldn't happen.
7776 if (Loc) *Loc = getExprLoc();
7777 }
7778
7779 return IsConstExpr;
7780}
Richard Smith253c2a32012-01-27 01:14:48 +00007781
7782bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007783 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007784 PartialDiagnosticAt> &Diags) {
7785 // FIXME: It would be useful to check constexpr function templates, but at the
7786 // moment the constant expression evaluator cannot cope with the non-rigorous
7787 // ASTs which we build for dependent expressions.
7788 if (FD->isDependentContext())
7789 return true;
7790
7791 Expr::EvalStatus Status;
7792 Status.Diag = &Diags;
7793
7794 EvalInfo Info(FD->getASTContext(), Status);
7795 Info.CheckingPotentialConstantExpression = true;
7796
7797 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7798 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7799
7800 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7801 // is a temporary being used as the 'this' pointer.
7802 LValue This;
7803 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007804 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007805
Richard Smith253c2a32012-01-27 01:14:48 +00007806 ArrayRef<const Expr*> Args;
7807
7808 SourceLocation Loc = FD->getLocation();
7809
Richard Smith2e312c82012-03-03 22:46:17 +00007810 APValue Scratch;
7811 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00007812 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00007813 else
Richard Smith253c2a32012-01-27 01:14:48 +00007814 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7815 Args, FD->getBody(), Info, Scratch);
7816
7817 return Diags.empty();
7818}