blob: 17e174e061a1ed12ad59eb49783d54877197d3e7 [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.
918static void EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
919 APValue Scratch;
920 if (!Evaluate(Scratch, Info, E))
921 Info.EvalStatus.HasSideEffects = true;
922}
923
Richard Smithd62306a2011-11-10 06:34:14 +0000924/// Should this call expression be treated as a string literal?
925static bool IsStringLiteralCall(const CallExpr *E) {
926 unsigned Builtin = E->isBuiltinCall();
927 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
928 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
929}
930
Richard Smithce40ad62011-11-12 22:28:03 +0000931static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000932 // C++11 [expr.const]p3 An address constant expression is a prvalue core
933 // constant expression of pointer type that evaluates to...
934
935 // ... a null pointer value, or a prvalue core constant expression of type
936 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000937 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000938
Richard Smithce40ad62011-11-12 22:28:03 +0000939 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
940 // ... the address of an object with static storage duration,
941 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
942 return VD->hasGlobalStorage();
943 // ... the address of a function,
944 return isa<FunctionDecl>(D);
945 }
946
947 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000948 switch (E->getStmtClass()) {
949 default:
950 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000951 case Expr::CompoundLiteralExprClass: {
952 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
953 return CLE->isFileScope() && CLE->isLValue();
954 }
Richard Smithd62306a2011-11-10 06:34:14 +0000955 // A string literal has static storage duration.
956 case Expr::StringLiteralClass:
957 case Expr::PredefinedExprClass:
958 case Expr::ObjCStringLiteralClass:
959 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000960 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000961 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000962 return true;
963 case Expr::CallExprClass:
964 return IsStringLiteralCall(cast<CallExpr>(E));
965 // For GCC compatibility, &&label has static storage duration.
966 case Expr::AddrLabelExprClass:
967 return true;
968 // A Block literal expression may be used as the initialization value for
969 // Block variables at global or local static scope.
970 case Expr::BlockExprClass:
971 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000972 case Expr::ImplicitValueInitExprClass:
973 // FIXME:
974 // We can never form an lvalue with an implicit value initialization as its
975 // base through expression evaluation, so these only appear in one case: the
976 // implicit variable declaration we invent when checking whether a constexpr
977 // constructor can produce a constant expression. We must assume that such
978 // an expression might be a global lvalue.
979 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000980 }
John McCall95007602010-05-10 23:27:23 +0000981}
982
Richard Smithb228a862012-02-15 02:18:13 +0000983static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
984 assert(Base && "no location for a null lvalue");
985 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
986 if (VD)
987 Info.Note(VD->getLocation(), diag::note_declared_at);
988 else
Ted Kremenek28831752012-08-23 20:46:57 +0000989 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000990 diag::note_constexpr_temporary_here);
991}
992
Richard Smith80815602011-11-07 05:07:52 +0000993/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000994/// value for an address or reference constant expression. Return true if we
995/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +0000996static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
997 QualType Type, const LValue &LVal) {
998 bool IsReferenceType = Type->isReferenceType();
999
Richard Smith357362d2011-12-13 06:39:58 +00001000 APValue::LValueBase Base = LVal.getLValueBase();
1001 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1002
Richard Smith0dea49e2012-02-18 04:58:18 +00001003 // Check that the object is a global. Note that the fake 'this' object we
1004 // manufacture when checking potential constant expressions is conservatively
1005 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001006 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001007 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001008 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001009 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1010 << IsReferenceType << !Designator.Entries.empty()
1011 << !!VD << VD;
1012 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001013 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001014 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001015 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001016 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001017 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001018 }
Richard Smithb228a862012-02-15 02:18:13 +00001019 assert((Info.CheckingPotentialConstantExpression ||
1020 LVal.getLValueCallIndex() == 0) &&
1021 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001022
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001023 // Check if this is a thread-local variable.
1024 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1025 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001026 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001027 return false;
1028 }
1029 }
1030
Richard Smitha8105bc2012-01-06 16:39:00 +00001031 // Allow address constant expressions to be past-the-end pointers. This is
1032 // an extension: the standard requires them to point to an object.
1033 if (!IsReferenceType)
1034 return true;
1035
1036 // A reference constant expression must refer to an object.
1037 if (!Base) {
1038 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001039 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001040 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001041 }
1042
Richard Smith357362d2011-12-13 06:39:58 +00001043 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001044 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001045 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001046 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001047 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001048 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001049 }
1050
Richard Smith80815602011-11-07 05:07:52 +00001051 return true;
1052}
1053
Richard Smithfddd3842011-12-30 21:15:51 +00001054/// Check that this core constant expression is of literal type, and if not,
1055/// produce an appropriate diagnostic.
1056static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001057 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001058 return true;
1059
1060 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001061 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001062 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001063 << E->getType();
1064 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001065 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001066 return false;
1067}
1068
Richard Smith0b0a0b62011-10-29 20:57:55 +00001069/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001070/// constant expression. If not, report an appropriate diagnostic. Does not
1071/// check that the expression is of literal type.
1072static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1073 QualType Type, const APValue &Value) {
1074 // Core issue 1454: For a literal constant expression of array or class type,
1075 // each subobject of its value shall have been initialized by a constant
1076 // expression.
1077 if (Value.isArray()) {
1078 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1079 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1080 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1081 Value.getArrayInitializedElt(I)))
1082 return false;
1083 }
1084 if (!Value.hasArrayFiller())
1085 return true;
1086 return CheckConstantExpression(Info, DiagLoc, EltTy,
1087 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001088 }
Richard Smithb228a862012-02-15 02:18:13 +00001089 if (Value.isUnion() && Value.getUnionField()) {
1090 return CheckConstantExpression(Info, DiagLoc,
1091 Value.getUnionField()->getType(),
1092 Value.getUnionValue());
1093 }
1094 if (Value.isStruct()) {
1095 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1096 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1097 unsigned BaseIndex = 0;
1098 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1099 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1100 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1101 Value.getStructBase(BaseIndex)))
1102 return false;
1103 }
1104 }
1105 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1106 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001107 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1108 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001109 return false;
1110 }
1111 }
1112
1113 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001114 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001115 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001116 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1117 }
1118
1119 // Everything else is fine.
1120 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001121}
1122
Richard Smith83c68212011-10-31 05:11:32 +00001123const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001124 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001125}
1126
1127static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001128 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001129}
1130
Richard Smithcecf1842011-11-01 21:06:14 +00001131static bool IsWeakLValue(const LValue &Value) {
1132 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001133 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001134}
1135
Richard Smith2e312c82012-03-03 22:46:17 +00001136static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001137 // A null base expression indicates a null pointer. These are always
1138 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001139 if (!Value.getLValueBase()) {
1140 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001141 return true;
1142 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001143
Richard Smith027bf112011-11-17 22:56:20 +00001144 // We have a non-null base. These are generally known to be true, but if it's
1145 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001146 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001147 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001148 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001149}
1150
Richard Smith2e312c82012-03-03 22:46:17 +00001151static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001152 switch (Val.getKind()) {
1153 case APValue::Uninitialized:
1154 return false;
1155 case APValue::Int:
1156 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001157 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001158 case APValue::Float:
1159 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001160 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001161 case APValue::ComplexInt:
1162 Result = Val.getComplexIntReal().getBoolValue() ||
1163 Val.getComplexIntImag().getBoolValue();
1164 return true;
1165 case APValue::ComplexFloat:
1166 Result = !Val.getComplexFloatReal().isZero() ||
1167 !Val.getComplexFloatImag().isZero();
1168 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001169 case APValue::LValue:
1170 return EvalPointerValueAsBool(Val, Result);
1171 case APValue::MemberPointer:
1172 Result = Val.getMemberPointerDecl();
1173 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001174 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001175 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001176 case APValue::Struct:
1177 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001178 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001179 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001180 }
1181
Richard Smith11562c52011-10-28 17:51:58 +00001182 llvm_unreachable("unknown APValue kind");
1183}
1184
1185static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1186 EvalInfo &Info) {
1187 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001188 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001189 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001190 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001191 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001192}
1193
Richard Smith357362d2011-12-13 06:39:58 +00001194template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001195static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001196 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001197 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001198 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001199}
1200
1201static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1202 QualType SrcType, const APFloat &Value,
1203 QualType DestType, APSInt &Result) {
1204 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001205 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001206 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001207
Richard Smith357362d2011-12-13 06:39:58 +00001208 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001209 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001210 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1211 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001212 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001213 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001214}
1215
Richard Smith357362d2011-12-13 06:39:58 +00001216static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1217 QualType SrcType, QualType DestType,
1218 APFloat &Result) {
1219 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001220 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001221 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1222 APFloat::rmNearestTiesToEven, &ignored)
1223 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001224 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001225 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001226}
1227
Richard Smith911e1422012-01-30 22:27:01 +00001228static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1229 QualType DestType, QualType SrcType,
1230 APSInt &Value) {
1231 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001232 APSInt Result = Value;
1233 // Figure out if this is a truncate, extend or noop cast.
1234 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001235 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001236 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001237 return Result;
1238}
1239
Richard Smith357362d2011-12-13 06:39:58 +00001240static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1241 QualType SrcType, const APSInt &Value,
1242 QualType DestType, APFloat &Result) {
1243 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1244 if (Result.convertFromAPInt(Value, Value.isSigned(),
1245 APFloat::rmNearestTiesToEven)
1246 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001247 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001248 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001249}
1250
Eli Friedman803acb32011-12-22 03:51:45 +00001251static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1252 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001253 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001254 if (!Evaluate(SVal, Info, E))
1255 return false;
1256 if (SVal.isInt()) {
1257 Res = SVal.getInt();
1258 return true;
1259 }
1260 if (SVal.isFloat()) {
1261 Res = SVal.getFloat().bitcastToAPInt();
1262 return true;
1263 }
1264 if (SVal.isVector()) {
1265 QualType VecTy = E->getType();
1266 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1267 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1268 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1269 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1270 Res = llvm::APInt::getNullValue(VecSize);
1271 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1272 APValue &Elt = SVal.getVectorElt(i);
1273 llvm::APInt EltAsInt;
1274 if (Elt.isInt()) {
1275 EltAsInt = Elt.getInt();
1276 } else if (Elt.isFloat()) {
1277 EltAsInt = Elt.getFloat().bitcastToAPInt();
1278 } else {
1279 // Don't try to handle vectors of anything other than int or float
1280 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001281 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001282 return false;
1283 }
1284 unsigned BaseEltSize = EltAsInt.getBitWidth();
1285 if (BigEndian)
1286 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1287 else
1288 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1289 }
1290 return true;
1291 }
1292 // Give up if the input isn't an int, float, or vector. For example, we
1293 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001294 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001295 return false;
1296}
1297
Richard Smitha8105bc2012-01-06 16:39:00 +00001298/// Cast an lvalue referring to a base subobject to a derived class, by
1299/// truncating the lvalue's path to the given length.
1300static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1301 const RecordDecl *TruncatedType,
1302 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001303 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001304
1305 // Check we actually point to a derived class object.
1306 if (TruncatedElements == D.Entries.size())
1307 return true;
1308 assert(TruncatedElements >= D.MostDerivedPathLength &&
1309 "not casting to a derived class");
1310 if (!Result.checkSubobject(Info, E, CSK_Derived))
1311 return false;
1312
1313 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001314 const RecordDecl *RD = TruncatedType;
1315 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001316 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001317 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1318 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001319 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001320 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001321 else
Richard Smithd62306a2011-11-10 06:34:14 +00001322 Result.Offset -= Layout.getBaseClassOffset(Base);
1323 RD = Base;
1324 }
Richard Smith027bf112011-11-17 22:56:20 +00001325 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001326 return true;
1327}
1328
John McCalld7bca762012-05-01 00:38:49 +00001329static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001330 const CXXRecordDecl *Derived,
1331 const CXXRecordDecl *Base,
1332 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001333 if (!RL) {
1334 if (Derived->isInvalidDecl()) return false;
1335 RL = &Info.Ctx.getASTRecordLayout(Derived);
1336 }
1337
Richard Smithd62306a2011-11-10 06:34:14 +00001338 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001339 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001340 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001341}
1342
Richard Smitha8105bc2012-01-06 16:39:00 +00001343static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001344 const CXXRecordDecl *DerivedDecl,
1345 const CXXBaseSpecifier *Base) {
1346 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1347
John McCalld7bca762012-05-01 00:38:49 +00001348 if (!Base->isVirtual())
1349 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001350
Richard Smitha8105bc2012-01-06 16:39:00 +00001351 SubobjectDesignator &D = Obj.Designator;
1352 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001353 return false;
1354
Richard Smitha8105bc2012-01-06 16:39:00 +00001355 // Extract most-derived object and corresponding type.
1356 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1357 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1358 return false;
1359
1360 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001361 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001362 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1363 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001364 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001365 return true;
1366}
1367
1368/// Update LVal to refer to the given field, which must be a member of the type
1369/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001370static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001371 const FieldDecl *FD,
1372 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001373 if (!RL) {
1374 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001375 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001376 }
Richard Smithd62306a2011-11-10 06:34:14 +00001377
1378 unsigned I = FD->getFieldIndex();
1379 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001380 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001381 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001382}
1383
Richard Smith1b78b3d2012-01-25 22:15:11 +00001384/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001385static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001386 LValue &LVal,
1387 const IndirectFieldDecl *IFD) {
1388 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1389 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001390 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1391 return false;
1392 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001393}
1394
Richard Smithd62306a2011-11-10 06:34:14 +00001395/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001396static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1397 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001398 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1399 // extension.
1400 if (Type->isVoidType() || Type->isFunctionType()) {
1401 Size = CharUnits::One();
1402 return true;
1403 }
1404
1405 if (!Type->isConstantSizeType()) {
1406 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001407 // FIXME: Better diagnostic.
1408 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001409 return false;
1410 }
1411
1412 Size = Info.Ctx.getTypeSizeInChars(Type);
1413 return true;
1414}
1415
1416/// Update a pointer value to model pointer arithmetic.
1417/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001418/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001419/// \param LVal - The pointer value to be updated.
1420/// \param EltTy - The pointee type represented by LVal.
1421/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001422static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1423 LValue &LVal, QualType EltTy,
1424 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001425 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001426 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001427 return false;
1428
1429 // Compute the new offset in the appropriate width.
1430 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001431 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001432 return true;
1433}
1434
Richard Smith66c96992012-02-18 22:04:06 +00001435/// Update an lvalue to refer to a component of a complex number.
1436/// \param Info - Information about the ongoing evaluation.
1437/// \param LVal - The lvalue to be updated.
1438/// \param EltTy - The complex number's component type.
1439/// \param Imag - False for the real component, true for the imaginary.
1440static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1441 LValue &LVal, QualType EltTy,
1442 bool Imag) {
1443 if (Imag) {
1444 CharUnits SizeOfComponent;
1445 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1446 return false;
1447 LVal.Offset += SizeOfComponent;
1448 }
1449 LVal.addComplex(Info, E, EltTy, Imag);
1450 return true;
1451}
1452
Richard Smith27908702011-10-24 17:54:18 +00001453/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001454static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1455 const VarDecl *VD,
Richard Smith2e312c82012-03-03 22:46:17 +00001456 CallStackFrame *Frame, APValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001457 // If this is a parameter to an active constexpr function call, perform
1458 // argument substitution.
1459 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001460 // Assume arguments of a potential constant expression are unknown
1461 // constant expressions.
1462 if (Info.CheckingPotentialConstantExpression)
1463 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001464 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001465 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001466 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001467 }
Richard Smithfec09922011-11-01 16:57:24 +00001468 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1469 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001470 }
Richard Smith27908702011-10-24 17:54:18 +00001471
Richard Smithd9f663b2013-04-22 15:31:51 +00001472 // If this is a local variable, dig out its value.
1473 if (VD->hasLocalStorage() && Frame && Frame->Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001474 // In C++1y, we can't safely read anything which might have been mutated
1475 // when checking a potential constant expression.
1476 if (Info.getLangOpts().CPlusPlus1y &&
1477 Info.CheckingPotentialConstantExpression)
1478 return false;
1479
Richard Smithd9f663b2013-04-22 15:31:51 +00001480 Result = Frame->Temporaries[VD];
1481 // If we've carried on past an unevaluatable local variable initializer,
1482 // we can't go any further. This can happen during potential constant
1483 // expression checking.
1484 return !Result.isUninit();
1485 }
1486
Richard Smithd0b4dd62011-12-19 06:19:21 +00001487 // Dig out the initializer, and use the declaration which it's attached to.
1488 const Expr *Init = VD->getAnyInitializer(VD);
1489 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001490 // If we're checking a potential constant expression, the variable could be
1491 // initialized later.
1492 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001493 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001494 return false;
1495 }
1496
Richard Smithd62306a2011-11-10 06:34:14 +00001497 // If we're currently evaluating the initializer of this declaration, use that
1498 // in-flight value.
1499 if (Info.EvaluatingDecl == VD) {
Richard Smith2e312c82012-03-03 22:46:17 +00001500 Result = *Info.EvaluatingDeclValue;
Richard Smithd62306a2011-11-10 06:34:14 +00001501 return !Result.isUninit();
1502 }
1503
Richard Smithcecf1842011-11-01 21:06:14 +00001504 // Never evaluate the initializer of a weak variable. We can't be sure that
1505 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001506 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001507 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001508 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001509 }
Richard Smithcecf1842011-11-01 21:06:14 +00001510
Richard Smithd0b4dd62011-12-19 06:19:21 +00001511 // Check that we can fold the initializer. In C++, we will have already done
1512 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001513 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001514 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001515 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001516 Notes.size() + 1) << VD;
1517 Info.Note(VD->getLocation(), diag::note_declared_at);
1518 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001519 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001520 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001521 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001522 Notes.size() + 1) << VD;
1523 Info.Note(VD->getLocation(), diag::note_declared_at);
1524 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001525 }
Richard Smith27908702011-10-24 17:54:18 +00001526
Richard Smith2e312c82012-03-03 22:46:17 +00001527 Result = *VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001528 return true;
Richard Smith27908702011-10-24 17:54:18 +00001529}
1530
Richard Smith11562c52011-10-28 17:51:58 +00001531static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001532 Qualifiers Quals = T.getQualifiers();
1533 return Quals.hasConst() && !Quals.hasVolatile();
1534}
1535
Richard Smithe97cbd72011-11-11 04:05:33 +00001536/// Get the base index of the given base class within an APValue representing
1537/// the given derived class.
1538static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1539 const CXXRecordDecl *Base) {
1540 Base = Base->getCanonicalDecl();
1541 unsigned Index = 0;
1542 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1543 E = Derived->bases_end(); I != E; ++I, ++Index) {
1544 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1545 return Index;
1546 }
1547
1548 llvm_unreachable("base class missing from derived class's bases list");
1549}
1550
Richard Smith3da88fa2013-04-26 14:36:30 +00001551/// Extract the value of a character from a string literal.
1552static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1553 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001554 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001555 const StringLiteral *S = cast<StringLiteral>(Lit);
1556 const ConstantArrayType *CAT =
1557 Info.Ctx.getAsConstantArrayType(S->getType());
1558 assert(CAT && "string literal isn't an array");
1559 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001560 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001561
1562 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001563 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001564 if (Index < S->getLength())
1565 Value = S->getCodeUnit(Index);
1566 return Value;
1567}
1568
Richard Smith3da88fa2013-04-26 14:36:30 +00001569// Expand a string literal into an array of characters.
1570static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1571 APValue &Result) {
1572 const StringLiteral *S = cast<StringLiteral>(Lit);
1573 const ConstantArrayType *CAT =
1574 Info.Ctx.getAsConstantArrayType(S->getType());
1575 assert(CAT && "string literal isn't an array");
1576 QualType CharType = CAT->getElementType();
1577 assert(CharType->isIntegerType() && "unexpected character type");
1578
1579 unsigned Elts = CAT->getSize().getZExtValue();
1580 Result = APValue(APValue::UninitArray(),
1581 std::min(S->getLength(), Elts), Elts);
1582 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1583 CharType->isUnsignedIntegerType());
1584 if (Result.hasArrayFiller())
1585 Result.getArrayFiller() = APValue(Value);
1586 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1587 Value = S->getCodeUnit(I);
1588 Result.getArrayInitializedElt(I) = APValue(Value);
1589 }
1590}
1591
1592// Expand an array so that it has more than Index filled elements.
1593static void expandArray(APValue &Array, unsigned Index) {
1594 unsigned Size = Array.getArraySize();
1595 assert(Index < Size);
1596
1597 // Always at least double the number of elements for which we store a value.
1598 unsigned OldElts = Array.getArrayInitializedElts();
1599 unsigned NewElts = std::max(Index+1, OldElts * 2);
1600 NewElts = std::min(Size, std::max(NewElts, 8u));
1601
1602 // Copy the data across.
1603 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1604 for (unsigned I = 0; I != OldElts; ++I)
1605 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1606 for (unsigned I = OldElts; I != NewElts; ++I)
1607 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1608 if (NewValue.hasArrayFiller())
1609 NewValue.getArrayFiller() = Array.getArrayFiller();
1610 Array.swap(NewValue);
1611}
1612
1613/// Kinds of access we can perform on an object.
1614enum AccessKinds {
1615 AK_Read,
1616 AK_Assign
1617};
1618
1619/// Find the designated sub-object of an rvalue.
1620template<typename SubobjectHandler>
1621typename SubobjectHandler::result_type
1622findSubobject(EvalInfo &Info, const Expr *E, APValue &Obj, QualType ObjType,
1623 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001624 if (Sub.Invalid)
1625 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001626 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001627 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001628 if (Info.getLangOpts().CPlusPlus11)
1629 Info.Diag(E, diag::note_constexpr_access_past_end)
1630 << handler.AccessKind;
1631 else
1632 Info.Diag(E);
1633 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001634 }
Richard Smith6804be52011-11-11 08:28:03 +00001635 if (Sub.Entries.empty())
Richard Smith3da88fa2013-04-26 14:36:30 +00001636 return handler.found(Obj, ObjType);
Richard Smith253c2a32012-01-27 01:14:48 +00001637 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1638 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001639 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001640
Richard Smith4e9e5232012-03-10 00:28:11 +00001641 APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001642 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001643 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001644 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001645 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001646 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001647 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001648 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001649 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001650 // Note, it should not be possible to form a pointer with a valid
1651 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001652 if (Info.getLangOpts().CPlusPlus11)
1653 Info.Diag(E, diag::note_constexpr_access_past_end)
1654 << handler.AccessKind;
1655 else
1656 Info.Diag(E);
1657 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001658 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001659
1660 ObjType = CAT->getElementType();
1661
Richard Smith14a94132012-02-17 03:35:37 +00001662 // An array object is represented as either an Array APValue or as an
1663 // LValue which refers to a string literal.
1664 if (O->isLValue()) {
1665 assert(I == N - 1 && "extracting subobject of character?");
1666 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001667 if (handler.AccessKind != AK_Read)
1668 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1669 *O);
1670 else
1671 return handler.foundString(*O, ObjType, Index);
1672 }
1673
1674 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001675 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001676 else if (handler.AccessKind != AK_Read) {
1677 expandArray(*O, Index);
1678 O = &O->getArrayInitializedElt(Index);
1679 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001680 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001681 } else if (ObjType->isAnyComplexType()) {
1682 // Next subobject is a complex number.
1683 uint64_t Index = Sub.Entries[I].ArrayIndex;
1684 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001685 if (Info.getLangOpts().CPlusPlus11)
1686 Info.Diag(E, diag::note_constexpr_access_past_end)
1687 << handler.AccessKind;
1688 else
1689 Info.Diag(E);
1690 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001691 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001692
1693 bool WasConstQualified = ObjType.isConstQualified();
1694 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1695 if (WasConstQualified)
1696 ObjType.addConst();
1697
Richard Smith66c96992012-02-18 22:04:06 +00001698 assert(I == N - 1 && "extracting subobject of scalar?");
1699 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001700 return handler.found(Index ? O->getComplexIntImag()
1701 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001702 } else {
1703 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001704 return handler.found(Index ? O->getComplexFloatImag()
1705 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001706 }
Richard Smithd62306a2011-11-10 06:34:14 +00001707 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001708 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001709 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001710 << Field;
1711 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001712 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001713 }
1714
Richard Smithd62306a2011-11-10 06:34:14 +00001715 // Next subobject is a class, struct or union field.
1716 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1717 if (RD->isUnion()) {
1718 const FieldDecl *UnionField = O->getUnionField();
1719 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001720 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001721 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1722 << handler.AccessKind << Field << !UnionField << UnionField;
1723 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001724 }
Richard Smithd62306a2011-11-10 06:34:14 +00001725 O = &O->getUnionValue();
1726 } else
1727 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001728
1729 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001730 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001731 if (WasConstQualified && !Field->isMutable())
1732 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001733
1734 if (ObjType.isVolatileQualified()) {
1735 if (Info.getLangOpts().CPlusPlus) {
1736 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001737 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1738 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001739 Info.Note(Field->getLocation(), diag::note_declared_at);
1740 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001741 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001742 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001743 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001744 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001745 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001746 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001747 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1748 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1749 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001750
1751 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001752 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001753 if (WasConstQualified)
1754 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001755 }
Richard Smithd62306a2011-11-10 06:34:14 +00001756
Richard Smithf57d8cb2011-12-09 22:58:01 +00001757 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001758 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001759 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1760 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001761 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001762 }
1763
Richard Smith3da88fa2013-04-26 14:36:30 +00001764 return handler.found(*O, ObjType);
1765}
1766
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001767namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001768struct ExtractSubobjectHandler {
1769 EvalInfo &Info;
1770 APValue &Obj;
1771
1772 static const AccessKinds AccessKind = AK_Read;
1773
1774 typedef bool result_type;
1775 bool failed() { return false; }
1776 bool found(APValue &Subobj, QualType SubobjType) {
1777 if (&Subobj != &Obj) {
1778 // We can't just swap Obj and Subobj here, because we'd create an object
1779 // that has itself as a subobject. To avoid the leak, we ensure that Tmp
1780 // ends up owning the original complete object, which is destroyed by
1781 // Tmp's destructor.
1782 APValue Tmp;
1783 Subobj.swap(Tmp);
1784 Obj.swap(Tmp);
1785 }
1786 return true;
1787 }
1788 bool found(APSInt &Value, QualType SubobjType) {
1789 Obj = APValue(Value);
1790 return true;
1791 }
1792 bool found(APFloat &Value, QualType SubobjType) {
1793 Obj = APValue(Value);
1794 return true;
1795 }
1796 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1797 Obj = APValue(extractStringLiteralCharacter(
1798 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1799 return true;
1800 }
1801};
1802const AccessKinds ExtractSubobjectHandler::AccessKind;
1803
1804/// Extract the designated sub-object of an rvalue.
1805static bool extractSubobject(EvalInfo &Info, const Expr *E,
1806 APValue &Obj, QualType ObjType,
1807 const SubobjectDesignator &Sub) {
1808 ExtractSubobjectHandler Handler = { Info, Obj };
1809 return findSubobject(Info, E, Obj, ObjType, Sub, Handler);
1810}
1811
1812struct ModifySubobjectHandler {
1813 EvalInfo &Info;
1814 APValue &NewVal;
1815 const Expr *E;
1816
1817 typedef bool result_type;
1818 static const AccessKinds AccessKind = AK_Assign;
1819
1820 bool checkConst(QualType QT) {
1821 // Assigning to a const object has undefined behavior.
1822 if (QT.isConstQualified()) {
1823 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
1824 return false;
1825 }
1826 return true;
1827 }
1828
1829 bool failed() { return false; }
1830 bool found(APValue &Subobj, QualType SubobjType) {
1831 if (!checkConst(SubobjType))
1832 return false;
1833 // We've been given ownership of NewVal, so just swap it in.
1834 Subobj.swap(NewVal);
1835 return true;
1836 }
1837 bool found(APSInt &Value, QualType SubobjType) {
1838 if (!checkConst(SubobjType))
1839 return false;
1840 if (!NewVal.isInt()) {
1841 // Maybe trying to write a cast pointer value into a complex?
1842 Info.Diag(E);
1843 return false;
1844 }
1845 Value = NewVal.getInt();
1846 return true;
1847 }
1848 bool found(APFloat &Value, QualType SubobjType) {
1849 if (!checkConst(SubobjType))
1850 return false;
1851 Value = NewVal.getFloat();
1852 return true;
1853 }
1854 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1855 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
1856 }
1857};
1858const AccessKinds ModifySubobjectHandler::AccessKind;
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001859} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00001860
1861/// Update the designated sub-object of an rvalue to the given value.
1862static bool modifySubobject(EvalInfo &Info, const Expr *E,
1863 APValue &Obj, QualType ObjType,
1864 const SubobjectDesignator &Sub,
1865 APValue &NewVal) {
1866 ModifySubobjectHandler Handler = { Info, NewVal, E };
1867 return findSubobject(Info, E, Obj, ObjType, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00001868}
1869
Richard Smith84f6dcf2012-02-02 01:16:57 +00001870/// Find the position where two subobject designators diverge, or equivalently
1871/// the length of the common initial subsequence.
1872static unsigned FindDesignatorMismatch(QualType ObjType,
1873 const SubobjectDesignator &A,
1874 const SubobjectDesignator &B,
1875 bool &WasArrayIndex) {
1876 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1877 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001878 if (!ObjType.isNull() &&
1879 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001880 // Next subobject is an array element.
1881 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1882 WasArrayIndex = true;
1883 return I;
1884 }
Richard Smith66c96992012-02-18 22:04:06 +00001885 if (ObjType->isAnyComplexType())
1886 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1887 else
1888 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001889 } else {
1890 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1891 WasArrayIndex = false;
1892 return I;
1893 }
1894 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1895 // Next subobject is a field.
1896 ObjType = FD->getType();
1897 else
1898 // Next subobject is a base class.
1899 ObjType = QualType();
1900 }
1901 }
1902 WasArrayIndex = false;
1903 return I;
1904}
1905
1906/// Determine whether the given subobject designators refer to elements of the
1907/// same array object.
1908static bool AreElementsOfSameArray(QualType ObjType,
1909 const SubobjectDesignator &A,
1910 const SubobjectDesignator &B) {
1911 if (A.Entries.size() != B.Entries.size())
1912 return false;
1913
1914 bool IsArray = A.MostDerivedArraySize != 0;
1915 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1916 // A is a subobject of the array element.
1917 return false;
1918
1919 // If A (and B) designates an array element, the last entry will be the array
1920 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1921 // of length 1' case, and the entire path must match.
1922 bool WasArrayIndex;
1923 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1924 return CommonLength >= A.Entries.size() - IsArray;
1925}
1926
Richard Smithd62306a2011-11-10 06:34:14 +00001927/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
Richard Smith3da88fa2013-04-26 14:36:30 +00001928/// the given glvalue. This can also be used for 'lvalue-to-lvalue' conversions
Richard Smithd62306a2011-11-10 06:34:14 +00001929/// for looking up the glvalue referred to by an entity of reference type.
1930///
1931/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001932/// \param Conv - The expression for which we are performing the conversion.
1933/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001934/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
1935/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00001936/// \param LVal - The glvalue on which we are attempting to perform this action.
1937/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001938static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1939 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00001940 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001941 if (LVal.Designator.Invalid)
1942 // A diagnostic will have already been produced.
1943 return false;
1944
Richard Smithce40ad62011-11-12 22:28:03 +00001945 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith11562c52011-10-28 17:51:58 +00001946
Richard Smithf57d8cb2011-12-09 22:58:01 +00001947 if (!LVal.Base) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001948 Info.Diag(Conv, diag::note_constexpr_access_null) << AK_Read;
Richard Smithf2b681b2011-12-21 05:04:46 +00001949 return false;
1950 }
1951
Richard Smithb228a862012-02-15 02:18:13 +00001952 CallStackFrame *Frame = 0;
1953 if (LVal.CallIndex) {
1954 Frame = Info.getCallFrame(LVal.CallIndex);
1955 if (!Frame) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001956 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1)
1957 << AK_Read << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001958 NoteLValueLocation(Info, LVal.Base);
1959 return false;
1960 }
1961 }
1962
Richard Smithf2b681b2011-12-21 05:04:46 +00001963 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1964 // is not a constant expression (even if the object is non-volatile). We also
1965 // apply this rule to C++98, in order to conform to the expected 'volatile'
1966 // semantics.
1967 if (Type.isVolatileQualified()) {
1968 if (Info.getLangOpts().CPlusPlus)
Richard Smith3da88fa2013-04-26 14:36:30 +00001969 Info.Diag(Conv, diag::note_constexpr_access_volatile_type)
1970 << AK_Read << Type;
Richard Smithf2b681b2011-12-21 05:04:46 +00001971 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001972 Info.Diag(Conv);
Richard Smith11562c52011-10-28 17:51:58 +00001973 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001974 }
Richard Smith11562c52011-10-28 17:51:58 +00001975
Richard Smithce40ad62011-11-12 22:28:03 +00001976 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001977 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1978 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001979 // expressions are constant expressions too. Inside constexpr functions,
1980 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001981 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001982 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001983 if (VD) {
1984 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1985 VD = VDef;
1986 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001987 if (!VD || VD->isInvalidDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001988 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00001989 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001990 }
1991
Richard Smithf2b681b2011-12-21 05:04:46 +00001992 // DR1313: If the object is volatile-qualified but the glvalue was not,
1993 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001994 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001995 if (VT.isVolatileQualified()) {
1996 if (Info.getLangOpts().CPlusPlus) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001997 Info.Diag(Conv, diag::note_constexpr_access_volatile_obj, 1)
1998 << AK_Read << 1 << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001999 Info.Note(VD->getLocation(), diag::note_declared_at);
2000 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002001 Info.Diag(Conv);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002002 }
Richard Smithf2b681b2011-12-21 05:04:46 +00002003 return false;
2004 }
2005
Richard Smithd9f663b2013-04-22 15:31:51 +00002006 // Unless we're looking at a local variable or argument in a constexpr call,
2007 // the variable we're reading must be const.
2008 if (LVal.CallIndex <= 1 || !VD->hasLocalStorage()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002009 if (VD->isConstexpr()) {
2010 // OK, we can read this variable.
2011 } else if (VT->isIntegralOrEnumerationType()) {
2012 if (!VT.isConstQualified()) {
2013 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002014 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00002015 Info.Note(VD->getLocation(), diag::note_declared_at);
2016 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002017 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00002018 }
2019 return false;
2020 }
2021 } else if (VT->isFloatingType() && VT.isConstQualified()) {
2022 // We support folding of const floating-point types, in order to make
2023 // static const data members of such types (supported as an extension)
2024 // more useful.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002025 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002026 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00002027 Info.Note(VD->getLocation(), diag::note_declared_at);
2028 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002029 Info.CCEDiag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00002030 }
2031 } else {
2032 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002033 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002034 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00002035 Info.Note(VD->getLocation(), diag::note_declared_at);
2036 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002037 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00002038 }
Richard Smith96e0c102011-11-04 02:25:55 +00002039 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002040 }
Richard Smith96e0c102011-11-04 02:25:55 +00002041 }
Richard Smithf2b681b2011-12-21 05:04:46 +00002042
Richard Smith3da88fa2013-04-26 14:36:30 +00002043 return EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal) &&
2044 extractSubobject(Info, Conv, RVal, VT, LVal.Designator);
Richard Smith11562c52011-10-28 17:51:58 +00002045 }
2046
Richard Smithf2b681b2011-12-21 05:04:46 +00002047 // Volatile temporary objects cannot be read in constant expressions.
2048 if (Base->getType().isVolatileQualified()) {
2049 if (Info.getLangOpts().CPlusPlus) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002050 Info.Diag(Conv, diag::note_constexpr_access_volatile_obj, 1)
2051 << AK_Read << 0;
Richard Smithf2b681b2011-12-21 05:04:46 +00002052 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2053 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002054 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00002055 }
2056 return false;
2057 }
2058
Richard Smithf3e9e432011-11-07 09:22:26 +00002059 if (Frame) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002060 // In C++1y, we can't safely read anything which might have been mutated
2061 // when checking a potential constant expression.
2062 if (Info.getLangOpts().CPlusPlus1y &&
2063 Info.CheckingPotentialConstantExpression)
2064 return false;
2065
Richard Smithf3e9e432011-11-07 09:22:26 +00002066 // If this is a temporary expression with a nontrivial initializer, grab the
2067 // value from the relevant stack frame.
2068 RVal = Frame->Temporaries[Base];
2069 } else if (const CompoundLiteralExpr *CLE
2070 = dyn_cast<CompoundLiteralExpr>(Base)) {
2071 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2072 // initializer until now for such expressions. Such an expression can't be
2073 // an ICE in C, so this only matters for fold.
2074 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2075 if (!Evaluate(RVal, Info, CLE->getInitializer()))
2076 return false;
Richard Smith14a94132012-02-17 03:35:37 +00002077 } else if (isa<StringLiteral>(Base)) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002078 if (Info.getLangOpts().CPlusPlus1y &&
2079 Info.CheckingPotentialConstantExpression &&
2080 !Base->getType().isConstQualified())
2081 return false;
2082
Richard Smith14a94132012-02-17 03:35:37 +00002083 // We represent a string literal array as an lvalue pointing at the
2084 // corresponding expression, rather than building an array of chars.
2085 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith2e312c82012-03-03 22:46:17 +00002086 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002087 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002088 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00002089 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002090 }
Richard Smith96e0c102011-11-04 02:25:55 +00002091
Richard Smith3da88fa2013-04-26 14:36:30 +00002092 return extractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator);
2093}
2094
2095/// Perform an assignment of Val to LVal. Takes ownership of Val.
2096// FIXME: Factor out duplication with HandleLValueToRValueConversion.
2097static bool HandleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2098 QualType LValType, APValue &Val) {
2099 if (!Info.getLangOpts().CPlusPlus1y) {
2100 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2101 return false;
2102 }
2103
2104 if (LVal.Designator.Invalid)
2105 // A diagnostic will have already been produced.
2106 return false;
2107
2108 if (Info.CheckingPotentialConstantExpression)
2109 return false;
2110
2111 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2112
2113 if (!LVal.Base) {
2114 Info.Diag(E, diag::note_constexpr_access_null) << AK_Assign;
2115 return false;
2116 }
2117
2118 if (!LVal.CallIndex) {
2119 Info.Diag(E, diag::note_constexpr_modify_global);
2120 return false;
2121 }
2122
2123 CallStackFrame *Frame = Info.getCallFrame(LVal.CallIndex);
2124 if (!Frame) {
2125 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2126 << AK_Assign << !Base;
2127 NoteLValueLocation(Info, LVal.Base);
2128 return false;
2129 }
2130
2131 if (LValType.isVolatileQualified()) {
2132 if (Info.getLangOpts().CPlusPlus)
2133 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2134 << AK_Assign << LValType;
2135 else
2136 Info.Diag(E);
2137 return false;
2138 }
2139
2140 // Compute value storage location and type of base object.
2141 APValue *BaseVal = 0;
2142 QualType BaseType;
2143
2144 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2145 const VarDecl *VD = dyn_cast<VarDecl>(D);
2146 if (VD) {
2147 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2148 VD = VDef;
2149 }
2150 if (!VD || VD->isInvalidDecl()) {
2151 Info.Diag(E);
2152 return false;
2153 }
2154
2155 // Modifications to volatile-qualified objects are not allowed.
2156 BaseType = VD->getType();
2157 if (BaseType.isVolatileQualified()) {
2158 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2159 << AK_Assign << 1 << VD;
2160 Info.Note(VD->getLocation(), diag::note_declared_at);
2161 return false;
2162 }
2163
2164 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2165 if (!Frame || !Frame->Arguments) {
2166 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2167 return false;
2168 }
2169 BaseVal = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2170 } else if (VD->hasLocalStorage() && Frame && Frame->Index > 1) {
2171 BaseVal = &Frame->Temporaries[VD];
2172 } else {
2173 // FIXME: Can this happen?
2174 Info.Diag(E);
2175 return false;
2176 }
2177 } else {
2178 BaseType = Base->getType();
2179 BaseVal = &Frame->Temporaries[Base];
2180
2181 // Volatile temporary objects cannot be modified in constant expressions.
2182 if (BaseType.isVolatileQualified()) {
2183 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2184 << AK_Assign << 0;
2185 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2186 return false;
2187 }
2188 }
2189
2190 return modifySubobject(Info, E, *BaseVal, BaseType, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002191}
2192
Richard Smithe97cbd72011-11-11 04:05:33 +00002193/// Build an lvalue for the object argument of a member function call.
2194static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2195 LValue &This) {
2196 if (Object->getType()->isPointerType())
2197 return EvaluatePointer(Object, This, Info);
2198
2199 if (Object->isGLValue())
2200 return EvaluateLValue(Object, This, Info);
2201
Richard Smithd9f663b2013-04-22 15:31:51 +00002202 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002203 return EvaluateTemporary(Object, This, Info);
2204
2205 return false;
2206}
2207
2208/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2209/// lvalue referring to the result.
2210///
2211/// \param Info - Information about the ongoing evaluation.
2212/// \param BO - The member pointer access operation.
2213/// \param LV - Filled in with a reference to the resulting object.
2214/// \param IncludeMember - Specifies whether the member itself is included in
2215/// the resulting LValue subobject designator. This is not possible when
2216/// creating a bound member function.
2217/// \return The field or method declaration to which the member pointer refers,
2218/// or 0 if evaluation fails.
2219static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2220 const BinaryOperator *BO,
2221 LValue &LV,
2222 bool IncludeMember = true) {
2223 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2224
Richard Smith253c2a32012-01-27 01:14:48 +00002225 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2226 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002227 return 0;
2228
2229 MemberPtr MemPtr;
2230 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2231 return 0;
2232
2233 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2234 // member value, the behavior is undefined.
2235 if (!MemPtr.getDecl())
2236 return 0;
2237
Richard Smith253c2a32012-01-27 01:14:48 +00002238 if (!EvalObjOK)
2239 return 0;
2240
Richard Smith027bf112011-11-17 22:56:20 +00002241 if (MemPtr.isDerivedMember()) {
2242 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002243 // The end of the derived-to-base path for the base object must match the
2244 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002245 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002246 LV.Designator.Entries.size())
2247 return 0;
2248 unsigned PathLengthToMember =
2249 LV.Designator.Entries.size() - MemPtr.Path.size();
2250 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2251 const CXXRecordDecl *LVDecl = getAsBaseClass(
2252 LV.Designator.Entries[PathLengthToMember + I]);
2253 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2254 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2255 return 0;
2256 }
2257
2258 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002259 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2260 PathLengthToMember))
2261 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002262 } else if (!MemPtr.Path.empty()) {
2263 // Extend the LValue path with the member pointer's path.
2264 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2265 MemPtr.Path.size() + IncludeMember);
2266
2267 // Walk down to the appropriate base class.
2268 QualType LVType = BO->getLHS()->getType();
2269 if (const PointerType *PT = LVType->getAs<PointerType>())
2270 LVType = PT->getPointeeType();
2271 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2272 assert(RD && "member pointer access on non-class-type expression");
2273 // The first class in the path is that of the lvalue.
2274 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2275 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002276 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2277 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002278 RD = Base;
2279 }
2280 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002281 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2282 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002283 }
2284
2285 // Add the member. Note that we cannot build bound member functions here.
2286 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002287 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2288 if (!HandleLValueMember(Info, BO, LV, FD))
2289 return 0;
2290 } else if (const IndirectFieldDecl *IFD =
2291 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2292 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2293 return 0;
2294 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002295 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002296 }
Richard Smith027bf112011-11-17 22:56:20 +00002297 }
2298
2299 return MemPtr.getDecl();
2300}
2301
2302/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2303/// the provided lvalue, which currently refers to the base object.
2304static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2305 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002306 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002307 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002308 return false;
2309
Richard Smitha8105bc2012-01-06 16:39:00 +00002310 QualType TargetQT = E->getType();
2311 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2312 TargetQT = PT->getPointeeType();
2313
2314 // Check this cast lands within the final derived-to-base subobject path.
2315 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002316 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002317 << D.MostDerivedType << TargetQT;
2318 return false;
2319 }
2320
Richard Smith027bf112011-11-17 22:56:20 +00002321 // Check the type of the final cast. We don't need to check the path,
2322 // since a cast can only be formed if the path is unique.
2323 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002324 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2325 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002326 if (NewEntriesSize == D.MostDerivedPathLength)
2327 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2328 else
Richard Smith027bf112011-11-17 22:56:20 +00002329 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002330 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002331 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002332 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002333 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002334 }
Richard Smith027bf112011-11-17 22:56:20 +00002335
2336 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002337 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002338}
2339
Mike Stump876387b2009-10-27 22:09:17 +00002340namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002341enum EvalStmtResult {
2342 /// Evaluation failed.
2343 ESR_Failed,
2344 /// Hit a 'return' statement.
2345 ESR_Returned,
2346 /// Evaluation succeeded.
2347 ESR_Succeeded
2348};
2349}
2350
Richard Smithd9f663b2013-04-22 15:31:51 +00002351static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2352 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2353 // We don't need to evaluate the initializer for a static local.
2354 if (!VD->hasLocalStorage())
2355 return true;
2356
2357 LValue Result;
2358 Result.set(VD, Info.CurrentCall->Index);
2359 APValue &Val = Info.CurrentCall->Temporaries[VD];
2360
2361 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2362 // Wipe out any partially-computed value, to allow tracking that this
2363 // evaluation failed.
2364 Val = APValue();
2365 return false;
2366 }
2367 }
2368
2369 return true;
2370}
2371
Richard Smith254a73d2011-10-28 22:34:42 +00002372// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002373static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002374 const Stmt *S) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002375 // FIXME: Mark all temporaries in the current frame as destroyed at
2376 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002377 switch (S->getStmtClass()) {
2378 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002379 if (const Expr *E = dyn_cast<Expr>(S)) {
2380 EvaluateIgnoredValue(Info, E);
2381 // Don't bother evaluating beyond an expression-statement which couldn't
2382 // be evaluated.
2383 if (Info.EvalStatus.HasSideEffects && !Info.keepEvaluatingAfterFailure())
2384 return ESR_Failed;
2385 return ESR_Succeeded;
2386 }
2387
2388 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002389 return ESR_Failed;
2390
2391 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002392 return ESR_Succeeded;
2393
Richard Smithd9f663b2013-04-22 15:31:51 +00002394 case Stmt::DeclStmtClass: {
2395 const DeclStmt *DS = cast<DeclStmt>(S);
2396 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2397 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2398 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2399 return ESR_Failed;
2400 return ESR_Succeeded;
2401 }
2402
Richard Smith357362d2011-12-13 06:39:58 +00002403 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002404 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002405 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002406 return ESR_Failed;
2407 return ESR_Returned;
2408 }
Richard Smith254a73d2011-10-28 22:34:42 +00002409
2410 case Stmt::CompoundStmtClass: {
2411 const CompoundStmt *CS = cast<CompoundStmt>(S);
2412 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2413 BE = CS->body_end(); BI != BE; ++BI) {
2414 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2415 if (ESR != ESR_Succeeded)
2416 return ESR;
2417 }
2418 return ESR_Succeeded;
2419 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002420
2421 case Stmt::IfStmtClass: {
2422 const IfStmt *IS = cast<IfStmt>(S);
2423
2424 // Evaluate the condition, as either a var decl or as an expression.
2425 bool Cond;
2426 if (VarDecl *CondDecl = IS->getConditionVariable()) {
2427 if (!EvaluateDecl(Info, CondDecl))
2428 return ESR_Failed;
2429 if (!HandleConversionToBool(Info.CurrentCall->Temporaries[CondDecl],
2430 Cond))
2431 return ESR_Failed;
2432 } else if (!EvaluateAsBooleanCondition(IS->getCond(), Cond, Info))
2433 return ESR_Failed;
2434
2435 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2436 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2437 if (ESR != ESR_Succeeded)
2438 return ESR;
2439 }
2440 return ESR_Succeeded;
2441 }
Richard Smith254a73d2011-10-28 22:34:42 +00002442 }
2443}
2444
Richard Smithcc36f692011-12-22 02:22:31 +00002445/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2446/// default constructor. If so, we'll fold it whether or not it's marked as
2447/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2448/// so we need special handling.
2449static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002450 const CXXConstructorDecl *CD,
2451 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002452 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2453 return false;
2454
Richard Smith66e05fe2012-01-18 05:21:49 +00002455 // Value-initialization does not call a trivial default constructor, so such a
2456 // call is a core constant expression whether or not the constructor is
2457 // constexpr.
2458 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002459 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002460 // FIXME: If DiagDecl is an implicitly-declared special member function,
2461 // we should be much more explicit about why it's not constexpr.
2462 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2463 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2464 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002465 } else {
2466 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2467 }
2468 }
2469 return true;
2470}
2471
Richard Smith357362d2011-12-13 06:39:58 +00002472/// CheckConstexprFunction - Check that a function can be called in a constant
2473/// expression.
2474static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2475 const FunctionDecl *Declaration,
2476 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002477 // Potential constant expressions can contain calls to declared, but not yet
2478 // defined, constexpr functions.
2479 if (Info.CheckingPotentialConstantExpression && !Definition &&
2480 Declaration->isConstexpr())
2481 return false;
2482
Richard Smith357362d2011-12-13 06:39:58 +00002483 // Can we evaluate this function call?
2484 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2485 return true;
2486
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002487 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002488 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002489 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2490 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002491 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2492 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2493 << DiagDecl;
2494 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2495 } else {
2496 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2497 }
2498 return false;
2499}
2500
Richard Smithd62306a2011-11-10 06:34:14 +00002501namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002502typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002503}
2504
2505/// EvaluateArgs - Evaluate the arguments to a function call.
2506static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2507 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002508 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002509 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002510 I != E; ++I) {
2511 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2512 // If we're checking for a potential constant expression, evaluate all
2513 // initializers even if some of them fail.
2514 if (!Info.keepEvaluatingAfterFailure())
2515 return false;
2516 Success = false;
2517 }
2518 }
2519 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002520}
2521
Richard Smith254a73d2011-10-28 22:34:42 +00002522/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002523static bool HandleFunctionCall(SourceLocation CallLoc,
2524 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002525 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002526 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002527 ArgVector ArgValues(Args.size());
2528 if (!EvaluateArgs(Args, ArgValues, Info))
2529 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002530
Richard Smith253c2a32012-01-27 01:14:48 +00002531 if (!Info.CheckCallLimit(CallLoc))
2532 return false;
2533
2534 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd9f663b2013-04-22 15:31:51 +00002535 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00002536 if (ESR == ESR_Succeeded) {
2537 if (Callee->getResultType()->isVoidType())
2538 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002539 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00002540 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002541 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00002542}
2543
Richard Smithd62306a2011-11-10 06:34:14 +00002544/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002545static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002546 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002547 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002548 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002549 ArgVector ArgValues(Args.size());
2550 if (!EvaluateArgs(Args, ArgValues, Info))
2551 return false;
2552
Richard Smith253c2a32012-01-27 01:14:48 +00002553 if (!Info.CheckCallLimit(CallLoc))
2554 return false;
2555
Richard Smith3607ffe2012-02-13 03:54:03 +00002556 const CXXRecordDecl *RD = Definition->getParent();
2557 if (RD->getNumVBases()) {
2558 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2559 return false;
2560 }
2561
Richard Smith253c2a32012-01-27 01:14:48 +00002562 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002563
2564 // If it's a delegating constructor, just delegate.
2565 if (Definition->isDelegatingConstructor()) {
2566 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00002567 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
2568 return false;
2569 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002570 }
2571
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002572 // For a trivial copy or move constructor, perform an APValue copy. This is
2573 // essential for unions, where the operations performed by the constructor
2574 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002575 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002576 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2577 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002578 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002579 RHS.setFrom(Info.Ctx, ArgValues[0]);
2580 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2581 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002582 }
2583
2584 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002585 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002586 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2587 std::distance(RD->field_begin(), RD->field_end()));
2588
John McCalld7bca762012-05-01 00:38:49 +00002589 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002590 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2591
Richard Smith253c2a32012-01-27 01:14:48 +00002592 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002593 unsigned BasesSeen = 0;
2594#ifndef NDEBUG
2595 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2596#endif
2597 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2598 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002599 LValue Subobject = This;
2600 APValue *Value = &Result;
2601
2602 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002603 if ((*I)->isBaseInitializer()) {
2604 QualType BaseType((*I)->getBaseClass(), 0);
2605#ifndef NDEBUG
2606 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002607 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002608 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2609 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2610 "base class initializers not in expected order");
2611 ++BaseIt;
2612#endif
John McCalld7bca762012-05-01 00:38:49 +00002613 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2614 BaseType->getAsCXXRecordDecl(), &Layout))
2615 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002616 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002617 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002618 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2619 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002620 if (RD->isUnion()) {
2621 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002622 Value = &Result.getUnionValue();
2623 } else {
2624 Value = &Result.getStructField(FD->getFieldIndex());
2625 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002626 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002627 // Walk the indirect field decl's chain to find the object to initialize,
2628 // and make sure we've initialized every step along it.
2629 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2630 CE = IFD->chain_end();
2631 C != CE; ++C) {
2632 FieldDecl *FD = cast<FieldDecl>(*C);
2633 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2634 // Switch the union field if it differs. This happens if we had
2635 // preceding zero-initialization, and we're now initializing a union
2636 // subobject other than the first.
2637 // FIXME: In this case, the values of the other subobjects are
2638 // specified, since zero-initialization sets all padding bits to zero.
2639 if (Value->isUninit() ||
2640 (Value->isUnion() && Value->getUnionField() != FD)) {
2641 if (CD->isUnion())
2642 *Value = APValue(FD);
2643 else
2644 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2645 std::distance(CD->field_begin(), CD->field_end()));
2646 }
John McCalld7bca762012-05-01 00:38:49 +00002647 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2648 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002649 if (CD->isUnion())
2650 Value = &Value->getUnionValue();
2651 else
2652 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002653 }
Richard Smithd62306a2011-11-10 06:34:14 +00002654 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002655 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002656 }
Richard Smith253c2a32012-01-27 01:14:48 +00002657
Richard Smithb228a862012-02-15 02:18:13 +00002658 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2659 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002660 ? CCEK_Constant : CCEK_MemberInit)) {
2661 // If we're checking for a potential constant expression, evaluate all
2662 // initializers even if some of them fail.
2663 if (!Info.keepEvaluatingAfterFailure())
2664 return false;
2665 Success = false;
2666 }
Richard Smithd62306a2011-11-10 06:34:14 +00002667 }
2668
Richard Smithd9f663b2013-04-22 15:31:51 +00002669 return Success &&
2670 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002671}
2672
Eli Friedman9a156e52008-11-12 09:44:48 +00002673//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002674// Generic Evaluation
2675//===----------------------------------------------------------------------===//
2676namespace {
2677
Richard Smithf57d8cb2011-12-09 22:58:01 +00002678// FIXME: RetTy is always bool. Remove it.
2679template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002680class ExprEvaluatorBase
2681 : public ConstStmtVisitor<Derived, RetTy> {
2682private:
Richard Smith2e312c82012-03-03 22:46:17 +00002683 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002684 return static_cast<Derived*>(this)->Success(V, E);
2685 }
Richard Smithfddd3842011-12-30 21:15:51 +00002686 RetTy DerivedZeroInitialization(const Expr *E) {
2687 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002688 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002689
Richard Smith17100ba2012-02-16 02:46:34 +00002690 // Check whether a conditional operator with a non-constant condition is a
2691 // potential constant expression. If neither arm is a potential constant
2692 // expression, then the conditional operator is not either.
2693 template<typename ConditionalOperator>
2694 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2695 assert(Info.CheckingPotentialConstantExpression);
2696
2697 // Speculatively evaluate both arms.
2698 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002699 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002700 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2701
2702 StmtVisitorTy::Visit(E->getFalseExpr());
2703 if (Diag.empty())
2704 return;
2705
2706 Diag.clear();
2707 StmtVisitorTy::Visit(E->getTrueExpr());
2708 if (Diag.empty())
2709 return;
2710 }
2711
2712 Error(E, diag::note_constexpr_conditional_never_const);
2713 }
2714
2715
2716 template<typename ConditionalOperator>
2717 bool HandleConditionalOperator(const ConditionalOperator *E) {
2718 bool BoolResult;
2719 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2720 if (Info.CheckingPotentialConstantExpression)
2721 CheckPotentialConstantConditional(E);
2722 return false;
2723 }
2724
2725 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2726 return StmtVisitorTy::Visit(EvalExpr);
2727 }
2728
Peter Collingbournee9200682011-05-13 03:29:01 +00002729protected:
2730 EvalInfo &Info;
2731 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2732 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2733
Richard Smith92b1ce02011-12-12 09:28:41 +00002734 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002735 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002736 }
2737
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002738 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2739
2740public:
2741 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2742
2743 EvalInfo &getEvalInfo() { return Info; }
2744
Richard Smithf57d8cb2011-12-09 22:58:01 +00002745 /// Report an evaluation error. This should only be called when an error is
2746 /// first discovered. When propagating an error, just return false.
2747 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002748 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002749 return false;
2750 }
2751 bool Error(const Expr *E) {
2752 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2753 }
2754
Peter Collingbournee9200682011-05-13 03:29:01 +00002755 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002756 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002757 }
2758 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002759 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002760 }
2761
2762 RetTy VisitParenExpr(const ParenExpr *E)
2763 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2764 RetTy VisitUnaryExtension(const UnaryOperator *E)
2765 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2766 RetTy VisitUnaryPlus(const UnaryOperator *E)
2767 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2768 RetTy VisitChooseExpr(const ChooseExpr *E)
2769 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2770 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2771 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002772 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2773 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002774 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2775 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00002776 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
2777 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002778 // We cannot create any objects for which cleanups are required, so there is
2779 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2780 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2781 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002782
Richard Smith6d6ecc32011-12-12 12:46:16 +00002783 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2784 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2785 return static_cast<Derived*>(this)->VisitCastExpr(E);
2786 }
2787 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2788 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2789 return static_cast<Derived*>(this)->VisitCastExpr(E);
2790 }
2791
Richard Smith027bf112011-11-17 22:56:20 +00002792 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2793 switch (E->getOpcode()) {
2794 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002795 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002796
2797 case BO_Comma:
2798 VisitIgnoredValue(E->getLHS());
2799 return StmtVisitorTy::Visit(E->getRHS());
2800
2801 case BO_PtrMemD:
2802 case BO_PtrMemI: {
2803 LValue Obj;
2804 if (!HandleMemberPointerAccess(Info, E, Obj))
2805 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002806 APValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002807 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002808 return false;
2809 return DerivedSuccess(Result, E);
2810 }
2811 }
2812 }
2813
Peter Collingbournee9200682011-05-13 03:29:01 +00002814 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002815 // Evaluate and cache the common expression. We treat it as a temporary,
2816 // even though it's not quite the same thing.
2817 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2818 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002819 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002820
Richard Smith17100ba2012-02-16 02:46:34 +00002821 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002822 }
2823
2824 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002825 bool IsBcpCall = false;
2826 // If the condition (ignoring parens) is a __builtin_constant_p call,
2827 // the result is a constant expression if it can be folded without
2828 // side-effects. This is an important GNU extension. See GCC PR38377
2829 // for discussion.
2830 if (const CallExpr *CallCE =
2831 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2832 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2833 IsBcpCall = true;
2834
2835 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2836 // constant expression; we can't check whether it's potentially foldable.
2837 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2838 return false;
2839
2840 FoldConstant Fold(Info);
2841
Richard Smith17100ba2012-02-16 02:46:34 +00002842 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00002843 return false;
2844
2845 if (IsBcpCall)
2846 Fold.Fold(Info);
2847
2848 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00002849 }
2850
2851 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002852 APValue &Value = Info.CurrentCall->Temporaries[E];
2853 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002854 const Expr *Source = E->getSourceExpr();
2855 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002856 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002857 if (Source == E) { // sanity checking.
2858 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002859 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002860 }
2861 return StmtVisitorTy::Visit(Source);
2862 }
Richard Smith26d4cc12012-06-26 08:12:11 +00002863 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002864 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002865
Richard Smith254a73d2011-10-28 22:34:42 +00002866 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002867 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002868 QualType CalleeType = Callee->getType();
2869
Richard Smith254a73d2011-10-28 22:34:42 +00002870 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002871 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002872 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00002873 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00002874
Richard Smithe97cbd72011-11-11 04:05:33 +00002875 // Extract function decl and 'this' pointer from the callee.
2876 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002877 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002878 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2879 // Explicit bound member calls, such as x.f() or p->g();
2880 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002881 return false;
2882 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002883 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00002884 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00002885 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2886 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002887 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2888 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002889 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002890 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002891 return Error(Callee);
2892
2893 FD = dyn_cast<FunctionDecl>(Member);
2894 if (!FD)
2895 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002896 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002897 LValue Call;
2898 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002899 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002900
Richard Smitha8105bc2012-01-06 16:39:00 +00002901 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002902 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002903 FD = dyn_cast_or_null<FunctionDecl>(
2904 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002905 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002906 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002907
2908 // Overloaded operator calls to member functions are represented as normal
2909 // calls with '*this' as the first argument.
2910 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2911 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002912 // FIXME: When selecting an implicit conversion for an overloaded
2913 // operator delete, we sometimes try to evaluate calls to conversion
2914 // operators without a 'this' parameter!
2915 if (Args.empty())
2916 return Error(E);
2917
Richard Smithe97cbd72011-11-11 04:05:33 +00002918 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2919 return false;
2920 This = &ThisVal;
2921 Args = Args.slice(1);
2922 }
2923
2924 // Don't call function pointers which have been cast to some other type.
2925 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002926 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002927 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002928 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002929
Richard Smith47b34932012-02-01 02:39:43 +00002930 if (This && !This->checkSubobject(Info, E, CSK_This))
2931 return false;
2932
Richard Smith3607ffe2012-02-13 03:54:03 +00002933 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2934 // calls to such functions in constant expressions.
2935 if (This && !HasQualifier &&
2936 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2937 return Error(E, diag::note_constexpr_virtual_call);
2938
Richard Smith357362d2011-12-13 06:39:58 +00002939 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002940 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00002941 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002942
Richard Smith357362d2011-12-13 06:39:58 +00002943 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00002944 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2945 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002946 return false;
2947
Richard Smithb228a862012-02-15 02:18:13 +00002948 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00002949 }
2950
Richard Smith11562c52011-10-28 17:51:58 +00002951 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2952 return StmtVisitorTy::Visit(E->getInitializer());
2953 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002954 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002955 if (E->getNumInits() == 0)
2956 return DerivedZeroInitialization(E);
2957 if (E->getNumInits() == 1)
2958 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002959 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002960 }
2961 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002962 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002963 }
2964 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002965 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002966 }
Richard Smith027bf112011-11-17 22:56:20 +00002967 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002968 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002969 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002970
Richard Smithd62306a2011-11-10 06:34:14 +00002971 /// A member expression where the object is a prvalue is itself a prvalue.
2972 RetTy VisitMemberExpr(const MemberExpr *E) {
2973 assert(!E->isArrow() && "missing call to bound member function?");
2974
Richard Smith2e312c82012-03-03 22:46:17 +00002975 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00002976 if (!Evaluate(Val, Info, E->getBase()))
2977 return false;
2978
2979 QualType BaseTy = E->getBase()->getType();
2980
2981 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002982 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002983 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00002984 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00002985 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2986
Richard Smitha8105bc2012-01-06 16:39:00 +00002987 SubobjectDesignator Designator(BaseTy);
2988 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002989
Richard Smith3da88fa2013-04-26 14:36:30 +00002990 return extractSubobject(Info, E, Val, BaseTy, Designator) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002991 DerivedSuccess(Val, E);
2992 }
2993
Richard Smith11562c52011-10-28 17:51:58 +00002994 RetTy VisitCastExpr(const CastExpr *E) {
2995 switch (E->getCastKind()) {
2996 default:
2997 break;
2998
David Chisnallfa35df62012-01-16 17:27:18 +00002999 case CK_AtomicToNonAtomic:
3000 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003001 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003002 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003003 return StmtVisitorTy::Visit(E->getSubExpr());
3004
3005 case CK_LValueToRValue: {
3006 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003007 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3008 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003009 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003010 // Note, we use the subexpression's type in order to retain cv-qualifiers.
3011 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
3012 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003013 return false;
3014 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003015 }
3016 }
3017
Richard Smithf57d8cb2011-12-09 22:58:01 +00003018 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003019 }
3020
Richard Smith4a678122011-10-24 18:44:57 +00003021 /// Visit a value which is evaluated, but whose value is ignored.
3022 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003023 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003024 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003025};
3026
3027}
3028
3029//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003030// Common base class for lvalue and temporary evaluation.
3031//===----------------------------------------------------------------------===//
3032namespace {
3033template<class Derived>
3034class LValueExprEvaluatorBase
3035 : public ExprEvaluatorBase<Derived, bool> {
3036protected:
3037 LValue &Result;
3038 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3039 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3040
3041 bool Success(APValue::LValueBase B) {
3042 Result.set(B);
3043 return true;
3044 }
3045
3046public:
3047 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3048 ExprEvaluatorBaseTy(Info), Result(Result) {}
3049
Richard Smith2e312c82012-03-03 22:46:17 +00003050 bool Success(const APValue &V, const Expr *E) {
3051 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003052 return true;
3053 }
Richard Smith027bf112011-11-17 22:56:20 +00003054
Richard Smith027bf112011-11-17 22:56:20 +00003055 bool VisitMemberExpr(const MemberExpr *E) {
3056 // Handle non-static data members.
3057 QualType BaseTy;
3058 if (E->isArrow()) {
3059 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3060 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003061 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003062 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003063 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003064 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3065 return false;
3066 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003067 } else {
3068 if (!this->Visit(E->getBase()))
3069 return false;
3070 BaseTy = E->getBase()->getType();
3071 }
Richard Smith027bf112011-11-17 22:56:20 +00003072
Richard Smith1b78b3d2012-01-25 22:15:11 +00003073 const ValueDecl *MD = E->getMemberDecl();
3074 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3075 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3076 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3077 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003078 if (!HandleLValueMember(this->Info, E, Result, FD))
3079 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003080 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003081 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3082 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003083 } else
3084 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003085
Richard Smith1b78b3d2012-01-25 22:15:11 +00003086 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003087 APValue RefValue;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003088 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003089 RefValue))
3090 return false;
3091 return Success(RefValue, E);
3092 }
3093 return true;
3094 }
3095
3096 bool VisitBinaryOperator(const BinaryOperator *E) {
3097 switch (E->getOpcode()) {
3098 default:
3099 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3100
3101 case BO_PtrMemD:
3102 case BO_PtrMemI:
3103 return HandleMemberPointerAccess(this->Info, E, Result);
Richard Smith3da88fa2013-04-26 14:36:30 +00003104
3105 case BO_Assign: {
3106 if (!this->Visit(E->getLHS()))
3107 return false;
3108 APValue NewVal;
3109 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3110 return false;
3111 return HandleAssignment(this->Info, E, Result, E->getLHS()->getType(),
3112 NewVal);
3113 }
Richard Smith027bf112011-11-17 22:56:20 +00003114 }
3115 }
3116
3117 bool VisitCastExpr(const CastExpr *E) {
3118 switch (E->getCastKind()) {
3119 default:
3120 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3121
3122 case CK_DerivedToBase:
3123 case CK_UncheckedDerivedToBase: {
3124 if (!this->Visit(E->getSubExpr()))
3125 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003126
3127 // Now figure out the necessary offset to add to the base LV to get from
3128 // the derived class to the base class.
3129 QualType Type = E->getSubExpr()->getType();
3130
3131 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3132 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003133 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003134 *PathI))
3135 return false;
3136 Type = (*PathI)->getType();
3137 }
3138
3139 return true;
3140 }
3141 }
3142 }
3143};
3144}
3145
3146//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003147// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003148//
3149// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3150// function designators (in C), decl references to void objects (in C), and
3151// temporaries (if building with -Wno-address-of-temporary).
3152//
3153// LValue evaluation produces values comprising a base expression of one of the
3154// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003155// - Declarations
3156// * VarDecl
3157// * FunctionDecl
3158// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003159// * CompoundLiteralExpr in C
3160// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003161// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003162// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003163// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003164// * ObjCEncodeExpr
3165// * AddrLabelExpr
3166// * BlockExpr
3167// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003168// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003169// * Any Expr, with a CallIndex indicating the function in which the temporary
3170// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003171// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003172//===----------------------------------------------------------------------===//
3173namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003174class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003175 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003176public:
Richard Smith027bf112011-11-17 22:56:20 +00003177 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3178 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003179
Richard Smith11562c52011-10-28 17:51:58 +00003180 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
3181
Peter Collingbournee9200682011-05-13 03:29:01 +00003182 bool VisitDeclRefExpr(const DeclRefExpr *E);
3183 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003184 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003185 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3186 bool VisitMemberExpr(const MemberExpr *E);
3187 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3188 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003189 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003190 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003191 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3192 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003193 bool VisitUnaryReal(const UnaryOperator *E);
3194 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003195
Peter Collingbournee9200682011-05-13 03:29:01 +00003196 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003197 switch (E->getCastKind()) {
3198 default:
Richard Smith027bf112011-11-17 22:56:20 +00003199 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003200
Eli Friedmance3e02a2011-10-11 00:13:24 +00003201 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003202 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003203 if (!Visit(E->getSubExpr()))
3204 return false;
3205 Result.Designator.setInvalid();
3206 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003207
Richard Smith027bf112011-11-17 22:56:20 +00003208 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003209 if (!Visit(E->getSubExpr()))
3210 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003211 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003212 }
3213 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003214};
3215} // end anonymous namespace
3216
Richard Smith11562c52011-10-28 17:51:58 +00003217/// Evaluate an expression as an lvalue. This can be legitimately called on
3218/// expressions which are not glvalues, in a few cases:
3219/// * function designators in C,
3220/// * "extern void" objects,
3221/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00003222static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003223 assert((E->isGLValue() || E->getType()->isFunctionType() ||
3224 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
3225 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00003226 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003227}
3228
Peter Collingbournee9200682011-05-13 03:29:01 +00003229bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003230 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3231 return Success(FD);
3232 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003233 return VisitVarDecl(E, VD);
3234 return Error(E);
3235}
Richard Smith733237d2011-10-24 23:14:33 +00003236
Richard Smith11562c52011-10-28 17:51:58 +00003237bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00003238 if (!VD->getType()->isReferenceType()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003239 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
Richard Smithb228a862012-02-15 02:18:13 +00003240 Result.set(VD, Info.CurrentCall->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003241 return true;
3242 }
Richard Smithce40ad62011-11-12 22:28:03 +00003243 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003244 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003245
Richard Smith2e312c82012-03-03 22:46:17 +00003246 APValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003247 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
3248 return false;
3249 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003250}
3251
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003252bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3253 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003254 if (E->getType()->isRecordType())
3255 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003256
Richard Smithb228a862012-02-15 02:18:13 +00003257 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003258 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3259 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003260}
3261
Peter Collingbournee9200682011-05-13 03:29:01 +00003262bool
3263LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003264 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3265 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3266 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003267 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003268}
3269
Richard Smith6e525142011-12-27 12:18:28 +00003270bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003271 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003272 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003273
3274 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3275 << E->getExprOperand()->getType()
3276 << E->getExprOperand()->getSourceRange();
3277 return false;
Richard Smith6e525142011-12-27 12:18:28 +00003278}
3279
Francois Pichet0066db92012-04-16 04:08:35 +00003280bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3281 return Success(E);
3282}
3283
Peter Collingbournee9200682011-05-13 03:29:01 +00003284bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003285 // Handle static data members.
3286 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3287 VisitIgnoredValue(E->getBase());
3288 return VisitVarDecl(E, VD);
3289 }
3290
Richard Smith254a73d2011-10-28 22:34:42 +00003291 // Handle static member functions.
3292 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3293 if (MD->isStatic()) {
3294 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003295 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003296 }
3297 }
3298
Richard Smithd62306a2011-11-10 06:34:14 +00003299 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003300 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003301}
3302
Peter Collingbournee9200682011-05-13 03:29:01 +00003303bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003304 // FIXME: Deal with vectors as array subscript bases.
3305 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003306 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003307
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003308 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003309 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003310
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003311 APSInt Index;
3312 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003313 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003314 int64_t IndexValue
3315 = Index.isSigned() ? Index.getSExtValue()
3316 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003317
Richard Smitha8105bc2012-01-06 16:39:00 +00003318 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003319}
Eli Friedman9a156e52008-11-12 09:44:48 +00003320
Peter Collingbournee9200682011-05-13 03:29:01 +00003321bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003322 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003323}
3324
Richard Smith66c96992012-02-18 22:04:06 +00003325bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3326 if (!Visit(E->getSubExpr()))
3327 return false;
3328 // __real is a no-op on scalar lvalues.
3329 if (E->getSubExpr()->getType()->isAnyComplexType())
3330 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3331 return true;
3332}
3333
3334bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3335 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3336 "lvalue __imag__ on scalar?");
3337 if (!Visit(E->getSubExpr()))
3338 return false;
3339 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3340 return true;
3341}
3342
Eli Friedman9a156e52008-11-12 09:44:48 +00003343//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003344// Pointer Evaluation
3345//===----------------------------------------------------------------------===//
3346
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003347namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003348class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003349 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003350 LValue &Result;
3351
Peter Collingbournee9200682011-05-13 03:29:01 +00003352 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003353 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003354 return true;
3355 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003356public:
Mike Stump11289f42009-09-09 15:08:12 +00003357
John McCall45d55e42010-05-07 21:00:08 +00003358 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003359 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003360
Richard Smith2e312c82012-03-03 22:46:17 +00003361 bool Success(const APValue &V, const Expr *E) {
3362 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00003363 return true;
3364 }
Richard Smithfddd3842011-12-30 21:15:51 +00003365 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003366 return Success((Expr*)0);
3367 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003368
John McCall45d55e42010-05-07 21:00:08 +00003369 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003370 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003371 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003372 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003373 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003374 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003375 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003376 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003377 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003378 bool VisitCallExpr(const CallExpr *E);
3379 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003380 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003381 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003382 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003383 }
Richard Smithd62306a2011-11-10 06:34:14 +00003384 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3385 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003386 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003387 Result = *Info.CurrentCall->This;
3388 return true;
3389 }
John McCallc07a0c72011-02-17 10:25:35 +00003390
Eli Friedman449fe542009-03-23 04:56:01 +00003391 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003392};
Chris Lattner05706e882008-07-11 18:11:29 +00003393} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003394
John McCall45d55e42010-05-07 21:00:08 +00003395static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003396 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003397 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003398}
3399
John McCall45d55e42010-05-07 21:00:08 +00003400bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003401 if (E->getOpcode() != BO_Add &&
3402 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003403 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003404
Chris Lattner05706e882008-07-11 18:11:29 +00003405 const Expr *PExp = E->getLHS();
3406 const Expr *IExp = E->getRHS();
3407 if (IExp->getType()->isPointerType())
3408 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003409
Richard Smith253c2a32012-01-27 01:14:48 +00003410 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3411 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003412 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003413
John McCall45d55e42010-05-07 21:00:08 +00003414 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003415 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003416 return false;
3417 int64_t AdditionalOffset
3418 = Offset.isSigned() ? Offset.getSExtValue()
3419 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003420 if (E->getOpcode() == BO_Sub)
3421 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003422
Ted Kremenek28831752012-08-23 20:46:57 +00003423 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003424 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3425 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003426}
Eli Friedman9a156e52008-11-12 09:44:48 +00003427
John McCall45d55e42010-05-07 21:00:08 +00003428bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3429 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003430}
Mike Stump11289f42009-09-09 15:08:12 +00003431
Peter Collingbournee9200682011-05-13 03:29:01 +00003432bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3433 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003434
Eli Friedman847a2bc2009-12-27 05:43:15 +00003435 switch (E->getCastKind()) {
3436 default:
3437 break;
3438
John McCalle3027922010-08-25 11:45:40 +00003439 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003440 case CK_CPointerToObjCPointerCast:
3441 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003442 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003443 if (!Visit(SubExpr))
3444 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003445 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3446 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3447 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003448 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003449 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003450 if (SubExpr->getType()->isVoidPointerType())
3451 CCEDiag(E, diag::note_constexpr_invalid_cast)
3452 << 3 << SubExpr->getType();
3453 else
3454 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3455 }
Richard Smith96e0c102011-11-04 02:25:55 +00003456 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003457
Anders Carlsson18275092010-10-31 20:41:46 +00003458 case CK_DerivedToBase:
3459 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003460 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003461 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003462 if (!Result.Base && Result.Offset.isZero())
3463 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003464
Richard Smithd62306a2011-11-10 06:34:14 +00003465 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003466 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003467 QualType Type =
3468 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003469
Richard Smithd62306a2011-11-10 06:34:14 +00003470 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003471 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003472 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3473 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003474 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003475 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003476 }
3477
Anders Carlsson18275092010-10-31 20:41:46 +00003478 return true;
3479 }
3480
Richard Smith027bf112011-11-17 22:56:20 +00003481 case CK_BaseToDerived:
3482 if (!Visit(E->getSubExpr()))
3483 return false;
3484 if (!Result.Base && Result.Offset.isZero())
3485 return true;
3486 return HandleBaseToDerivedCast(Info, E, Result);
3487
Richard Smith0b0a0b62011-10-29 20:57:55 +00003488 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003489 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003490 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003491
John McCalle3027922010-08-25 11:45:40 +00003492 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003493 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3494
Richard Smith2e312c82012-03-03 22:46:17 +00003495 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003496 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003497 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003498
John McCall45d55e42010-05-07 21:00:08 +00003499 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003500 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3501 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003502 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003503 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003504 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003505 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003506 return true;
3507 } else {
3508 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003509 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003510 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003511 }
3512 }
John McCalle3027922010-08-25 11:45:40 +00003513 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003514 if (SubExpr->isGLValue()) {
3515 if (!EvaluateLValue(SubExpr, Result, Info))
3516 return false;
3517 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003518 Result.set(SubExpr, Info.CurrentCall->Index);
3519 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3520 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003521 return false;
3522 }
Richard Smith96e0c102011-11-04 02:25:55 +00003523 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003524 if (const ConstantArrayType *CAT
3525 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3526 Result.addArray(Info, E, CAT);
3527 else
3528 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003529 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003530
John McCalle3027922010-08-25 11:45:40 +00003531 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003532 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003533 }
3534
Richard Smith11562c52011-10-28 17:51:58 +00003535 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003536}
Chris Lattner05706e882008-07-11 18:11:29 +00003537
Peter Collingbournee9200682011-05-13 03:29:01 +00003538bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003539 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003540 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003541
Peter Collingbournee9200682011-05-13 03:29:01 +00003542 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003543}
Chris Lattner05706e882008-07-11 18:11:29 +00003544
3545//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003546// Member Pointer Evaluation
3547//===----------------------------------------------------------------------===//
3548
3549namespace {
3550class MemberPointerExprEvaluator
3551 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3552 MemberPtr &Result;
3553
3554 bool Success(const ValueDecl *D) {
3555 Result = MemberPtr(D);
3556 return true;
3557 }
3558public:
3559
3560 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3561 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3562
Richard Smith2e312c82012-03-03 22:46:17 +00003563 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003564 Result.setFrom(V);
3565 return true;
3566 }
Richard Smithfddd3842011-12-30 21:15:51 +00003567 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003568 return Success((const ValueDecl*)0);
3569 }
3570
3571 bool VisitCastExpr(const CastExpr *E);
3572 bool VisitUnaryAddrOf(const UnaryOperator *E);
3573};
3574} // end anonymous namespace
3575
3576static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3577 EvalInfo &Info) {
3578 assert(E->isRValue() && E->getType()->isMemberPointerType());
3579 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3580}
3581
3582bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3583 switch (E->getCastKind()) {
3584 default:
3585 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3586
3587 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003588 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003589 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003590
3591 case CK_BaseToDerivedMemberPointer: {
3592 if (!Visit(E->getSubExpr()))
3593 return false;
3594 if (E->path_empty())
3595 return true;
3596 // Base-to-derived member pointer casts store the path in derived-to-base
3597 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3598 // the wrong end of the derived->base arc, so stagger the path by one class.
3599 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3600 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3601 PathI != PathE; ++PathI) {
3602 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3603 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3604 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003605 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003606 }
3607 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3608 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003609 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003610 return true;
3611 }
3612
3613 case CK_DerivedToBaseMemberPointer:
3614 if (!Visit(E->getSubExpr()))
3615 return false;
3616 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3617 PathE = E->path_end(); PathI != PathE; ++PathI) {
3618 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3619 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3620 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003621 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003622 }
3623 return true;
3624 }
3625}
3626
3627bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3628 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3629 // member can be formed.
3630 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3631}
3632
3633//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003634// Record Evaluation
3635//===----------------------------------------------------------------------===//
3636
3637namespace {
3638 class RecordExprEvaluator
3639 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3640 const LValue &This;
3641 APValue &Result;
3642 public:
3643
3644 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3645 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3646
Richard Smith2e312c82012-03-03 22:46:17 +00003647 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003648 Result = V;
3649 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003650 }
Richard Smithfddd3842011-12-30 21:15:51 +00003651 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003652
Richard Smithe97cbd72011-11-11 04:05:33 +00003653 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003654 bool VisitInitListExpr(const InitListExpr *E);
3655 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3656 };
3657}
3658
Richard Smithfddd3842011-12-30 21:15:51 +00003659/// Perform zero-initialization on an object of non-union class type.
3660/// C++11 [dcl.init]p5:
3661/// To zero-initialize an object or reference of type T means:
3662/// [...]
3663/// -- if T is a (possibly cv-qualified) non-union class type,
3664/// each non-static data member and each base-class subobject is
3665/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003666static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3667 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003668 const LValue &This, APValue &Result) {
3669 assert(!RD->isUnion() && "Expected non-union class type");
3670 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3671 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3672 std::distance(RD->field_begin(), RD->field_end()));
3673
John McCalld7bca762012-05-01 00:38:49 +00003674 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003675 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3676
3677 if (CD) {
3678 unsigned Index = 0;
3679 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003680 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00003681 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3682 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003683 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3684 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003685 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00003686 Result.getStructBase(Index)))
3687 return false;
3688 }
3689 }
3690
Richard Smitha8105bc2012-01-06 16:39:00 +00003691 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3692 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00003693 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00003694 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00003695 continue;
3696
3697 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003698 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003699 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003700
David Blaikie2d7c57e2012-04-30 02:36:29 +00003701 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003702 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00003703 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003704 return false;
3705 }
3706
3707 return true;
3708}
3709
3710bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3711 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003712 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003713 if (RD->isUnion()) {
3714 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3715 // object's first non-static named data member is zero-initialized
3716 RecordDecl::field_iterator I = RD->field_begin();
3717 if (I == RD->field_end()) {
3718 Result = APValue((const FieldDecl*)0);
3719 return true;
3720 }
3721
3722 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003723 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00003724 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00003725 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003726 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003727 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003728 }
3729
Richard Smith5d108602012-02-17 00:44:16 +00003730 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003731 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00003732 return false;
3733 }
3734
Richard Smitha8105bc2012-01-06 16:39:00 +00003735 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00003736}
3737
Richard Smithe97cbd72011-11-11 04:05:33 +00003738bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3739 switch (E->getCastKind()) {
3740 default:
3741 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3742
3743 case CK_ConstructorConversion:
3744 return Visit(E->getSubExpr());
3745
3746 case CK_DerivedToBase:
3747 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00003748 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003749 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00003750 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003751 if (!DerivedObject.isStruct())
3752 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00003753
3754 // Derived-to-base rvalue conversion: just slice off the derived part.
3755 APValue *Value = &DerivedObject;
3756 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3757 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3758 PathE = E->path_end(); PathI != PathE; ++PathI) {
3759 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3760 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3761 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3762 RD = Base;
3763 }
3764 Result = *Value;
3765 return true;
3766 }
3767 }
3768}
3769
Richard Smithd62306a2011-11-10 06:34:14 +00003770bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00003771 // Cannot constant-evaluate std::initializer_list inits.
3772 if (E->initializesStdInitializerList())
3773 return false;
3774
Richard Smithd62306a2011-11-10 06:34:14 +00003775 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003776 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003777 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3778
3779 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00003780 const FieldDecl *Field = E->getInitializedFieldInUnion();
3781 Result = APValue(Field);
3782 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00003783 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00003784
3785 // If the initializer list for a union does not contain any elements, the
3786 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00003787 // FIXME: The element should be initialized from an initializer list.
3788 // Is this difference ever observable for initializer lists which
3789 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00003790 ImplicitValueInitExpr VIE(Field->getType());
3791 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3792
Richard Smithd62306a2011-11-10 06:34:14 +00003793 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003794 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3795 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00003796
3797 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3798 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3799 isa<CXXDefaultInitExpr>(InitExpr));
3800
Richard Smithb228a862012-02-15 02:18:13 +00003801 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00003802 }
3803
3804 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3805 "initializer list for class with base classes");
3806 Result = APValue(APValue::UninitStruct(), 0,
3807 std::distance(RD->field_begin(), RD->field_end()));
3808 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00003809 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003810 for (RecordDecl::field_iterator Field = RD->field_begin(),
3811 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3812 // Anonymous bit-fields are not considered members of the class for
3813 // purposes of aggregate initialization.
3814 if (Field->isUnnamedBitfield())
3815 continue;
3816
3817 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003818
Richard Smith253c2a32012-01-27 01:14:48 +00003819 bool HaveInit = ElementNo < E->getNumInits();
3820
3821 // FIXME: Diagnostics here should point to the end of the initializer
3822 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00003823 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00003824 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003825 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003826
3827 // Perform an implicit value-initialization for members beyond the end of
3828 // the initializer list.
3829 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00003830 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00003831
Richard Smith852c9db2013-04-20 22:23:05 +00003832 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3833 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3834 isa<CXXDefaultInitExpr>(Init));
3835
3836 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
3837 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00003838 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00003839 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003840 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00003841 }
3842 }
3843
Richard Smith253c2a32012-01-27 01:14:48 +00003844 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003845}
3846
3847bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3848 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00003849 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3850
Richard Smithfddd3842011-12-30 21:15:51 +00003851 bool ZeroInit = E->requiresZeroInitialization();
3852 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00003853 // If we've already performed zero-initialization, we're already done.
3854 if (!Result.isUninit())
3855 return true;
3856
Richard Smithfddd3842011-12-30 21:15:51 +00003857 if (ZeroInit)
3858 return ZeroInitialization(E);
3859
Richard Smithcc36f692011-12-22 02:22:31 +00003860 const CXXRecordDecl *RD = FD->getParent();
3861 if (RD->isUnion())
3862 Result = APValue((FieldDecl*)0);
3863 else
3864 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3865 std::distance(RD->field_begin(), RD->field_end()));
3866 return true;
3867 }
3868
Richard Smithd62306a2011-11-10 06:34:14 +00003869 const FunctionDecl *Definition = 0;
3870 FD->getBody(Definition);
3871
Richard Smith357362d2011-12-13 06:39:58 +00003872 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3873 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003874
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003875 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00003876 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003877 if (const MaterializeTemporaryExpr *ME
3878 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3879 return Visit(ME->GetTemporaryExpr());
3880
Richard Smithfddd3842011-12-30 21:15:51 +00003881 if (ZeroInit && !ZeroInitialization(E))
3882 return false;
3883
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003884 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00003885 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003886 cast<CXXConstructorDecl>(Definition), Info,
3887 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003888}
3889
3890static bool EvaluateRecord(const Expr *E, const LValue &This,
3891 APValue &Result, EvalInfo &Info) {
3892 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003893 "can't evaluate expression as a record rvalue");
3894 return RecordExprEvaluator(Info, This, Result).Visit(E);
3895}
3896
3897//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003898// Temporary Evaluation
3899//
3900// Temporaries are represented in the AST as rvalues, but generally behave like
3901// lvalues. The full-object of which the temporary is a subobject is implicitly
3902// materialized so that a reference can bind to it.
3903//===----------------------------------------------------------------------===//
3904namespace {
3905class TemporaryExprEvaluator
3906 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3907public:
3908 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3909 LValueExprEvaluatorBaseTy(Info, Result) {}
3910
3911 /// Visit an expression which constructs the value of this temporary.
3912 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003913 Result.set(E, Info.CurrentCall->Index);
3914 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00003915 }
3916
3917 bool VisitCastExpr(const CastExpr *E) {
3918 switch (E->getCastKind()) {
3919 default:
3920 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3921
3922 case CK_ConstructorConversion:
3923 return VisitConstructExpr(E->getSubExpr());
3924 }
3925 }
3926 bool VisitInitListExpr(const InitListExpr *E) {
3927 return VisitConstructExpr(E);
3928 }
3929 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3930 return VisitConstructExpr(E);
3931 }
3932 bool VisitCallExpr(const CallExpr *E) {
3933 return VisitConstructExpr(E);
3934 }
3935};
3936} // end anonymous namespace
3937
3938/// Evaluate an expression of record type as a temporary.
3939static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003940 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003941 return TemporaryExprEvaluator(Info, Result).Visit(E);
3942}
3943
3944//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003945// Vector Evaluation
3946//===----------------------------------------------------------------------===//
3947
3948namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003949 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003950 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3951 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003952 public:
Mike Stump11289f42009-09-09 15:08:12 +00003953
Richard Smith2d406342011-10-22 21:10:00 +00003954 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3955 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003956
Richard Smith2d406342011-10-22 21:10:00 +00003957 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3958 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3959 // FIXME: remove this APValue copy.
3960 Result = APValue(V.data(), V.size());
3961 return true;
3962 }
Richard Smith2e312c82012-03-03 22:46:17 +00003963 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00003964 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003965 Result = V;
3966 return true;
3967 }
Richard Smithfddd3842011-12-30 21:15:51 +00003968 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003969
Richard Smith2d406342011-10-22 21:10:00 +00003970 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003971 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003972 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003973 bool VisitInitListExpr(const InitListExpr *E);
3974 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003975 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003976 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003977 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003978 };
3979} // end anonymous namespace
3980
3981static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003982 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003983 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003984}
3985
Richard Smith2d406342011-10-22 21:10:00 +00003986bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3987 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003988 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003989
Richard Smith161f09a2011-12-06 22:44:34 +00003990 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003991 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003992
Eli Friedmanc757de22011-03-25 00:43:55 +00003993 switch (E->getCastKind()) {
3994 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003995 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003996 if (SETy->isIntegerType()) {
3997 APSInt IntResult;
3998 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003999 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004000 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004001 } else if (SETy->isRealFloatingType()) {
4002 APFloat F(0.0);
4003 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004004 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004005 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004006 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004007 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004008 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004009
4010 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004011 SmallVector<APValue, 4> Elts(NElts, Val);
4012 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004013 }
Eli Friedman803acb32011-12-22 03:51:45 +00004014 case CK_BitCast: {
4015 // Evaluate the operand into an APInt we can extract from.
4016 llvm::APInt SValInt;
4017 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4018 return false;
4019 // Extract the elements
4020 QualType EltTy = VTy->getElementType();
4021 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4022 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4023 SmallVector<APValue, 4> Elts;
4024 if (EltTy->isRealFloatingType()) {
4025 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004026 unsigned FloatEltSize = EltSize;
4027 if (&Sem == &APFloat::x87DoubleExtended)
4028 FloatEltSize = 80;
4029 for (unsigned i = 0; i < NElts; i++) {
4030 llvm::APInt Elt;
4031 if (BigEndian)
4032 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4033 else
4034 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004035 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004036 }
4037 } else if (EltTy->isIntegerType()) {
4038 for (unsigned i = 0; i < NElts; i++) {
4039 llvm::APInt Elt;
4040 if (BigEndian)
4041 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4042 else
4043 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4044 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4045 }
4046 } else {
4047 return Error(E);
4048 }
4049 return Success(Elts, E);
4050 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004051 default:
Richard Smith11562c52011-10-28 17:51:58 +00004052 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004053 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004054}
4055
Richard Smith2d406342011-10-22 21:10:00 +00004056bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004057VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004058 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004059 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004060 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004061
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004062 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004063 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004064
Eli Friedmanb9c71292012-01-03 23:24:20 +00004065 // The number of initializers can be less than the number of
4066 // vector elements. For OpenCL, this can be due to nested vector
4067 // initialization. For GCC compatibility, missing trailing elements
4068 // should be initialized with zeroes.
4069 unsigned CountInits = 0, CountElts = 0;
4070 while (CountElts < NumElements) {
4071 // Handle nested vector initialization.
4072 if (CountInits < NumInits
4073 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4074 APValue v;
4075 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4076 return Error(E);
4077 unsigned vlen = v.getVectorLength();
4078 for (unsigned j = 0; j < vlen; j++)
4079 Elements.push_back(v.getVectorElt(j));
4080 CountElts += vlen;
4081 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004082 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004083 if (CountInits < NumInits) {
4084 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004085 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004086 } else // trailing integer zero.
4087 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4088 Elements.push_back(APValue(sInt));
4089 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004090 } else {
4091 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004092 if (CountInits < NumInits) {
4093 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004094 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004095 } else // trailing float zero.
4096 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4097 Elements.push_back(APValue(f));
4098 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004099 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004100 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004101 }
Richard Smith2d406342011-10-22 21:10:00 +00004102 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004103}
4104
Richard Smith2d406342011-10-22 21:10:00 +00004105bool
Richard Smithfddd3842011-12-30 21:15:51 +00004106VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004107 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004108 QualType EltTy = VT->getElementType();
4109 APValue ZeroElement;
4110 if (EltTy->isIntegerType())
4111 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4112 else
4113 ZeroElement =
4114 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4115
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004116 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004117 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004118}
4119
Richard Smith2d406342011-10-22 21:10:00 +00004120bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004121 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004122 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004123}
4124
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004125//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004126// Array Evaluation
4127//===----------------------------------------------------------------------===//
4128
4129namespace {
4130 class ArrayExprEvaluator
4131 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004132 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004133 APValue &Result;
4134 public:
4135
Richard Smithd62306a2011-11-10 06:34:14 +00004136 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4137 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004138
4139 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004140 assert((V.isArray() || V.isLValue()) &&
4141 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004142 Result = V;
4143 return true;
4144 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004145
Richard Smithfddd3842011-12-30 21:15:51 +00004146 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004147 const ConstantArrayType *CAT =
4148 Info.Ctx.getAsConstantArrayType(E->getType());
4149 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004150 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004151
4152 Result = APValue(APValue::UninitArray(), 0,
4153 CAT->getSize().getZExtValue());
4154 if (!Result.hasArrayFiller()) return true;
4155
Richard Smithfddd3842011-12-30 21:15:51 +00004156 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004157 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004158 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004159 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004160 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004161 }
4162
Richard Smithf3e9e432011-11-07 09:22:26 +00004163 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004164 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004165 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4166 const LValue &Subobject,
4167 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004168 };
4169} // end anonymous namespace
4170
Richard Smithd62306a2011-11-10 06:34:14 +00004171static bool EvaluateArray(const Expr *E, const LValue &This,
4172 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004173 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004174 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004175}
4176
4177bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4178 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4179 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004180 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004181
Richard Smithca2cfbf2011-12-22 01:07:19 +00004182 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4183 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004184 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004185 LValue LV;
4186 if (!EvaluateLValue(E->getInit(0), LV, Info))
4187 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004188 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004189 LV.moveInto(Val);
4190 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004191 }
4192
Richard Smith253c2a32012-01-27 01:14:48 +00004193 bool Success = true;
4194
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004195 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4196 "zero-initialized array shouldn't have any initialized elts");
4197 APValue Filler;
4198 if (Result.isArray() && Result.hasArrayFiller())
4199 Filler = Result.getArrayFiller();
4200
Richard Smith9543c5e2013-04-22 14:44:29 +00004201 unsigned NumEltsToInit = E->getNumInits();
4202 unsigned NumElts = CAT->getSize().getZExtValue();
4203 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4204
4205 // If the initializer might depend on the array index, run it for each
4206 // array element. For now, just whitelist non-class value-initialization.
4207 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4208 NumEltsToInit = NumElts;
4209
4210 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004211
4212 // If the array was previously zero-initialized, preserve the
4213 // zero-initialized values.
4214 if (!Filler.isUninit()) {
4215 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4216 Result.getArrayInitializedElt(I) = Filler;
4217 if (Result.hasArrayFiller())
4218 Result.getArrayFiller() = Filler;
4219 }
4220
Richard Smithd62306a2011-11-10 06:34:14 +00004221 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004222 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004223 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4224 const Expr *Init =
4225 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00004226 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00004227 Info, Subobject, Init) ||
4228 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00004229 CAT->getElementType(), 1)) {
4230 if (!Info.keepEvaluatingAfterFailure())
4231 return false;
4232 Success = false;
4233 }
Richard Smithd62306a2011-11-10 06:34:14 +00004234 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004235
Richard Smith9543c5e2013-04-22 14:44:29 +00004236 if (!Result.hasArrayFiller())
4237 return Success;
4238
4239 // If we get here, we have a trivial filler, which we can just evaluate
4240 // once and splat over the rest of the array elements.
4241 assert(FillerExpr && "no array filler for incomplete init list");
4242 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4243 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00004244}
4245
Richard Smith027bf112011-11-17 22:56:20 +00004246bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004247 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4248}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004249
Richard Smith9543c5e2013-04-22 14:44:29 +00004250bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4251 const LValue &Subobject,
4252 APValue *Value,
4253 QualType Type) {
4254 bool HadZeroInit = !Value->isUninit();
4255
4256 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4257 unsigned N = CAT->getSize().getZExtValue();
4258
4259 // Preserve the array filler if we had prior zero-initialization.
4260 APValue Filler =
4261 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4262 : APValue();
4263
4264 *Value = APValue(APValue::UninitArray(), N, N);
4265
4266 if (HadZeroInit)
4267 for (unsigned I = 0; I != N; ++I)
4268 Value->getArrayInitializedElt(I) = Filler;
4269
4270 // Initialize the elements.
4271 LValue ArrayElt = Subobject;
4272 ArrayElt.addArray(Info, E, CAT);
4273 for (unsigned I = 0; I != N; ++I)
4274 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4275 CAT->getElementType()) ||
4276 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4277 CAT->getElementType(), 1))
4278 return false;
4279
4280 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004281 }
Richard Smith027bf112011-11-17 22:56:20 +00004282
Richard Smith9543c5e2013-04-22 14:44:29 +00004283 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004284 return Error(E);
4285
Richard Smith027bf112011-11-17 22:56:20 +00004286 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004287
Richard Smithfddd3842011-12-30 21:15:51 +00004288 bool ZeroInit = E->requiresZeroInitialization();
4289 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004290 if (HadZeroInit)
4291 return true;
4292
Richard Smithfddd3842011-12-30 21:15:51 +00004293 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004294 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004295 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004296 }
4297
Richard Smithcc36f692011-12-22 02:22:31 +00004298 const CXXRecordDecl *RD = FD->getParent();
4299 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004300 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004301 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004302 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004303 APValue(APValue::UninitStruct(), RD->getNumBases(),
4304 std::distance(RD->field_begin(), RD->field_end()));
4305 return true;
4306 }
4307
Richard Smith027bf112011-11-17 22:56:20 +00004308 const FunctionDecl *Definition = 0;
4309 FD->getBody(Definition);
4310
Richard Smith357362d2011-12-13 06:39:58 +00004311 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4312 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004313
Richard Smith9eae7232012-01-12 18:54:33 +00004314 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004315 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004316 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004317 return false;
4318 }
4319
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004320 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004321 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004322 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004323 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004324}
4325
Richard Smithf3e9e432011-11-07 09:22:26 +00004326//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004327// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004328//
4329// As a GNU extension, we support casting pointers to sufficiently-wide integer
4330// types and back in constant folding. Integer values are thus represented
4331// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004332//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004333
4334namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004335class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004336 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004337 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004338public:
Richard Smith2e312c82012-03-03 22:46:17 +00004339 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004340 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004341
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004342 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004343 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004344 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004345 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004346 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004347 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004348 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004349 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004350 return true;
4351 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004352 bool Success(const llvm::APSInt &SI, const Expr *E) {
4353 return Success(SI, E, Result);
4354 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004355
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004356 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004357 assert(E->getType()->isIntegralOrEnumerationType() &&
4358 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004359 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004360 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004361 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004362 Result.getInt().setIsUnsigned(
4363 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004364 return true;
4365 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004366 bool Success(const llvm::APInt &I, const Expr *E) {
4367 return Success(I, E, Result);
4368 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004369
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004370 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004371 assert(E->getType()->isIntegralOrEnumerationType() &&
4372 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004373 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004374 return true;
4375 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004376 bool Success(uint64_t Value, const Expr *E) {
4377 return Success(Value, E, Result);
4378 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004379
Ken Dyckdbc01912011-03-11 02:13:43 +00004380 bool Success(CharUnits Size, const Expr *E) {
4381 return Success(Size.getQuantity(), E);
4382 }
4383
Richard Smith2e312c82012-03-03 22:46:17 +00004384 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004385 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00004386 Result = V;
4387 return true;
4388 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004389 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004390 }
Mike Stump11289f42009-09-09 15:08:12 +00004391
Richard Smithfddd3842011-12-30 21:15:51 +00004392 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00004393
Peter Collingbournee9200682011-05-13 03:29:01 +00004394 //===--------------------------------------------------------------------===//
4395 // Visitor Methods
4396 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004397
Chris Lattner7174bf32008-07-12 00:38:25 +00004398 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004399 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004400 }
4401 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004402 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004403 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004404
4405 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4406 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004407 if (CheckReferencedDecl(E, E->getDecl()))
4408 return true;
4409
4410 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004411 }
4412 bool VisitMemberExpr(const MemberExpr *E) {
4413 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004414 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004415 return true;
4416 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004417
4418 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004419 }
4420
Peter Collingbournee9200682011-05-13 03:29:01 +00004421 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004422 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004423 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004424 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004425
Peter Collingbournee9200682011-05-13 03:29:01 +00004426 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004427 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004428
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004429 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004430 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004431 }
Mike Stump11289f42009-09-09 15:08:12 +00004432
Ted Kremeneke65b0862012-03-06 20:05:56 +00004433 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4434 return Success(E->getValue(), E);
4435 }
4436
Richard Smith4ce706a2011-10-11 21:43:33 +00004437 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004438 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004439 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004440 }
4441
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004442 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004443 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004444 }
4445
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004446 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4447 return Success(E->getValue(), E);
4448 }
4449
Douglas Gregor29c42f22012-02-24 07:38:34 +00004450 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4451 return Success(E->getValue(), E);
4452 }
4453
John Wiegley6242b6a2011-04-28 00:16:57 +00004454 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4455 return Success(E->getValue(), E);
4456 }
4457
John Wiegleyf9f65842011-04-25 06:54:41 +00004458 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4459 return Success(E->getValue(), E);
4460 }
4461
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004462 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004463 bool VisitUnaryImag(const UnaryOperator *E);
4464
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004465 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004466 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004467
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004468private:
Ken Dyck160146e2010-01-27 17:10:57 +00004469 CharUnits GetAlignOfExpr(const Expr *E);
4470 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004471 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004472 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004473 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004474};
Chris Lattner05706e882008-07-11 18:11:29 +00004475} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004476
Richard Smith11562c52011-10-28 17:51:58 +00004477/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4478/// produce either the integer value or a pointer.
4479///
4480/// GCC has a heinous extension which folds casts between pointer types and
4481/// pointer-sized integral types. We support this by allowing the evaluation of
4482/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4483/// Some simple arithmetic on such values is supported (they are treated much
4484/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004485static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004486 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004487 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004488 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004489}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004490
Richard Smithf57d8cb2011-12-09 22:58:01 +00004491static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004492 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004493 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004494 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004495 if (!Val.isInt()) {
4496 // FIXME: It would be better to produce the diagnostic for casting
4497 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004498 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004499 return false;
4500 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004501 Result = Val.getInt();
4502 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004503}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004504
Richard Smithf57d8cb2011-12-09 22:58:01 +00004505/// Check whether the given declaration can be directly converted to an integral
4506/// rvalue. If not, no diagnostic is produced; there are other things we can
4507/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004508bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004509 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004510 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004511 // Check for signedness/width mismatches between E type and ECD value.
4512 bool SameSign = (ECD->getInitVal().isSigned()
4513 == E->getType()->isSignedIntegerOrEnumerationType());
4514 bool SameWidth = (ECD->getInitVal().getBitWidth()
4515 == Info.Ctx.getIntWidth(E->getType()));
4516 if (SameSign && SameWidth)
4517 return Success(ECD->getInitVal(), E);
4518 else {
4519 // Get rid of mismatch (otherwise Success assertions will fail)
4520 // by computing a new value matching the type of E.
4521 llvm::APSInt Val = ECD->getInitVal();
4522 if (!SameSign)
4523 Val.setIsSigned(!ECD->getInitVal().isSigned());
4524 if (!SameWidth)
4525 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4526 return Success(Val, E);
4527 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004528 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004529 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004530}
4531
Chris Lattner86ee2862008-10-06 06:40:35 +00004532/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4533/// as GCC.
4534static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4535 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004536 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004537 enum gcc_type_class {
4538 no_type_class = -1,
4539 void_type_class, integer_type_class, char_type_class,
4540 enumeral_type_class, boolean_type_class,
4541 pointer_type_class, reference_type_class, offset_type_class,
4542 real_type_class, complex_type_class,
4543 function_type_class, method_type_class,
4544 record_type_class, union_type_class,
4545 array_type_class, string_type_class,
4546 lang_type_class
4547 };
Mike Stump11289f42009-09-09 15:08:12 +00004548
4549 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004550 // ideal, however it is what gcc does.
4551 if (E->getNumArgs() == 0)
4552 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004553
Chris Lattner86ee2862008-10-06 06:40:35 +00004554 QualType ArgTy = E->getArg(0)->getType();
4555 if (ArgTy->isVoidType())
4556 return void_type_class;
4557 else if (ArgTy->isEnumeralType())
4558 return enumeral_type_class;
4559 else if (ArgTy->isBooleanType())
4560 return boolean_type_class;
4561 else if (ArgTy->isCharType())
4562 return string_type_class; // gcc doesn't appear to use char_type_class
4563 else if (ArgTy->isIntegerType())
4564 return integer_type_class;
4565 else if (ArgTy->isPointerType())
4566 return pointer_type_class;
4567 else if (ArgTy->isReferenceType())
4568 return reference_type_class;
4569 else if (ArgTy->isRealType())
4570 return real_type_class;
4571 else if (ArgTy->isComplexType())
4572 return complex_type_class;
4573 else if (ArgTy->isFunctionType())
4574 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004575 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004576 return record_type_class;
4577 else if (ArgTy->isUnionType())
4578 return union_type_class;
4579 else if (ArgTy->isArrayType())
4580 return array_type_class;
4581 else if (ArgTy->isUnionType())
4582 return union_type_class;
4583 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004584 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004585}
4586
Richard Smith5fab0c92011-12-28 19:48:30 +00004587/// EvaluateBuiltinConstantPForLValue - Determine the result of
4588/// __builtin_constant_p when applied to the given lvalue.
4589///
4590/// An lvalue is only "constant" if it is a pointer or reference to the first
4591/// character of a string literal.
4592template<typename LValue>
4593static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004594 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004595 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4596}
4597
4598/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4599/// GCC as we can manage.
4600static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4601 QualType ArgType = Arg->getType();
4602
4603 // __builtin_constant_p always has one operand. The rules which gcc follows
4604 // are not precisely documented, but are as follows:
4605 //
4606 // - If the operand is of integral, floating, complex or enumeration type,
4607 // and can be folded to a known value of that type, it returns 1.
4608 // - If the operand and can be folded to a pointer to the first character
4609 // of a string literal (or such a pointer cast to an integral type), it
4610 // returns 1.
4611 //
4612 // Otherwise, it returns 0.
4613 //
4614 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4615 // its support for this does not currently work.
4616 if (ArgType->isIntegralOrEnumerationType()) {
4617 Expr::EvalResult Result;
4618 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4619 return false;
4620
4621 APValue &V = Result.Val;
4622 if (V.getKind() == APValue::Int)
4623 return true;
4624
4625 return EvaluateBuiltinConstantPForLValue(V);
4626 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4627 return Arg->isEvaluatable(Ctx);
4628 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4629 LValue LV;
4630 Expr::EvalStatus Status;
4631 EvalInfo Info(Ctx, Status);
4632 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4633 : EvaluatePointer(Arg, LV, Info)) &&
4634 !Status.HasSideEffects)
4635 return EvaluateBuiltinConstantPForLValue(LV);
4636 }
4637
4638 // Anything else isn't considered to be sufficiently constant.
4639 return false;
4640}
4641
John McCall95007602010-05-10 23:27:23 +00004642/// Retrieves the "underlying object type" of the given expression,
4643/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004644QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4645 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4646 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004647 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004648 } else if (const Expr *E = B.get<const Expr*>()) {
4649 if (isa<CompoundLiteralExpr>(E))
4650 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004651 }
4652
4653 return QualType();
4654}
4655
Peter Collingbournee9200682011-05-13 03:29:01 +00004656bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004657 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004658
4659 {
4660 // The operand of __builtin_object_size is never evaluated for side-effects.
4661 // If there are any, but we can determine the pointed-to object anyway, then
4662 // ignore the side-effects.
4663 SpeculativeEvaluationRAII SpeculativeEval(Info);
4664 if (!EvaluatePointer(E->getArg(0), Base, Info))
4665 return false;
4666 }
John McCall95007602010-05-10 23:27:23 +00004667
4668 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004669 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004670
Richard Smithce40ad62011-11-12 22:28:03 +00004671 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004672 if (T.isNull() ||
4673 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004674 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004675 T->isVariablyModifiedType() ||
4676 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004677 return Error(E);
John McCall95007602010-05-10 23:27:23 +00004678
4679 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4680 CharUnits Offset = Base.getLValueOffset();
4681
4682 if (!Offset.isNegative() && Offset <= Size)
4683 Size -= Offset;
4684 else
4685 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00004686 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00004687}
4688
Peter Collingbournee9200682011-05-13 03:29:01 +00004689bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00004690 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004691 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00004692 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004693
4694 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00004695 if (TryEvaluateBuiltinObjectSize(E))
4696 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00004697
Richard Smith0421ce72012-08-07 04:16:51 +00004698 // If evaluating the argument has side-effects, we can't determine the size
4699 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4700 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004701 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00004702 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00004703 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00004704 return Success(0, E);
4705 }
Mike Stump876387b2009-10-27 22:09:17 +00004706
Richard Smith01ade172012-05-23 04:13:20 +00004707 // Expression had no side effects, but we couldn't statically determine the
4708 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004709 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004710 }
4711
Benjamin Kramera801f4a2012-10-06 14:42:22 +00004712 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00004713 case Builtin::BI__builtin_bswap32:
4714 case Builtin::BI__builtin_bswap64: {
4715 APSInt Val;
4716 if (!EvaluateInteger(E->getArg(0), Val, Info))
4717 return false;
4718
4719 return Success(Val.byteSwap(), E);
4720 }
4721
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004722 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004723 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00004724
Richard Smith5fab0c92011-12-28 19:48:30 +00004725 case Builtin::BI__builtin_constant_p:
4726 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00004727
Chris Lattnerd545ad12009-09-23 06:06:36 +00004728 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00004729 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00004730 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00004731 return Success(Operand, E);
4732 }
Eli Friedmand5c93992010-02-13 00:10:10 +00004733
4734 case Builtin::BI__builtin_expect:
4735 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00004736
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004737 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00004738 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004739 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00004740 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00004741 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4742 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00004743 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00004744 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004745 case Builtin::BI__builtin_strlen:
4746 // As an extension, we support strlen() and __builtin_strlen() as constant
4747 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00004748 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004749 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4750 // The string literal may have embedded null characters. Find the first
4751 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004752 StringRef Str = S->getString();
4753 StringRef::size_type Pos = Str.find(0);
4754 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004755 Str = Str.substr(0, Pos);
4756
4757 return Success(Str.size(), E);
4758 }
4759
Richard Smithf57d8cb2011-12-09 22:58:01 +00004760 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004761
Richard Smith01ba47d2012-04-13 00:45:38 +00004762 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00004763 case Builtin::BI__atomic_is_lock_free:
4764 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00004765 APSInt SizeVal;
4766 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4767 return false;
4768
4769 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4770 // of two less than the maximum inline atomic width, we know it is
4771 // lock-free. If the size isn't a power of two, or greater than the
4772 // maximum alignment where we promote atomics, we know it is not lock-free
4773 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4774 // the answer can only be determined at runtime; for example, 16-byte
4775 // atomics have lock-free implementations on some, but not all,
4776 // x86-64 processors.
4777
4778 // Check power-of-two.
4779 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00004780 if (Size.isPowerOfTwo()) {
4781 // Check against inlining width.
4782 unsigned InlineWidthBits =
4783 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4784 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4785 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4786 Size == CharUnits::One() ||
4787 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4788 Expr::NPC_NeverValueDependent))
4789 // OK, we will inline appropriately-aligned operations of this size,
4790 // and _Atomic(T) is appropriately-aligned.
4791 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004792
Richard Smith01ba47d2012-04-13 00:45:38 +00004793 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4794 castAs<PointerType>()->getPointeeType();
4795 if (!PointeeType->isIncompleteType() &&
4796 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4797 // OK, we will inline operations on this object.
4798 return Success(1, E);
4799 }
4800 }
4801 }
Eli Friedmana4c26022011-10-17 21:44:23 +00004802
Richard Smith01ba47d2012-04-13 00:45:38 +00004803 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4804 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004805 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004806 }
Chris Lattner7174bf32008-07-12 00:38:25 +00004807}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004808
Richard Smith8b3497e2011-10-31 01:37:14 +00004809static bool HasSameBase(const LValue &A, const LValue &B) {
4810 if (!A.getLValueBase())
4811 return !B.getLValueBase();
4812 if (!B.getLValueBase())
4813 return false;
4814
Richard Smithce40ad62011-11-12 22:28:03 +00004815 if (A.getLValueBase().getOpaqueValue() !=
4816 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004817 const Decl *ADecl = GetLValueBaseDecl(A);
4818 if (!ADecl)
4819 return false;
4820 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00004821 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00004822 return false;
4823 }
4824
4825 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00004826 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00004827}
4828
Richard Smithc8042322012-02-01 05:53:12 +00004829/// Perform the given integer operation, which is known to need at most BitWidth
4830/// bits, and check for overflow in the original type (if that type was not an
4831/// unsigned type).
4832template<typename Operation>
4833static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4834 const APSInt &LHS, const APSInt &RHS,
4835 unsigned BitWidth, Operation Op) {
4836 if (LHS.isUnsigned())
4837 return Op(LHS, RHS);
4838
4839 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4840 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00004841 if (Result.extend(BitWidth) != Value) {
4842 if (Info.getIntOverflowCheckMode())
4843 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4844 diag::warn_integer_constant_overflow)
4845 << Result.toString(10) << E->getType();
4846 else
4847 HandleOverflow(Info, E, Value, E->getType());
4848 }
Richard Smithc8042322012-02-01 05:53:12 +00004849 return Result;
4850}
4851
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004852namespace {
Richard Smith11562c52011-10-28 17:51:58 +00004853
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004854/// \brief Data recursive integer evaluator of certain binary operators.
4855///
4856/// We use a data recursive algorithm for binary operators so that we are able
4857/// to handle extreme cases of chained binary operators without causing stack
4858/// overflow.
4859class DataRecursiveIntBinOpEvaluator {
4860 struct EvalResult {
4861 APValue Val;
4862 bool Failed;
4863
4864 EvalResult() : Failed(false) { }
4865
4866 void swap(EvalResult &RHS) {
4867 Val.swap(RHS.Val);
4868 Failed = RHS.Failed;
4869 RHS.Failed = false;
4870 }
4871 };
4872
4873 struct Job {
4874 const Expr *E;
4875 EvalResult LHSResult; // meaningful only for binary operator expression.
4876 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4877
4878 Job() : StoredInfo(0) { }
4879 void startSpeculativeEval(EvalInfo &Info) {
4880 OldEvalStatus = Info.EvalStatus;
4881 Info.EvalStatus.Diag = 0;
4882 StoredInfo = &Info;
4883 }
4884 ~Job() {
4885 if (StoredInfo) {
4886 StoredInfo->EvalStatus = OldEvalStatus;
4887 }
4888 }
4889 private:
4890 EvalInfo *StoredInfo; // non-null if status changed.
4891 Expr::EvalStatus OldEvalStatus;
4892 };
4893
4894 SmallVector<Job, 16> Queue;
4895
4896 IntExprEvaluator &IntEval;
4897 EvalInfo &Info;
4898 APValue &FinalResult;
4899
4900public:
4901 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4902 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4903
4904 /// \brief True if \param E is a binary operator that we are going to handle
4905 /// data recursively.
4906 /// We handle binary operators that are comma, logical, or that have operands
4907 /// with integral or enumeration type.
4908 static bool shouldEnqueue(const BinaryOperator *E) {
4909 return E->getOpcode() == BO_Comma ||
4910 E->isLogicalOp() ||
4911 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4912 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00004913 }
4914
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004915 bool Traverse(const BinaryOperator *E) {
4916 enqueue(E);
4917 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00004918 while (!Queue.empty())
4919 process(PrevResult);
4920
4921 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004922
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004923 FinalResult.swap(PrevResult.Val);
4924 return true;
4925 }
4926
4927private:
4928 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4929 return IntEval.Success(Value, E, Result);
4930 }
4931 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4932 return IntEval.Success(Value, E, Result);
4933 }
4934 bool Error(const Expr *E) {
4935 return IntEval.Error(E);
4936 }
4937 bool Error(const Expr *E, diag::kind D) {
4938 return IntEval.Error(E, D);
4939 }
4940
4941 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4942 return Info.CCEDiag(E, D);
4943 }
4944
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004945 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4946 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004947 bool &SuppressRHSDiags);
4948
4949 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4950 const BinaryOperator *E, APValue &Result);
4951
4952 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4953 Result.Failed = !Evaluate(Result.Val, Info, E);
4954 if (Result.Failed)
4955 Result.Val = APValue();
4956 }
4957
Richard Trieuba4d0872012-03-21 23:30:30 +00004958 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004959
4960 void enqueue(const Expr *E) {
4961 E = E->IgnoreParens();
4962 Queue.resize(Queue.size()+1);
4963 Queue.back().E = E;
4964 Queue.back().Kind = Job::AnyExprKind;
4965 }
4966};
4967
4968}
4969
4970bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004971 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004972 bool &SuppressRHSDiags) {
4973 if (E->getOpcode() == BO_Comma) {
4974 // Ignore LHS but note if we could not evaluate it.
4975 if (LHSResult.Failed)
4976 Info.EvalStatus.HasSideEffects = true;
4977 return true;
4978 }
4979
4980 if (E->isLogicalOp()) {
4981 bool lhsResult;
4982 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004983 // We were able to evaluate the LHS, see if we can get away with not
4984 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004985 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004986 Success(lhsResult, E, LHSResult.Val);
4987 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004988 }
4989 } else {
4990 // Since we weren't able to evaluate the left hand side, it
4991 // must have had side effects.
4992 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004993
4994 // We can't evaluate the LHS; however, sometimes the result
4995 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4996 // Don't ignore RHS and suppress diagnostics from this arm.
4997 SuppressRHSDiags = true;
4998 }
4999
5000 return true;
5001 }
5002
5003 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5004 E->getRHS()->getType()->isIntegralOrEnumerationType());
5005
5006 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005007 return false; // Ignore RHS;
5008
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005009 return true;
5010}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005011
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005012bool DataRecursiveIntBinOpEvaluator::
5013 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5014 const BinaryOperator *E, APValue &Result) {
5015 if (E->getOpcode() == BO_Comma) {
5016 if (RHSResult.Failed)
5017 return false;
5018 Result = RHSResult.Val;
5019 return true;
5020 }
5021
5022 if (E->isLogicalOp()) {
5023 bool lhsResult, rhsResult;
5024 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5025 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5026
5027 if (LHSIsOK) {
5028 if (RHSIsOK) {
5029 if (E->getOpcode() == BO_LOr)
5030 return Success(lhsResult || rhsResult, E, Result);
5031 else
5032 return Success(lhsResult && rhsResult, E, Result);
5033 }
5034 } else {
5035 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005036 // We can't evaluate the LHS; however, sometimes the result
5037 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5038 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005039 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005040 }
5041 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005042
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005043 return false;
5044 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005045
5046 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5047 E->getRHS()->getType()->isIntegralOrEnumerationType());
5048
5049 if (LHSResult.Failed || RHSResult.Failed)
5050 return false;
5051
5052 const APValue &LHSVal = LHSResult.Val;
5053 const APValue &RHSVal = RHSResult.Val;
5054
5055 // Handle cases like (unsigned long)&a + 4.
5056 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5057 Result = LHSVal;
5058 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5059 RHSVal.getInt().getZExtValue());
5060 if (E->getOpcode() == BO_Add)
5061 Result.getLValueOffset() += AdditionalOffset;
5062 else
5063 Result.getLValueOffset() -= AdditionalOffset;
5064 return true;
5065 }
5066
5067 // Handle cases like 4 + (unsigned long)&a
5068 if (E->getOpcode() == BO_Add &&
5069 RHSVal.isLValue() && LHSVal.isInt()) {
5070 Result = RHSVal;
5071 Result.getLValueOffset() += CharUnits::fromQuantity(
5072 LHSVal.getInt().getZExtValue());
5073 return true;
5074 }
5075
5076 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5077 // Handle (intptr_t)&&A - (intptr_t)&&B.
5078 if (!LHSVal.getLValueOffset().isZero() ||
5079 !RHSVal.getLValueOffset().isZero())
5080 return false;
5081 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5082 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5083 if (!LHSExpr || !RHSExpr)
5084 return false;
5085 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5086 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5087 if (!LHSAddrExpr || !RHSAddrExpr)
5088 return false;
5089 // Make sure both labels come from the same function.
5090 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5091 RHSAddrExpr->getLabel()->getDeclContext())
5092 return false;
5093 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5094 return true;
5095 }
5096
5097 // All the following cases expect both operands to be an integer
5098 if (!LHSVal.isInt() || !RHSVal.isInt())
5099 return Error(E);
5100
5101 const APSInt &LHS = LHSVal.getInt();
5102 APSInt RHS = RHSVal.getInt();
5103
5104 switch (E->getOpcode()) {
5105 default:
5106 return Error(E);
5107 case BO_Mul:
5108 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5109 LHS.getBitWidth() * 2,
5110 std::multiplies<APSInt>()), E,
5111 Result);
5112 case BO_Add:
5113 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5114 LHS.getBitWidth() + 1,
5115 std::plus<APSInt>()), E, Result);
5116 case BO_Sub:
5117 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5118 LHS.getBitWidth() + 1,
5119 std::minus<APSInt>()), E, Result);
5120 case BO_And: return Success(LHS & RHS, E, Result);
5121 case BO_Xor: return Success(LHS ^ RHS, E, Result);
5122 case BO_Or: return Success(LHS | RHS, E, Result);
5123 case BO_Div:
5124 case BO_Rem:
5125 if (RHS == 0)
5126 return Error(E, diag::note_expr_divide_by_zero);
5127 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
5128 // not actually undefined behavior in C++11 due to a language defect.
5129 if (RHS.isNegative() && RHS.isAllOnesValue() &&
5130 LHS.isSigned() && LHS.isMinSignedValue())
5131 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
5132 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
5133 Result);
5134 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00005135 if (Info.getLangOpts().OpenCL)
5136 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005137 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005138 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5139 RHS.isUnsigned());
5140 else if (RHS.isSigned() && RHS.isNegative()) {
5141 // During constant-folding, a negative shift is an opposite shift. Such
5142 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005143 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5144 RHS = -RHS;
5145 goto shift_right;
5146 }
5147
5148 shift_left:
5149 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
5150 // the shifted type.
5151 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5152 if (SA != RHS) {
5153 CCEDiag(E, diag::note_constexpr_large_shift)
5154 << RHS << E->getType() << LHS.getBitWidth();
5155 } else if (LHS.isSigned()) {
5156 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
5157 // operand, and must not overflow the corresponding unsigned type.
5158 if (LHS.isNegative())
5159 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
5160 else if (LHS.countLeadingZeros() < SA)
5161 CCEDiag(E, diag::note_constexpr_lshift_discards);
5162 }
5163
5164 return Success(LHS << SA, E, Result);
5165 }
5166 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00005167 if (Info.getLangOpts().OpenCL)
5168 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005169 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005170 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5171 RHS.isUnsigned());
5172 else if (RHS.isSigned() && RHS.isNegative()) {
5173 // During constant-folding, a negative shift is an opposite shift. Such a
5174 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005175 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5176 RHS = -RHS;
5177 goto shift_left;
5178 }
5179
5180 shift_right:
5181 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
5182 // shifted type.
5183 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5184 if (SA != RHS)
5185 CCEDiag(E, diag::note_constexpr_large_shift)
5186 << RHS << E->getType() << LHS.getBitWidth();
5187
5188 return Success(LHS >> SA, E, Result);
5189 }
5190
5191 case BO_LT: return Success(LHS < RHS, E, Result);
5192 case BO_GT: return Success(LHS > RHS, E, Result);
5193 case BO_LE: return Success(LHS <= RHS, E, Result);
5194 case BO_GE: return Success(LHS >= RHS, E, Result);
5195 case BO_EQ: return Success(LHS == RHS, E, Result);
5196 case BO_NE: return Success(LHS != RHS, E, Result);
5197 }
5198}
5199
Richard Trieuba4d0872012-03-21 23:30:30 +00005200void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005201 Job &job = Queue.back();
5202
5203 switch (job.Kind) {
5204 case Job::AnyExprKind: {
5205 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5206 if (shouldEnqueue(Bop)) {
5207 job.Kind = Job::BinOpKind;
5208 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005209 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005210 }
5211 }
5212
5213 EvaluateExpr(job.E, Result);
5214 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005215 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005216 }
5217
5218 case Job::BinOpKind: {
5219 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005220 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005221 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005222 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005223 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005224 }
5225 if (SuppressRHSDiags)
5226 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005227 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005228 job.Kind = Job::BinOpVisitedLHSKind;
5229 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005230 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005231 }
5232
5233 case Job::BinOpVisitedLHSKind: {
5234 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5235 EvalResult RHS;
5236 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005237 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005238 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005239 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005240 }
5241 }
5242
5243 llvm_unreachable("Invalid Job::Kind!");
5244}
5245
5246bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5247 if (E->isAssignmentOp())
5248 return Error(E);
5249
5250 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5251 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005252
Anders Carlssonacc79812008-11-16 07:17:21 +00005253 QualType LHSTy = E->getLHS()->getType();
5254 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005255
5256 if (LHSTy->isAnyComplexType()) {
5257 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005258 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005259
Richard Smith253c2a32012-01-27 01:14:48 +00005260 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5261 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005262 return false;
5263
Richard Smith253c2a32012-01-27 01:14:48 +00005264 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005265 return false;
5266
5267 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005268 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005269 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005270 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005271 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5272
John McCalle3027922010-08-25 11:45:40 +00005273 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005274 return Success((CR_r == APFloat::cmpEqual &&
5275 CR_i == APFloat::cmpEqual), E);
5276 else {
John McCalle3027922010-08-25 11:45:40 +00005277 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005278 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005279 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005280 CR_r == APFloat::cmpLessThan ||
5281 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005282 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005283 CR_i == APFloat::cmpLessThan ||
5284 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005285 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005286 } else {
John McCalle3027922010-08-25 11:45:40 +00005287 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005288 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5289 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5290 else {
John McCalle3027922010-08-25 11:45:40 +00005291 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005292 "Invalid compex comparison.");
5293 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5294 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5295 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005296 }
5297 }
Mike Stump11289f42009-09-09 15:08:12 +00005298
Anders Carlssonacc79812008-11-16 07:17:21 +00005299 if (LHSTy->isRealFloatingType() &&
5300 RHSTy->isRealFloatingType()) {
5301 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005302
Richard Smith253c2a32012-01-27 01:14:48 +00005303 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5304 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005305 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005306
Richard Smith253c2a32012-01-27 01:14:48 +00005307 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005308 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005309
Anders Carlssonacc79812008-11-16 07:17:21 +00005310 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005311
Anders Carlssonacc79812008-11-16 07:17:21 +00005312 switch (E->getOpcode()) {
5313 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005314 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005315 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005316 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005317 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005318 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005319 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005320 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005321 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005322 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005323 E);
John McCalle3027922010-08-25 11:45:40 +00005324 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005325 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005326 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005327 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005328 || CR == APFloat::cmpLessThan
5329 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005330 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005331 }
Mike Stump11289f42009-09-09 15:08:12 +00005332
Eli Friedmana38da572009-04-28 19:17:36 +00005333 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005334 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005335 LValue LHSValue, RHSValue;
5336
5337 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5338 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005339 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005340
Richard Smith253c2a32012-01-27 01:14:48 +00005341 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005342 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005343
Richard Smith8b3497e2011-10-31 01:37:14 +00005344 // Reject differing bases from the normal codepath; we special-case
5345 // comparisons to null.
5346 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005347 if (E->getOpcode() == BO_Sub) {
5348 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005349 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5350 return false;
5351 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005352 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005353 if (!LHSExpr || !RHSExpr)
5354 return false;
5355 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5356 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5357 if (!LHSAddrExpr || !RHSAddrExpr)
5358 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005359 // Make sure both labels come from the same function.
5360 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5361 RHSAddrExpr->getLabel()->getDeclContext())
5362 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005363 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005364 return true;
5365 }
Richard Smith83c68212011-10-31 05:11:32 +00005366 // Inequalities and subtractions between unrelated pointers have
5367 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005368 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005369 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005370 // A constant address may compare equal to the address of a symbol.
5371 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005372 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005373 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5374 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005375 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005376 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005377 // distinct addresses. In clang, the result of such a comparison is
5378 // unspecified, so it is not a constant expression. However, we do know
5379 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005380 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5381 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005382 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005383 // We can't tell whether weak symbols will end up pointing to the same
5384 // object.
5385 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005386 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005387 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005388 // (Note that clang defaults to -fmerge-all-constants, which can
5389 // lead to inconsistent results for comparisons involving the address
5390 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005391 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005392 }
Eli Friedman64004332009-03-23 04:38:34 +00005393
Richard Smith1b470412012-02-01 08:10:20 +00005394 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5395 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5396
Richard Smith84f6dcf2012-02-02 01:16:57 +00005397 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5398 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5399
John McCalle3027922010-08-25 11:45:40 +00005400 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005401 // C++11 [expr.add]p6:
5402 // Unless both pointers point to elements of the same array object, or
5403 // one past the last element of the array object, the behavior is
5404 // undefined.
5405 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5406 !AreElementsOfSameArray(getType(LHSValue.Base),
5407 LHSDesignator, RHSDesignator))
5408 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5409
Chris Lattner882bdf22010-04-20 17:13:14 +00005410 QualType Type = E->getLHS()->getType();
5411 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005412
Richard Smithd62306a2011-11-10 06:34:14 +00005413 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005414 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005415 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005416
Richard Smith1b470412012-02-01 08:10:20 +00005417 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5418 // and produce incorrect results when it overflows. Such behavior
5419 // appears to be non-conforming, but is common, so perhaps we should
5420 // assume the standard intended for such cases to be undefined behavior
5421 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005422
Richard Smith1b470412012-02-01 08:10:20 +00005423 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5424 // overflow in the final conversion to ptrdiff_t.
5425 APSInt LHS(
5426 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5427 APSInt RHS(
5428 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5429 APSInt ElemSize(
5430 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5431 APSInt TrueResult = (LHS - RHS) / ElemSize;
5432 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5433
5434 if (Result.extend(65) != TrueResult)
5435 HandleOverflow(Info, E, TrueResult, E->getType());
5436 return Success(Result, E);
5437 }
Richard Smithde21b242012-01-31 06:41:30 +00005438
5439 // C++11 [expr.rel]p3:
5440 // Pointers to void (after pointer conversions) can be compared, with a
5441 // result defined as follows: If both pointers represent the same
5442 // address or are both the null pointer value, the result is true if the
5443 // operator is <= or >= and false otherwise; otherwise the result is
5444 // unspecified.
5445 // We interpret this as applying to pointers to *cv* void.
5446 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005447 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005448 CCEDiag(E, diag::note_constexpr_void_comparison);
5449
Richard Smith84f6dcf2012-02-02 01:16:57 +00005450 // C++11 [expr.rel]p2:
5451 // - If two pointers point to non-static data members of the same object,
5452 // or to subobjects or array elements fo such members, recursively, the
5453 // pointer to the later declared member compares greater provided the
5454 // two members have the same access control and provided their class is
5455 // not a union.
5456 // [...]
5457 // - Otherwise pointer comparisons are unspecified.
5458 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5459 E->isRelationalOp()) {
5460 bool WasArrayIndex;
5461 unsigned Mismatch =
5462 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5463 RHSDesignator, WasArrayIndex);
5464 // At the point where the designators diverge, the comparison has a
5465 // specified value if:
5466 // - we are comparing array indices
5467 // - we are comparing fields of a union, or fields with the same access
5468 // Otherwise, the result is unspecified and thus the comparison is not a
5469 // constant expression.
5470 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5471 Mismatch < RHSDesignator.Entries.size()) {
5472 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5473 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5474 if (!LF && !RF)
5475 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5476 else if (!LF)
5477 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5478 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5479 << RF->getParent() << RF;
5480 else if (!RF)
5481 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5482 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5483 << LF->getParent() << LF;
5484 else if (!LF->getParent()->isUnion() &&
5485 LF->getAccess() != RF->getAccess())
5486 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5487 << LF << LF->getAccess() << RF << RF->getAccess()
5488 << LF->getParent();
5489 }
5490 }
5491
Eli Friedman6c31cb42012-04-16 04:30:08 +00005492 // The comparison here must be unsigned, and performed with the same
5493 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005494 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5495 uint64_t CompareLHS = LHSOffset.getQuantity();
5496 uint64_t CompareRHS = RHSOffset.getQuantity();
5497 assert(PtrSize <= 64 && "Unexpected pointer width");
5498 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5499 CompareLHS &= Mask;
5500 CompareRHS &= Mask;
5501
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005502 // If there is a base and this is a relational operator, we can only
5503 // compare pointers within the object in question; otherwise, the result
5504 // depends on where the object is located in memory.
5505 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5506 QualType BaseTy = getType(LHSValue.Base);
5507 if (BaseTy->isIncompleteType())
5508 return Error(E);
5509 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5510 uint64_t OffsetLimit = Size.getQuantity();
5511 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5512 return Error(E);
5513 }
5514
Richard Smith8b3497e2011-10-31 01:37:14 +00005515 switch (E->getOpcode()) {
5516 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005517 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5518 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5519 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5520 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5521 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5522 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005523 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005524 }
5525 }
Richard Smith7bb00672012-02-01 01:42:44 +00005526
5527 if (LHSTy->isMemberPointerType()) {
5528 assert(E->isEqualityOp() && "unexpected member pointer operation");
5529 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5530
5531 MemberPtr LHSValue, RHSValue;
5532
5533 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5534 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5535 return false;
5536
5537 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5538 return false;
5539
5540 // C++11 [expr.eq]p2:
5541 // If both operands are null, they compare equal. Otherwise if only one is
5542 // null, they compare unequal.
5543 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5544 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5545 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5546 }
5547
5548 // Otherwise if either is a pointer to a virtual member function, the
5549 // result is unspecified.
5550 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5551 if (MD->isVirtual())
5552 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5553 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5554 if (MD->isVirtual())
5555 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5556
5557 // Otherwise they compare equal if and only if they would refer to the
5558 // same member of the same most derived object or the same subobject if
5559 // they were dereferenced with a hypothetical object of the associated
5560 // class type.
5561 bool Equal = LHSValue == RHSValue;
5562 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5563 }
5564
Richard Smithab44d9b2012-02-14 22:35:28 +00005565 if (LHSTy->isNullPtrType()) {
5566 assert(E->isComparisonOp() && "unexpected nullptr operation");
5567 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5568 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5569 // are compared, the result is true of the operator is <=, >= or ==, and
5570 // false otherwise.
5571 BinaryOperator::Opcode Opcode = E->getOpcode();
5572 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5573 }
5574
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005575 assert((!LHSTy->isIntegralOrEnumerationType() ||
5576 !RHSTy->isIntegralOrEnumerationType()) &&
5577 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5578 // We can't continue from here for non-integral types.
5579 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005580}
5581
Ken Dyck160146e2010-01-27 17:10:57 +00005582CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005583 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5584 // result shall be the alignment of the referenced type."
5585 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5586 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005587
5588 // __alignof is defined to return the preferred alignment.
5589 return Info.Ctx.toCharUnitsFromBits(
5590 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005591}
5592
Ken Dyck160146e2010-01-27 17:10:57 +00005593CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005594 E = E->IgnoreParens();
5595
5596 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005597 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005598 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005599 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5600 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005601
Chris Lattner68061312009-01-24 21:53:27 +00005602 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005603 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5604 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005605
Chris Lattner24aeeab2009-01-24 21:09:06 +00005606 return GetAlignOfType(E->getType());
5607}
5608
5609
Peter Collingbournee190dee2011-03-11 19:24:49 +00005610/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5611/// a result as the expression's type.
5612bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5613 const UnaryExprOrTypeTraitExpr *E) {
5614 switch(E->getKind()) {
5615 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005616 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005617 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005618 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005619 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005620 }
Eli Friedman64004332009-03-23 04:38:34 +00005621
Peter Collingbournee190dee2011-03-11 19:24:49 +00005622 case UETT_VecStep: {
5623 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005624
Peter Collingbournee190dee2011-03-11 19:24:49 +00005625 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005626 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005627
Peter Collingbournee190dee2011-03-11 19:24:49 +00005628 // The vec_step built-in functions that take a 3-component
5629 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5630 if (n == 3)
5631 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005632
Peter Collingbournee190dee2011-03-11 19:24:49 +00005633 return Success(n, E);
5634 } else
5635 return Success(1, E);
5636 }
5637
5638 case UETT_SizeOf: {
5639 QualType SrcTy = E->getTypeOfArgument();
5640 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5641 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005642 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5643 SrcTy = Ref->getPointeeType();
5644
Richard Smithd62306a2011-11-10 06:34:14 +00005645 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005646 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005647 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005648 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005649 }
5650 }
5651
5652 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005653}
5654
Peter Collingbournee9200682011-05-13 03:29:01 +00005655bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005656 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005657 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005658 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005659 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005660 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005661 for (unsigned i = 0; i != n; ++i) {
5662 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5663 switch (ON.getKind()) {
5664 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005665 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005666 APSInt IdxResult;
5667 if (!EvaluateInteger(Idx, IdxResult, Info))
5668 return false;
5669 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5670 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005671 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005672 CurrentType = AT->getElementType();
5673 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5674 Result += IdxResult.getSExtValue() * ElementSize;
5675 break;
5676 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005677
Douglas Gregor882211c2010-04-28 22:16:22 +00005678 case OffsetOfExpr::OffsetOfNode::Field: {
5679 FieldDecl *MemberDecl = ON.getField();
5680 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005681 if (!RT)
5682 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005683 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005684 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00005685 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00005686 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00005687 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00005688 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00005689 CurrentType = MemberDecl->getType().getNonReferenceType();
5690 break;
5691 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005692
Douglas Gregor882211c2010-04-28 22:16:22 +00005693 case OffsetOfExpr::OffsetOfNode::Identifier:
5694 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005695
Douglas Gregord1702062010-04-29 00:18:15 +00005696 case OffsetOfExpr::OffsetOfNode::Base: {
5697 CXXBaseSpecifier *BaseSpec = ON.getBase();
5698 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005699 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005700
5701 // Find the layout of the class whose base we are looking into.
5702 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005703 if (!RT)
5704 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005705 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005706 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00005707 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5708
5709 // Find the base class itself.
5710 CurrentType = BaseSpec->getType();
5711 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5712 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005713 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005714
5715 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00005716 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00005717 break;
5718 }
Douglas Gregor882211c2010-04-28 22:16:22 +00005719 }
5720 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005721 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005722}
5723
Chris Lattnere13042c2008-07-11 19:10:17 +00005724bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005725 switch (E->getOpcode()) {
5726 default:
5727 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5728 // See C99 6.6p3.
5729 return Error(E);
5730 case UO_Extension:
5731 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5732 // If so, we could clear the diagnostic ID.
5733 return Visit(E->getSubExpr());
5734 case UO_Plus:
5735 // The result is just the value.
5736 return Visit(E->getSubExpr());
5737 case UO_Minus: {
5738 if (!Visit(E->getSubExpr()))
5739 return false;
5740 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00005741 const APSInt &Value = Result.getInt();
5742 if (Value.isSigned() && Value.isMinSignedValue())
5743 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5744 E->getType());
5745 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005746 }
5747 case UO_Not: {
5748 if (!Visit(E->getSubExpr()))
5749 return false;
5750 if (!Result.isInt()) return Error(E);
5751 return Success(~Result.getInt(), E);
5752 }
5753 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00005754 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00005755 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00005756 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005757 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005758 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005759 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005760}
Mike Stump11289f42009-09-09 15:08:12 +00005761
Chris Lattner477c4be2008-07-12 01:15:53 +00005762/// HandleCast - This is used to evaluate implicit or explicit casts where the
5763/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00005764bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5765 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005766 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00005767 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005768
Eli Friedmanc757de22011-03-25 00:43:55 +00005769 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00005770 case CK_BaseToDerived:
5771 case CK_DerivedToBase:
5772 case CK_UncheckedDerivedToBase:
5773 case CK_Dynamic:
5774 case CK_ToUnion:
5775 case CK_ArrayToPointerDecay:
5776 case CK_FunctionToPointerDecay:
5777 case CK_NullToPointer:
5778 case CK_NullToMemberPointer:
5779 case CK_BaseToDerivedMemberPointer:
5780 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00005781 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00005782 case CK_ConstructorConversion:
5783 case CK_IntegralToPointer:
5784 case CK_ToVoid:
5785 case CK_VectorSplat:
5786 case CK_IntegralToFloating:
5787 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005788 case CK_CPointerToObjCPointerCast:
5789 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005790 case CK_AnyPointerToBlockPointerCast:
5791 case CK_ObjCObjectLValueCast:
5792 case CK_FloatingRealToComplex:
5793 case CK_FloatingComplexToReal:
5794 case CK_FloatingComplexCast:
5795 case CK_FloatingComplexToIntegralComplex:
5796 case CK_IntegralRealToComplex:
5797 case CK_IntegralComplexCast:
5798 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00005799 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005800 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005801 llvm_unreachable("invalid cast kind for integral value");
5802
Eli Friedman9faf2f92011-03-25 19:07:11 +00005803 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005804 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005805 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00005806 case CK_ARCProduceObject:
5807 case CK_ARCConsumeObject:
5808 case CK_ARCReclaimReturnedObject:
5809 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00005810 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005811 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005812
Richard Smith4ef685b2012-01-17 21:17:26 +00005813 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00005814 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00005815 case CK_AtomicToNonAtomic:
5816 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00005817 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00005818 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005819
5820 case CK_MemberPointerToBoolean:
5821 case CK_PointerToBoolean:
5822 case CK_IntegralToBoolean:
5823 case CK_FloatingToBoolean:
5824 case CK_FloatingComplexToBoolean:
5825 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005826 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00005827 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00005828 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005829 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005830 }
5831
Eli Friedmanc757de22011-03-25 00:43:55 +00005832 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00005833 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00005834 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00005835
Eli Friedman742421e2009-02-20 01:15:07 +00005836 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005837 // Allow casts of address-of-label differences if they are no-ops
5838 // or narrowing. (The narrowing case isn't actually guaranteed to
5839 // be constant-evaluatable except in some narrow cases which are hard
5840 // to detect here. We let it through on the assumption the user knows
5841 // what they are doing.)
5842 if (Result.isAddrLabelDiff())
5843 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00005844 // Only allow casts of lvalues if they are lossless.
5845 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5846 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005847
Richard Smith911e1422012-01-30 22:27:01 +00005848 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5849 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00005850 }
Mike Stump11289f42009-09-09 15:08:12 +00005851
Eli Friedmanc757de22011-03-25 00:43:55 +00005852 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005853 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5854
John McCall45d55e42010-05-07 21:00:08 +00005855 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00005856 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00005857 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00005858
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005859 if (LV.getLValueBase()) {
5860 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00005861 // FIXME: Allow a larger integer size than the pointer size, and allow
5862 // narrowing back down to pointer width in subsequent integral casts.
5863 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005864 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005865 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005866
Richard Smithcf74da72011-11-16 07:18:12 +00005867 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005868 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005869 return true;
5870 }
5871
Ken Dyck02990832010-01-15 12:37:54 +00005872 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5873 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00005874 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005875 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005876
Eli Friedmanc757de22011-03-25 00:43:55 +00005877 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00005878 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005879 if (!EvaluateComplex(SubExpr, C, Info))
5880 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00005881 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005882 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00005883
Eli Friedmanc757de22011-03-25 00:43:55 +00005884 case CK_FloatingToIntegral: {
5885 APFloat F(0.0);
5886 if (!EvaluateFloat(SubExpr, F, Info))
5887 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00005888
Richard Smith357362d2011-12-13 06:39:58 +00005889 APSInt Value;
5890 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5891 return false;
5892 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005893 }
5894 }
Mike Stump11289f42009-09-09 15:08:12 +00005895
Eli Friedmanc757de22011-03-25 00:43:55 +00005896 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00005897}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005898
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005899bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5900 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005901 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005902 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5903 return false;
5904 if (!LV.isComplexInt())
5905 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005906 return Success(LV.getComplexIntReal(), E);
5907 }
5908
5909 return Visit(E->getSubExpr());
5910}
5911
Eli Friedman4e7a2412009-02-27 04:45:43 +00005912bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005913 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005914 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005915 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5916 return false;
5917 if (!LV.isComplexInt())
5918 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005919 return Success(LV.getComplexIntImag(), E);
5920 }
5921
Richard Smith4a678122011-10-24 18:44:57 +00005922 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00005923 return Success(0, E);
5924}
5925
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005926bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5927 return Success(E->getPackLength(), E);
5928}
5929
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005930bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5931 return Success(E->getValue(), E);
5932}
5933
Chris Lattner05706e882008-07-11 18:11:29 +00005934//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00005935// Float Evaluation
5936//===----------------------------------------------------------------------===//
5937
5938namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005939class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005940 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00005941 APFloat &Result;
5942public:
5943 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005944 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00005945
Richard Smith2e312c82012-03-03 22:46:17 +00005946 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005947 Result = V.getFloat();
5948 return true;
5949 }
Eli Friedman24c01542008-08-22 00:06:13 +00005950
Richard Smithfddd3842011-12-30 21:15:51 +00005951 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00005952 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5953 return true;
5954 }
5955
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005956 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005957
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005958 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005959 bool VisitBinaryOperator(const BinaryOperator *E);
5960 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005961 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00005962
John McCallb1fb0d32010-05-07 22:08:54 +00005963 bool VisitUnaryReal(const UnaryOperator *E);
5964 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00005965
Richard Smithfddd3842011-12-30 21:15:51 +00005966 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00005967};
5968} // end anonymous namespace
5969
5970static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005971 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005972 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00005973}
5974
Jay Foad39c79802011-01-12 09:06:06 +00005975static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00005976 QualType ResultTy,
5977 const Expr *Arg,
5978 bool SNaN,
5979 llvm::APFloat &Result) {
5980 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5981 if (!S) return false;
5982
5983 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5984
5985 llvm::APInt fill;
5986
5987 // Treat empty strings as if they were zero.
5988 if (S->getString().empty())
5989 fill = llvm::APInt(32, 0);
5990 else if (S->getString().getAsInteger(0, fill))
5991 return false;
5992
5993 if (SNaN)
5994 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5995 else
5996 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5997 return true;
5998}
5999
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006000bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006001 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006002 default:
6003 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6004
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006005 case Builtin::BI__builtin_huge_val:
6006 case Builtin::BI__builtin_huge_valf:
6007 case Builtin::BI__builtin_huge_vall:
6008 case Builtin::BI__builtin_inf:
6009 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006010 case Builtin::BI__builtin_infl: {
6011 const llvm::fltSemantics &Sem =
6012 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006013 Result = llvm::APFloat::getInf(Sem);
6014 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006015 }
Mike Stump11289f42009-09-09 15:08:12 +00006016
John McCall16291492010-02-28 13:00:19 +00006017 case Builtin::BI__builtin_nans:
6018 case Builtin::BI__builtin_nansf:
6019 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006020 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6021 true, Result))
6022 return Error(E);
6023 return true;
John McCall16291492010-02-28 13:00:19 +00006024
Chris Lattner0b7282e2008-10-06 06:31:58 +00006025 case Builtin::BI__builtin_nan:
6026 case Builtin::BI__builtin_nanf:
6027 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006028 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006029 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006030 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6031 false, Result))
6032 return Error(E);
6033 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006034
6035 case Builtin::BI__builtin_fabs:
6036 case Builtin::BI__builtin_fabsf:
6037 case Builtin::BI__builtin_fabsl:
6038 if (!EvaluateFloat(E->getArg(0), Result, Info))
6039 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006040
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006041 if (Result.isNegative())
6042 Result.changeSign();
6043 return true;
6044
Mike Stump11289f42009-09-09 15:08:12 +00006045 case Builtin::BI__builtin_copysign:
6046 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006047 case Builtin::BI__builtin_copysignl: {
6048 APFloat RHS(0.);
6049 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6050 !EvaluateFloat(E->getArg(1), RHS, Info))
6051 return false;
6052 Result.copySign(RHS);
6053 return true;
6054 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006055 }
6056}
6057
John McCallb1fb0d32010-05-07 22:08:54 +00006058bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006059 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6060 ComplexValue CV;
6061 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6062 return false;
6063 Result = CV.FloatReal;
6064 return true;
6065 }
6066
6067 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006068}
6069
6070bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006071 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6072 ComplexValue CV;
6073 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6074 return false;
6075 Result = CV.FloatImag;
6076 return true;
6077 }
6078
Richard Smith4a678122011-10-24 18:44:57 +00006079 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006080 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6081 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006082 return true;
6083}
6084
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006085bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006086 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006087 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006088 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006089 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006090 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006091 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6092 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006093 Result.changeSign();
6094 return true;
6095 }
6096}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006097
Eli Friedman24c01542008-08-22 00:06:13 +00006098bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006099 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6100 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006101
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006102 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006103 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6104 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006105 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006106 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00006107 return false;
6108
6109 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006110 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006111 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00006112 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006113 break;
John McCalle3027922010-08-25 11:45:40 +00006114 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00006115 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006116 break;
John McCalle3027922010-08-25 11:45:40 +00006117 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00006118 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006119 break;
John McCalle3027922010-08-25 11:45:40 +00006120 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00006121 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006122 break;
Eli Friedman24c01542008-08-22 00:06:13 +00006123 }
Richard Smithc8042322012-02-01 05:53:12 +00006124
6125 if (Result.isInfinity() || Result.isNaN())
6126 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
6127 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00006128}
6129
6130bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6131 Result = E->getValue();
6132 return true;
6133}
6134
Peter Collingbournee9200682011-05-13 03:29:01 +00006135bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6136 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006137
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006138 switch (E->getCastKind()) {
6139 default:
Richard Smith11562c52011-10-28 17:51:58 +00006140 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006141
6142 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006143 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006144 return EvaluateInteger(SubExpr, IntResult, Info) &&
6145 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6146 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006147 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006148
6149 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006150 if (!Visit(SubExpr))
6151 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006152 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6153 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006154 }
John McCalld7646252010-11-14 08:17:51 +00006155
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006156 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006157 ComplexValue V;
6158 if (!EvaluateComplex(SubExpr, V, Info))
6159 return false;
6160 Result = V.getComplexFloatReal();
6161 return true;
6162 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006163 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006164}
6165
Eli Friedman24c01542008-08-22 00:06:13 +00006166//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006167// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006168//===----------------------------------------------------------------------===//
6169
6170namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006171class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006172 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006173 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006174
Anders Carlsson537969c2008-11-16 20:27:53 +00006175public:
John McCall93d91dc2010-05-07 17:22:02 +00006176 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006177 : ExprEvaluatorBaseTy(info), Result(Result) {}
6178
Richard Smith2e312c82012-03-03 22:46:17 +00006179 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006180 Result.setFrom(V);
6181 return true;
6182 }
Mike Stump11289f42009-09-09 15:08:12 +00006183
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006184 bool ZeroInitialization(const Expr *E);
6185
Anders Carlsson537969c2008-11-16 20:27:53 +00006186 //===--------------------------------------------------------------------===//
6187 // Visitor Methods
6188 //===--------------------------------------------------------------------===//
6189
Peter Collingbournee9200682011-05-13 03:29:01 +00006190 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006191 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006192 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006193 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006194 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006195};
6196} // end anonymous namespace
6197
John McCall93d91dc2010-05-07 17:22:02 +00006198static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6199 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006200 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006201 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006202}
6203
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006204bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006205 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006206 if (ElemTy->isRealFloatingType()) {
6207 Result.makeComplexFloat();
6208 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6209 Result.FloatReal = Zero;
6210 Result.FloatImag = Zero;
6211 } else {
6212 Result.makeComplexInt();
6213 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6214 Result.IntReal = Zero;
6215 Result.IntImag = Zero;
6216 }
6217 return true;
6218}
6219
Peter Collingbournee9200682011-05-13 03:29:01 +00006220bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6221 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006222
6223 if (SubExpr->getType()->isRealFloatingType()) {
6224 Result.makeComplexFloat();
6225 APFloat &Imag = Result.FloatImag;
6226 if (!EvaluateFloat(SubExpr, Imag, Info))
6227 return false;
6228
6229 Result.FloatReal = APFloat(Imag.getSemantics());
6230 return true;
6231 } else {
6232 assert(SubExpr->getType()->isIntegerType() &&
6233 "Unexpected imaginary literal.");
6234
6235 Result.makeComplexInt();
6236 APSInt &Imag = Result.IntImag;
6237 if (!EvaluateInteger(SubExpr, Imag, Info))
6238 return false;
6239
6240 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6241 return true;
6242 }
6243}
6244
Peter Collingbournee9200682011-05-13 03:29:01 +00006245bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006246
John McCallfcef3cf2010-12-14 17:51:41 +00006247 switch (E->getCastKind()) {
6248 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006249 case CK_BaseToDerived:
6250 case CK_DerivedToBase:
6251 case CK_UncheckedDerivedToBase:
6252 case CK_Dynamic:
6253 case CK_ToUnion:
6254 case CK_ArrayToPointerDecay:
6255 case CK_FunctionToPointerDecay:
6256 case CK_NullToPointer:
6257 case CK_NullToMemberPointer:
6258 case CK_BaseToDerivedMemberPointer:
6259 case CK_DerivedToBaseMemberPointer:
6260 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006261 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006262 case CK_ConstructorConversion:
6263 case CK_IntegralToPointer:
6264 case CK_PointerToIntegral:
6265 case CK_PointerToBoolean:
6266 case CK_ToVoid:
6267 case CK_VectorSplat:
6268 case CK_IntegralCast:
6269 case CK_IntegralToBoolean:
6270 case CK_IntegralToFloating:
6271 case CK_FloatingToIntegral:
6272 case CK_FloatingToBoolean:
6273 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006274 case CK_CPointerToObjCPointerCast:
6275 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006276 case CK_AnyPointerToBlockPointerCast:
6277 case CK_ObjCObjectLValueCast:
6278 case CK_FloatingComplexToReal:
6279 case CK_FloatingComplexToBoolean:
6280 case CK_IntegralComplexToReal:
6281 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006282 case CK_ARCProduceObject:
6283 case CK_ARCConsumeObject:
6284 case CK_ARCReclaimReturnedObject:
6285 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006286 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006287 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006288 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006289 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006290
John McCallfcef3cf2010-12-14 17:51:41 +00006291 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006292 case CK_AtomicToNonAtomic:
6293 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006294 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006295 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006296
6297 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006298 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006299 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006300 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006301
6302 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006303 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006304 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006305 return false;
6306
John McCallfcef3cf2010-12-14 17:51:41 +00006307 Result.makeComplexFloat();
6308 Result.FloatImag = APFloat(Real.getSemantics());
6309 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006310 }
6311
John McCallfcef3cf2010-12-14 17:51:41 +00006312 case CK_FloatingComplexCast: {
6313 if (!Visit(E->getSubExpr()))
6314 return false;
6315
6316 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6317 QualType From
6318 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6319
Richard Smith357362d2011-12-13 06:39:58 +00006320 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6321 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006322 }
6323
6324 case CK_FloatingComplexToIntegralComplex: {
6325 if (!Visit(E->getSubExpr()))
6326 return false;
6327
6328 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6329 QualType From
6330 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6331 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006332 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6333 To, Result.IntReal) &&
6334 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6335 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006336 }
6337
6338 case CK_IntegralRealToComplex: {
6339 APSInt &Real = Result.IntReal;
6340 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6341 return false;
6342
6343 Result.makeComplexInt();
6344 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6345 return true;
6346 }
6347
6348 case CK_IntegralComplexCast: {
6349 if (!Visit(E->getSubExpr()))
6350 return false;
6351
6352 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6353 QualType From
6354 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6355
Richard Smith911e1422012-01-30 22:27:01 +00006356 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6357 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006358 return true;
6359 }
6360
6361 case CK_IntegralComplexToFloatingComplex: {
6362 if (!Visit(E->getSubExpr()))
6363 return false;
6364
Ted Kremenek28831752012-08-23 20:46:57 +00006365 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006366 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006367 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006368 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006369 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6370 To, Result.FloatReal) &&
6371 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6372 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006373 }
6374 }
6375
6376 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006377}
6378
John McCall93d91dc2010-05-07 17:22:02 +00006379bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006380 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006381 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6382
Richard Smith253c2a32012-01-27 01:14:48 +00006383 bool LHSOK = Visit(E->getLHS());
6384 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006385 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006386
John McCall93d91dc2010-05-07 17:22:02 +00006387 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006388 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006389 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006390
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006391 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6392 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006393 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006394 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006395 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006396 if (Result.isComplexFloat()) {
6397 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6398 APFloat::rmNearestTiesToEven);
6399 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6400 APFloat::rmNearestTiesToEven);
6401 } else {
6402 Result.getComplexIntReal() += RHS.getComplexIntReal();
6403 Result.getComplexIntImag() += RHS.getComplexIntImag();
6404 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006405 break;
John McCalle3027922010-08-25 11:45:40 +00006406 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006407 if (Result.isComplexFloat()) {
6408 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6409 APFloat::rmNearestTiesToEven);
6410 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6411 APFloat::rmNearestTiesToEven);
6412 } else {
6413 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6414 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6415 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006416 break;
John McCalle3027922010-08-25 11:45:40 +00006417 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006418 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006419 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006420 APFloat &LHS_r = LHS.getComplexFloatReal();
6421 APFloat &LHS_i = LHS.getComplexFloatImag();
6422 APFloat &RHS_r = RHS.getComplexFloatReal();
6423 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006424
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006425 APFloat Tmp = LHS_r;
6426 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6427 Result.getComplexFloatReal() = Tmp;
6428 Tmp = LHS_i;
6429 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6430 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6431
6432 Tmp = LHS_r;
6433 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6434 Result.getComplexFloatImag() = Tmp;
6435 Tmp = LHS_i;
6436 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6437 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6438 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006439 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006440 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006441 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6442 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006443 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006444 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6445 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6446 }
6447 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006448 case BO_Div:
6449 if (Result.isComplexFloat()) {
6450 ComplexValue LHS = Result;
6451 APFloat &LHS_r = LHS.getComplexFloatReal();
6452 APFloat &LHS_i = LHS.getComplexFloatImag();
6453 APFloat &RHS_r = RHS.getComplexFloatReal();
6454 APFloat &RHS_i = RHS.getComplexFloatImag();
6455 APFloat &Res_r = Result.getComplexFloatReal();
6456 APFloat &Res_i = Result.getComplexFloatImag();
6457
6458 APFloat Den = RHS_r;
6459 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6460 APFloat Tmp = RHS_i;
6461 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6462 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6463
6464 Res_r = LHS_r;
6465 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6466 Tmp = LHS_i;
6467 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6468 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6469 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6470
6471 Res_i = LHS_i;
6472 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6473 Tmp = LHS_r;
6474 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6475 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6476 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6477 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006478 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6479 return Error(E, diag::note_expr_divide_by_zero);
6480
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006481 ComplexValue LHS = Result;
6482 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6483 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6484 Result.getComplexIntReal() =
6485 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6486 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6487 Result.getComplexIntImag() =
6488 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6489 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6490 }
6491 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006492 }
6493
John McCall93d91dc2010-05-07 17:22:02 +00006494 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006495}
6496
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006497bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6498 // Get the operand value into 'Result'.
6499 if (!Visit(E->getSubExpr()))
6500 return false;
6501
6502 switch (E->getOpcode()) {
6503 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006504 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006505 case UO_Extension:
6506 return true;
6507 case UO_Plus:
6508 // The result is always just the subexpr.
6509 return true;
6510 case UO_Minus:
6511 if (Result.isComplexFloat()) {
6512 Result.getComplexFloatReal().changeSign();
6513 Result.getComplexFloatImag().changeSign();
6514 }
6515 else {
6516 Result.getComplexIntReal() = -Result.getComplexIntReal();
6517 Result.getComplexIntImag() = -Result.getComplexIntImag();
6518 }
6519 return true;
6520 case UO_Not:
6521 if (Result.isComplexFloat())
6522 Result.getComplexFloatImag().changeSign();
6523 else
6524 Result.getComplexIntImag() = -Result.getComplexIntImag();
6525 return true;
6526 }
6527}
6528
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006529bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6530 if (E->getNumInits() == 2) {
6531 if (E->getType()->isComplexType()) {
6532 Result.makeComplexFloat();
6533 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6534 return false;
6535 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6536 return false;
6537 } else {
6538 Result.makeComplexInt();
6539 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6540 return false;
6541 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6542 return false;
6543 }
6544 return true;
6545 }
6546 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6547}
6548
Anders Carlsson537969c2008-11-16 20:27:53 +00006549//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006550// Void expression evaluation, primarily for a cast to void on the LHS of a
6551// comma operator
6552//===----------------------------------------------------------------------===//
6553
6554namespace {
6555class VoidExprEvaluator
6556 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6557public:
6558 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6559
Richard Smith2e312c82012-03-03 22:46:17 +00006560 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006561
6562 bool VisitCastExpr(const CastExpr *E) {
6563 switch (E->getCastKind()) {
6564 default:
6565 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6566 case CK_ToVoid:
6567 VisitIgnoredValue(E->getSubExpr());
6568 return true;
6569 }
6570 }
6571};
6572} // end anonymous namespace
6573
6574static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6575 assert(E->isRValue() && E->getType()->isVoidType());
6576 return VoidExprEvaluator(Info).Visit(E);
6577}
6578
6579//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006580// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006581//===----------------------------------------------------------------------===//
6582
Richard Smith2e312c82012-03-03 22:46:17 +00006583static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006584 // In C, function designators are not lvalues, but we evaluate them as if they
6585 // are.
6586 if (E->isGLValue() || E->getType()->isFunctionType()) {
6587 LValue LV;
6588 if (!EvaluateLValue(E, LV, Info))
6589 return false;
6590 LV.moveInto(Result);
6591 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006592 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006593 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006594 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006595 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006596 return false;
John McCall45d55e42010-05-07 21:00:08 +00006597 } else if (E->getType()->hasPointerRepresentation()) {
6598 LValue LV;
6599 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006600 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006601 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006602 } else if (E->getType()->isRealFloatingType()) {
6603 llvm::APFloat F(0.0);
6604 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006605 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006606 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006607 } else if (E->getType()->isAnyComplexType()) {
6608 ComplexValue C;
6609 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006610 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006611 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006612 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006613 MemberPtr P;
6614 if (!EvaluateMemberPointer(E, P, Info))
6615 return false;
6616 P.moveInto(Result);
6617 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006618 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006619 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006620 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006621 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006622 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006623 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006624 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006625 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006626 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006627 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6628 return false;
6629 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006630 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006631 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006632 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006633 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006634 if (!EvaluateVoid(E, Info))
6635 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006636 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006637 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006638 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006639 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006640 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006641 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006642 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006643
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006644 return true;
6645}
6646
Richard Smithb228a862012-02-15 02:18:13 +00006647/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6648/// cases, the in-place evaluation is essential, since later initializers for
6649/// an object can indirectly refer to subobjects which were initialized earlier.
6650static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6651 const Expr *E, CheckConstantExpressionKind CCEK,
6652 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006653 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006654 return false;
6655
6656 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006657 // Evaluate arrays and record types in-place, so that later initializers can
6658 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006659 if (E->getType()->isArrayType())
6660 return EvaluateArray(E, This, Result, Info);
6661 else if (E->getType()->isRecordType())
6662 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006663 }
6664
6665 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006666 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006667}
6668
Richard Smithf57d8cb2011-12-09 22:58:01 +00006669/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6670/// lvalue-to-rvalue cast if it is an lvalue.
6671static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006672 if (!CheckLiteralType(Info, E))
6673 return false;
6674
Richard Smith2e312c82012-03-03 22:46:17 +00006675 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006676 return false;
6677
6678 if (E->isGLValue()) {
6679 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00006680 LV.setFrom(Info.Ctx, Result);
6681 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006682 return false;
6683 }
6684
Richard Smith2e312c82012-03-03 22:46:17 +00006685 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00006686 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006687}
Richard Smith11562c52011-10-28 17:51:58 +00006688
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006689static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6690 const ASTContext &Ctx, bool &IsConst) {
6691 // Fast-path evaluations of integer literals, since we sometimes see files
6692 // containing vast quantities of these.
6693 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6694 Result.Val = APValue(APSInt(L->getValue(),
6695 L->getType()->isUnsignedIntegerType()));
6696 IsConst = true;
6697 return true;
6698 }
6699
6700 // FIXME: Evaluating values of large array and record types can cause
6701 // performance problems. Only do so in C++11 for now.
6702 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6703 Exp->getType()->isRecordType()) &&
6704 !Ctx.getLangOpts().CPlusPlus11) {
6705 IsConst = false;
6706 return true;
6707 }
6708 return false;
6709}
6710
6711
Richard Smith7b553f12011-10-29 00:50:52 +00006712/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00006713/// any crazy technique (that has nothing to do with language standards) that
6714/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00006715/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6716/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00006717bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006718 bool IsConst;
6719 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
6720 return IsConst;
6721
Richard Smithf57d8cb2011-12-09 22:58:01 +00006722 EvalInfo Info(Ctx, Result);
6723 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00006724}
6725
Jay Foad39c79802011-01-12 09:06:06 +00006726bool Expr::EvaluateAsBooleanCondition(bool &Result,
6727 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00006728 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00006729 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00006730 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00006731}
6732
Richard Smith5fab0c92011-12-28 19:48:30 +00006733bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6734 SideEffectsKind AllowSideEffects) const {
6735 if (!getType()->isIntegralOrEnumerationType())
6736 return false;
6737
Richard Smith11562c52011-10-28 17:51:58 +00006738 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00006739 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6740 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00006741 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006742
Richard Smith11562c52011-10-28 17:51:58 +00006743 Result = ExprResult.Val.getInt();
6744 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00006745}
6746
Jay Foad39c79802011-01-12 09:06:06 +00006747bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00006748 EvalInfo Info(Ctx, Result);
6749
John McCall45d55e42010-05-07 21:00:08 +00006750 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006751 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6752 !CheckLValueConstantExpression(Info, getExprLoc(),
6753 Ctx.getLValueReferenceType(getType()), LV))
6754 return false;
6755
Richard Smith2e312c82012-03-03 22:46:17 +00006756 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00006757 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00006758}
6759
Richard Smithd0b4dd62011-12-19 06:19:21 +00006760bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6761 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006762 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00006763 // FIXME: Evaluating initializers for large array and record types can cause
6764 // performance problems. Only do so in C++11 for now.
6765 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006766 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00006767 return false;
6768
Richard Smithd0b4dd62011-12-19 06:19:21 +00006769 Expr::EvalStatus EStatus;
6770 EStatus.Diag = &Notes;
6771
6772 EvalInfo InitInfo(Ctx, EStatus);
6773 InitInfo.setEvaluatingDecl(VD, Value);
6774
6775 LValue LVal;
6776 LVal.set(VD);
6777
Richard Smithfddd3842011-12-30 21:15:51 +00006778 // C++11 [basic.start.init]p2:
6779 // Variables with static storage duration or thread storage duration shall be
6780 // zero-initialized before any other initialization takes place.
6781 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006782 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00006783 !VD->getType()->isReferenceType()) {
6784 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006785 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6786 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00006787 return false;
6788 }
6789
Richard Smithb228a862012-02-15 02:18:13 +00006790 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6791 /*AllowNonLiteralTypes=*/true) ||
6792 EStatus.HasSideEffects)
6793 return false;
6794
6795 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6796 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00006797}
6798
Richard Smith7b553f12011-10-29 00:50:52 +00006799/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6800/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00006801bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00006802 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00006803 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00006804}
Anders Carlsson59689ed2008-11-22 21:04:56 +00006805
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006806APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006807 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006808 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006809 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00006810 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006811 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00006812 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006813 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00006814
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006815 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00006816}
John McCall864e3962010-05-07 05:32:02 +00006817
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006818void Expr::EvaluateForOverflow(const ASTContext &Ctx,
6819 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
6820 bool IsConst;
6821 EvalResult EvalResult;
6822 EvalResult.Diag = Diags;
6823 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
6824 EvalInfo Info(Ctx, EvalResult, true);
6825 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
6826 }
6827}
6828
Abramo Bagnaraf8199452010-05-14 17:07:14 +00006829 bool Expr::EvalResult::isGlobalLValue() const {
6830 assert(Val.isLValue());
6831 return IsGlobalLValue(Val.getLValueBase());
6832 }
6833
6834
John McCall864e3962010-05-07 05:32:02 +00006835/// isIntegerConstantExpr - this recursive routine will test if an expression is
6836/// an integer constant expression.
6837
6838/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6839/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00006840
6841// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00006842// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6843// and a (possibly null) SourceLocation indicating the location of the problem.
6844//
John McCall864e3962010-05-07 05:32:02 +00006845// Note that to reduce code duplication, this helper does no evaluation
6846// itself; the caller checks whether the expression is evaluatable, and
6847// in the rare cases where CheckICE actually cares about the evaluated
6848// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00006849
Dan Gohman28ade552010-07-26 21:25:24 +00006850namespace {
6851
Richard Smith9e575da2012-12-28 13:25:52 +00006852enum ICEKind {
6853 /// This expression is an ICE.
6854 IK_ICE,
6855 /// This expression is not an ICE, but if it isn't evaluated, it's
6856 /// a legal subexpression for an ICE. This return value is used to handle
6857 /// the comma operator in C99 mode, and non-constant subexpressions.
6858 IK_ICEIfUnevaluated,
6859 /// This expression is not an ICE, and is not a legal subexpression for one.
6860 IK_NotICE
6861};
6862
John McCall864e3962010-05-07 05:32:02 +00006863struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00006864 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00006865 SourceLocation Loc;
6866
Richard Smith9e575da2012-12-28 13:25:52 +00006867 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00006868};
6869
Dan Gohman28ade552010-07-26 21:25:24 +00006870}
6871
Richard Smith9e575da2012-12-28 13:25:52 +00006872static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6873
6874static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00006875
6876static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6877 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00006878 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00006879 !EVResult.Val.isInt())
6880 return ICEDiag(IK_NotICE, E->getLocStart());
6881
John McCall864e3962010-05-07 05:32:02 +00006882 return NoDiag();
6883}
6884
6885static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6886 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00006887 if (!E->getType()->isIntegralOrEnumerationType())
6888 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006889
6890 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00006891#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00006892#define STMT(Node, Base) case Expr::Node##Class:
6893#define EXPR(Node, Base)
6894#include "clang/AST/StmtNodes.inc"
6895 case Expr::PredefinedExprClass:
6896 case Expr::FloatingLiteralClass:
6897 case Expr::ImaginaryLiteralClass:
6898 case Expr::StringLiteralClass:
6899 case Expr::ArraySubscriptExprClass:
6900 case Expr::MemberExprClass:
6901 case Expr::CompoundAssignOperatorClass:
6902 case Expr::CompoundLiteralExprClass:
6903 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00006904 case Expr::DesignatedInitExprClass:
6905 case Expr::ImplicitValueInitExprClass:
6906 case Expr::ParenListExprClass:
6907 case Expr::VAArgExprClass:
6908 case Expr::AddrLabelExprClass:
6909 case Expr::StmtExprClass:
6910 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00006911 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00006912 case Expr::CXXDynamicCastExprClass:
6913 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00006914 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00006915 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006916 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00006917 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006918 case Expr::CXXThisExprClass:
6919 case Expr::CXXThrowExprClass:
6920 case Expr::CXXNewExprClass:
6921 case Expr::CXXDeleteExprClass:
6922 case Expr::CXXPseudoDestructorExprClass:
6923 case Expr::UnresolvedLookupExprClass:
6924 case Expr::DependentScopeDeclRefExprClass:
6925 case Expr::CXXConstructExprClass:
6926 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00006927 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00006928 case Expr::CXXTemporaryObjectExprClass:
6929 case Expr::CXXUnresolvedConstructExprClass:
6930 case Expr::CXXDependentScopeMemberExprClass:
6931 case Expr::UnresolvedMemberExprClass:
6932 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00006933 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006934 case Expr::ObjCArrayLiteralClass:
6935 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006936 case Expr::ObjCEncodeExprClass:
6937 case Expr::ObjCMessageExprClass:
6938 case Expr::ObjCSelectorExprClass:
6939 case Expr::ObjCProtocolExprClass:
6940 case Expr::ObjCIvarRefExprClass:
6941 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006942 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006943 case Expr::ObjCIsaExprClass:
6944 case Expr::ShuffleVectorExprClass:
6945 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00006946 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00006947 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00006948 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00006949 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00006950 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00006951 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00006952 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00006953 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00006954 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00006955 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00006956 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00006957 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00006958 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00006959
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006960 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00006961 case Expr::GNUNullExprClass:
6962 // GCC considers the GNU __null value to be an integral constant expression.
6963 return NoDiag();
6964
John McCall7c454bb2011-07-15 05:09:51 +00006965 case Expr::SubstNonTypeTemplateParmExprClass:
6966 return
6967 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6968
John McCall864e3962010-05-07 05:32:02 +00006969 case Expr::ParenExprClass:
6970 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00006971 case Expr::GenericSelectionExprClass:
6972 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006973 case Expr::IntegerLiteralClass:
6974 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006975 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00006976 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00006977 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00006978 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00006979 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00006980 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00006981 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00006982 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006983 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00006984 return NoDiag();
6985 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00006986 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00006987 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6988 // constant expressions, but they can never be ICEs because an ICE cannot
6989 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00006990 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006991 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00006992 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006993 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006994 }
Richard Smith6365c912012-02-24 22:12:32 +00006995 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006996 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6997 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00006998 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006999 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007000 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007001 // Parameter variables are never constants. Without this check,
7002 // getAnyInitializer() can find a default argument, which leads
7003 // to chaos.
7004 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007005 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007006
7007 // C++ 7.1.5.1p2
7008 // A variable of non-volatile const-qualified integral or enumeration
7009 // type initialized by an ICE can be used in ICEs.
7010 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007011 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007012 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007013
Richard Smithd0b4dd62011-12-19 06:19:21 +00007014 const VarDecl *VD;
7015 // Look for a declaration of this variable that has an initializer, and
7016 // check whether it is an ICE.
7017 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7018 return NoDiag();
7019 else
Richard Smith9e575da2012-12-28 13:25:52 +00007020 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007021 }
7022 }
Richard Smith9e575da2012-12-28 13:25:52 +00007023 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007024 }
John McCall864e3962010-05-07 05:32:02 +00007025 case Expr::UnaryOperatorClass: {
7026 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7027 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007028 case UO_PostInc:
7029 case UO_PostDec:
7030 case UO_PreInc:
7031 case UO_PreDec:
7032 case UO_AddrOf:
7033 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007034 // C99 6.6/3 allows increment and decrement within unevaluated
7035 // subexpressions of constant expressions, but they can never be ICEs
7036 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007037 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007038 case UO_Extension:
7039 case UO_LNot:
7040 case UO_Plus:
7041 case UO_Minus:
7042 case UO_Not:
7043 case UO_Real:
7044 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007045 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007046 }
Richard Smith9e575da2012-12-28 13:25:52 +00007047
John McCall864e3962010-05-07 05:32:02 +00007048 // OffsetOf falls through here.
7049 }
7050 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007051 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7052 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7053 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7054 // compliance: we should warn earlier for offsetof expressions with
7055 // array subscripts that aren't ICEs, and if the array subscripts
7056 // are ICEs, the value of the offsetof must be an integer constant.
7057 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007058 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007059 case Expr::UnaryExprOrTypeTraitExprClass: {
7060 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7061 if ((Exp->getKind() == UETT_SizeOf) &&
7062 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007063 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007064 return NoDiag();
7065 }
7066 case Expr::BinaryOperatorClass: {
7067 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7068 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007069 case BO_PtrMemD:
7070 case BO_PtrMemI:
7071 case BO_Assign:
7072 case BO_MulAssign:
7073 case BO_DivAssign:
7074 case BO_RemAssign:
7075 case BO_AddAssign:
7076 case BO_SubAssign:
7077 case BO_ShlAssign:
7078 case BO_ShrAssign:
7079 case BO_AndAssign:
7080 case BO_XorAssign:
7081 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007082 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7083 // constant expressions, but they can never be ICEs because an ICE cannot
7084 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007085 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007086
John McCalle3027922010-08-25 11:45:40 +00007087 case BO_Mul:
7088 case BO_Div:
7089 case BO_Rem:
7090 case BO_Add:
7091 case BO_Sub:
7092 case BO_Shl:
7093 case BO_Shr:
7094 case BO_LT:
7095 case BO_GT:
7096 case BO_LE:
7097 case BO_GE:
7098 case BO_EQ:
7099 case BO_NE:
7100 case BO_And:
7101 case BO_Xor:
7102 case BO_Or:
7103 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007104 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7105 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007106 if (Exp->getOpcode() == BO_Div ||
7107 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007108 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007109 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007110 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007111 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007112 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007113 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007114 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007115 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007116 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007117 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007118 }
7119 }
7120 }
John McCalle3027922010-08-25 11:45:40 +00007121 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007122 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007123 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7124 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007125 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7126 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007127 } else {
7128 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007129 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007130 }
7131 }
Richard Smith9e575da2012-12-28 13:25:52 +00007132 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007133 }
John McCalle3027922010-08-25 11:45:40 +00007134 case BO_LAnd:
7135 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007136 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7137 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007138 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007139 // Rare case where the RHS has a comma "side-effect"; we need
7140 // to actually check the condition to see whether the side
7141 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007142 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007143 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007144 return RHSResult;
7145 return NoDiag();
7146 }
7147
Richard Smith9e575da2012-12-28 13:25:52 +00007148 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007149 }
7150 }
7151 }
7152 case Expr::ImplicitCastExprClass:
7153 case Expr::CStyleCastExprClass:
7154 case Expr::CXXFunctionalCastExprClass:
7155 case Expr::CXXStaticCastExprClass:
7156 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007157 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007158 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007159 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007160 if (isa<ExplicitCastExpr>(E)) {
7161 if (const FloatingLiteral *FL
7162 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7163 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7164 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7165 APSInt IgnoredVal(DestWidth, !DestSigned);
7166 bool Ignored;
7167 // If the value does not fit in the destination type, the behavior is
7168 // undefined, so we are not required to treat it as a constant
7169 // expression.
7170 if (FL->getValue().convertToInteger(IgnoredVal,
7171 llvm::APFloat::rmTowardZero,
7172 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007173 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007174 return NoDiag();
7175 }
7176 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007177 switch (cast<CastExpr>(E)->getCastKind()) {
7178 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007179 case CK_AtomicToNonAtomic:
7180 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007181 case CK_NoOp:
7182 case CK_IntegralToBoolean:
7183 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007184 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007185 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007186 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007187 }
John McCall864e3962010-05-07 05:32:02 +00007188 }
John McCallc07a0c72011-02-17 10:25:35 +00007189 case Expr::BinaryConditionalOperatorClass: {
7190 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7191 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007192 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007193 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007194 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7195 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7196 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007197 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007198 return FalseResult;
7199 }
John McCall864e3962010-05-07 05:32:02 +00007200 case Expr::ConditionalOperatorClass: {
7201 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7202 // If the condition (ignoring parens) is a __builtin_constant_p call,
7203 // then only the true side is actually considered in an integer constant
7204 // expression, and it is fully evaluated. This is an important GNU
7205 // extension. See GCC PR38377 for discussion.
7206 if (const CallExpr *CallCE
7207 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007208 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7209 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007210 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007211 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007212 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007213
Richard Smithf57d8cb2011-12-09 22:58:01 +00007214 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7215 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007216
Richard Smith9e575da2012-12-28 13:25:52 +00007217 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007218 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007219 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007220 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007221 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007222 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007223 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007224 return NoDiag();
7225 // Rare case where the diagnostics depend on which side is evaluated
7226 // Note that if we get here, CondResult is 0, and at least one of
7227 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007228 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007229 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007230 return TrueResult;
7231 }
7232 case Expr::CXXDefaultArgExprClass:
7233 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007234 case Expr::CXXDefaultInitExprClass:
7235 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007236 case Expr::ChooseExprClass: {
7237 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7238 }
7239 }
7240
David Blaikiee4d798f2012-01-20 21:50:17 +00007241 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007242}
7243
Richard Smithf57d8cb2011-12-09 22:58:01 +00007244/// Evaluate an expression as a C++11 integral constant expression.
7245static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7246 const Expr *E,
7247 llvm::APSInt *Value,
7248 SourceLocation *Loc) {
7249 if (!E->getType()->isIntegralOrEnumerationType()) {
7250 if (Loc) *Loc = E->getExprLoc();
7251 return false;
7252 }
7253
Richard Smith66e05fe2012-01-18 05:21:49 +00007254 APValue Result;
7255 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007256 return false;
7257
Richard Smith66e05fe2012-01-18 05:21:49 +00007258 assert(Result.isInt() && "pointer cast to int is not an ICE");
7259 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007260 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007261}
7262
Richard Smith92b1ce02011-12-12 09:28:41 +00007263bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007264 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007265 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7266
Richard Smith9e575da2012-12-28 13:25:52 +00007267 ICEDiag D = CheckICE(this, Ctx);
7268 if (D.Kind != IK_ICE) {
7269 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007270 return false;
7271 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007272 return true;
7273}
7274
7275bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7276 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007277 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007278 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7279
7280 if (!isIntegerConstantExpr(Ctx, Loc))
7281 return false;
7282 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007283 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007284 return true;
7285}
Richard Smith66e05fe2012-01-18 05:21:49 +00007286
Richard Smith98a0a492012-02-14 21:38:30 +00007287bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007288 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007289}
7290
Richard Smith66e05fe2012-01-18 05:21:49 +00007291bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7292 SourceLocation *Loc) const {
7293 // We support this checking in C++98 mode in order to diagnose compatibility
7294 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007295 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007296
Richard Smith98a0a492012-02-14 21:38:30 +00007297 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007298 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007299 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007300 Status.Diag = &Diags;
7301 EvalInfo Info(Ctx, Status);
7302
7303 APValue Scratch;
7304 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7305
7306 if (!Diags.empty()) {
7307 IsConstExpr = false;
7308 if (Loc) *Loc = Diags[0].first;
7309 } else if (!IsConstExpr) {
7310 // FIXME: This shouldn't happen.
7311 if (Loc) *Loc = getExprLoc();
7312 }
7313
7314 return IsConstExpr;
7315}
Richard Smith253c2a32012-01-27 01:14:48 +00007316
7317bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007318 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007319 PartialDiagnosticAt> &Diags) {
7320 // FIXME: It would be useful to check constexpr function templates, but at the
7321 // moment the constant expression evaluator cannot cope with the non-rigorous
7322 // ASTs which we build for dependent expressions.
7323 if (FD->isDependentContext())
7324 return true;
7325
7326 Expr::EvalStatus Status;
7327 Status.Diag = &Diags;
7328
7329 EvalInfo Info(FD->getASTContext(), Status);
7330 Info.CheckingPotentialConstantExpression = true;
7331
7332 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7333 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7334
7335 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7336 // is a temporary being used as the 'this' pointer.
7337 LValue This;
7338 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007339 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007340
Richard Smith253c2a32012-01-27 01:14:48 +00007341 ArrayRef<const Expr*> Args;
7342
7343 SourceLocation Loc = FD->getLocation();
7344
Richard Smith2e312c82012-03-03 22:46:17 +00007345 APValue Scratch;
7346 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00007347 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00007348 else
Richard Smith253c2a32012-01-27 01:14:48 +00007349 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7350 Args, FD->getBody(), Info, Scratch);
7351
7352 return Diags.empty();
7353}