blob: 14503f47526d1330e9112db373553a95e2d40019 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smithd62306a2011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000070 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000071 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +000092 }
93
Richard Smitha8105bc2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith80815602011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith80815602011-11-07 05:07:52 +0000122 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000124 }
125
Richard Smitha8105bc2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000130 };
131
Richard Smith96e0c102011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smitha8105bc2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000141
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000152
Richard Smith80815602011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smitha8105bc2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith96e0c102011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith96e0c102011-11-04 02:25:55 +0000229 }
Richard Smith66c96992012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith96e0c102011-11-04 02:25:55 +0000252 return;
253 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000263 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smith254a73d2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000274
Richard Smithf6f003a2011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smithb228a862012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smithd62306a2011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000289 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000290
Eli Friedman4830ec82012-06-25 21:21:08 +0000291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000293 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
296 MapTy Temporaries;
297
Richard Smithf6f003a2011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000300 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000302 };
303
Richard Smith852c9db2013-04-20 22:23:05 +0000304 /// Temporarily override 'this'.
305 class ThisOverrideRAII {
306 public:
307 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
308 : Frame(Frame), OldThis(Frame.This) {
309 if (Enable)
310 Frame.This = NewThis;
311 }
312 ~ThisOverrideRAII() {
313 Frame.This = OldThis;
314 }
315 private:
316 CallStackFrame &Frame;
317 const LValue *OldThis;
318 };
319
Richard Smith92b1ce02011-12-12 09:28:41 +0000320 /// A partial diagnostic which we might know in advance that we are not going
321 /// to emit.
322 class OptionalDiagnostic {
323 PartialDiagnostic *Diag;
324
325 public:
326 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
327
328 template<typename T>
329 OptionalDiagnostic &operator<<(const T &v) {
330 if (Diag)
331 *Diag << v;
332 return *this;
333 }
Richard Smithfe800032012-01-31 04:08:20 +0000334
335 OptionalDiagnostic &operator<<(const APSInt &I) {
336 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000337 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000338 I.toString(Buffer);
339 *Diag << StringRef(Buffer.data(), Buffer.size());
340 }
341 return *this;
342 }
343
344 OptionalDiagnostic &operator<<(const APFloat &F) {
345 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000346 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000347 F.toString(Buffer);
348 *Diag << StringRef(Buffer.data(), Buffer.size());
349 }
350 return *this;
351 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000352 };
353
Richard Smithb228a862012-02-15 02:18:13 +0000354 /// EvalInfo - This is a private struct used by the evaluator to capture
355 /// information about a subexpression as it is folded. It retains information
356 /// about the AST context, but also maintains information about the folded
357 /// expression.
358 ///
359 /// If an expression could be evaluated, it is still possible it is not a C
360 /// "integer constant expression" or constant expression. If not, this struct
361 /// captures information about how and why not.
362 ///
363 /// One bit of information passed *into* the request for constant folding
364 /// indicates whether the subexpression is "evaluated" or not according to C
365 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
366 /// evaluate the expression regardless of what the RHS is, but C only allows
367 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000368 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000369 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000370
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000371 /// EvalStatus - Contains information about the evaluation.
372 Expr::EvalStatus &EvalStatus;
373
374 /// CurrentCall - The top of the constexpr call stack.
375 CallStackFrame *CurrentCall;
376
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000377 /// CallStackDepth - The number of calls in the call stack right now.
378 unsigned CallStackDepth;
379
Richard Smithb228a862012-02-15 02:18:13 +0000380 /// NextCallIndex - The next call index to assign.
381 unsigned NextCallIndex;
382
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000383 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000384 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000385 CallStackFrame BottomFrame;
386
Richard Smithd62306a2011-11-10 06:34:14 +0000387 /// EvaluatingDecl - This is the declaration whose initializer is being
388 /// evaluated, if any.
389 const VarDecl *EvaluatingDecl;
390
391 /// EvaluatingDeclValue - This is the value being constructed for the
392 /// declaration whose initializer is being evaluated, if any.
393 APValue *EvaluatingDeclValue;
394
Richard Smith357362d2011-12-13 06:39:58 +0000395 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
396 /// notes attached to it will also be stored, otherwise they will not be.
397 bool HasActiveDiagnostic;
398
Richard Smith253c2a32012-01-27 01:14:48 +0000399 /// CheckingPotentialConstantExpression - Are we checking whether the
400 /// expression is a potential constant expression? If so, some diagnostics
401 /// are suppressed.
402 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000403
404 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000405
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000406 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
407 bool OverflowCheckMode=false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000408 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000409 CallStackDepth(0), NextCallIndex(1),
410 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith253c2a32012-01-27 01:14:48 +0000411 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000412 CheckingPotentialConstantExpression(false),
413 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000414
Richard Smithd62306a2011-11-10 06:34:14 +0000415 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
416 EvaluatingDecl = VD;
417 EvaluatingDeclValue = &Value;
418 }
419
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000421
Richard Smith357362d2011-12-13 06:39:58 +0000422 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000423 // Don't perform any constexpr calls (other than the call we're checking)
424 // when checking a potential constant expression.
425 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
426 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000427 if (NextCallIndex == 0) {
428 // NextCallIndex has wrapped around.
429 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
430 return false;
431 }
Richard Smith357362d2011-12-13 06:39:58 +0000432 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
433 return true;
434 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
435 << getLangOpts().ConstexprCallDepth;
436 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000437 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000438
Richard Smithb228a862012-02-15 02:18:13 +0000439 CallStackFrame *getCallFrame(unsigned CallIndex) {
440 assert(CallIndex && "no call index in getCallFrame");
441 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
442 // be null in this loop.
443 CallStackFrame *Frame = CurrentCall;
444 while (Frame->Index > CallIndex)
445 Frame = Frame->Caller;
446 return (Frame->Index == CallIndex) ? Frame : 0;
447 }
448
Richard Smith357362d2011-12-13 06:39:58 +0000449 private:
450 /// Add a diagnostic to the diagnostics list.
451 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
452 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
453 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
454 return EvalStatus.Diag->back().second;
455 }
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 /// Add notes containing a call stack to the current point of evaluation.
458 void addCallStack(unsigned Limit);
459
Richard Smith357362d2011-12-13 06:39:58 +0000460 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000461 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000462 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
463 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000464 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000465 // If we have a prior diagnostic, it will be noting that the expression
466 // isn't a constant expression. This diagnostic is more important.
467 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000468 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000469 unsigned CallStackNotes = CallStackDepth - 1;
470 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
471 if (Limit)
472 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000473 if (CheckingPotentialConstantExpression)
474 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000475
Richard Smith357362d2011-12-13 06:39:58 +0000476 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000477 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000478 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
479 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000480 if (!CheckingPotentialConstantExpression)
481 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000482 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 }
Richard Smith357362d2011-12-13 06:39:58 +0000484 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
486 }
487
Richard Smithce1ec5e2012-03-15 04:53:45 +0000488 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
489 = diag::note_invalid_subexpr_in_const_expr,
490 unsigned ExtraNotes = 0) {
491 if (EvalStatus.Diag)
492 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
493 HasActiveDiagnostic = false;
494 return OptionalDiagnostic();
495 }
496
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000497 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
498
Richard Smith92b1ce02011-12-12 09:28:41 +0000499 /// Diagnose that the evaluation does not produce a C++11 core constant
500 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000501 template<typename LocArg>
502 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000503 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000504 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000505 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000506 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
507 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000508 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000509 }
Richard Smith357362d2011-12-13 06:39:58 +0000510 return Diag(Loc, DiagId, ExtraNotes);
511 }
512
513 /// Add a note to a prior diagnostic.
514 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
515 if (!HasActiveDiagnostic)
516 return OptionalDiagnostic();
517 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000518 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000519
520 /// Add a stack of notes to a prior diagnostic.
521 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
522 if (HasActiveDiagnostic) {
523 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
524 Diags.begin(), Diags.end());
525 }
526 }
Richard Smith253c2a32012-01-27 01:14:48 +0000527
528 /// Should we continue evaluation as much as possible after encountering a
529 /// construct which can't be folded?
530 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000531 // Should return true in IntOverflowCheckMode, so that we check for
532 // overflow even if some subexpressions can't be evaluated as constants.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000533 return IntOverflowCheckMode ||
534 (CheckingPotentialConstantExpression &&
535 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith253c2a32012-01-27 01:14:48 +0000536 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000538
539 /// Object used to treat all foldable expressions as constant expressions.
540 struct FoldConstant {
541 bool Enabled;
542
543 explicit FoldConstant(EvalInfo &Info)
544 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
545 !Info.EvalStatus.HasSideEffects) {
546 }
547 // Treat the value we've computed since this object was created as constant.
548 void Fold(EvalInfo &Info) {
549 if (Enabled && !Info.EvalStatus.Diag->empty() &&
550 !Info.EvalStatus.HasSideEffects)
551 Info.EvalStatus.Diag->clear();
552 }
553 };
Richard Smith17100ba2012-02-16 02:46:34 +0000554
555 /// RAII object used to suppress diagnostics and side-effects from a
556 /// speculative evaluation.
557 class SpeculativeEvaluationRAII {
558 EvalInfo &Info;
559 Expr::EvalStatus Old;
560
561 public:
562 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000563 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000564 : Info(Info), Old(Info.EvalStatus) {
565 Info.EvalStatus.Diag = NewDiag;
566 }
567 ~SpeculativeEvaluationRAII() {
568 Info.EvalStatus = Old;
569 }
570 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000571}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572
Richard Smitha8105bc2012-01-06 16:39:00 +0000573bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
574 CheckSubobjectKind CSK) {
575 if (Invalid)
576 return false;
577 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000578 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000579 << CSK;
580 setInvalid();
581 return false;
582 }
583 return true;
584}
585
586void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
587 const Expr *E, uint64_t N) {
588 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000589 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000590 << static_cast<int>(N) << /*array*/ 0
591 << static_cast<unsigned>(MostDerivedArraySize);
592 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << static_cast<int>(N) << /*non-array*/ 1;
595 setInvalid();
596}
597
Richard Smithf6f003a2011-12-16 19:06:07 +0000598CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
599 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000600 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000601 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000602 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 Info.CurrentCall = this;
604 ++Info.CallStackDepth;
605}
606
607CallStackFrame::~CallStackFrame() {
608 assert(Info.CurrentCall == this && "calls retired out of order");
609 --Info.CallStackDepth;
610 Info.CurrentCall = Caller;
611}
612
613/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000614static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000615 unsigned ArgIndex = 0;
616 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000617 !isa<CXXConstructorDecl>(Frame->Callee) &&
618 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000619
620 if (!IsMemberCall)
621 Out << *Frame->Callee << '(';
622
623 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
624 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000625 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000626 Out << ", ";
627
628 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000629 const APValue &Arg = Frame->Arguments[ArgIndex];
630 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000631
632 if (ArgIndex == 0 && IsMemberCall)
633 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000634 }
635
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 Out << ')';
637}
638
639void EvalInfo::addCallStack(unsigned Limit) {
640 // Determine which calls to skip, if any.
641 unsigned ActiveCalls = CallStackDepth - 1;
642 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
643 if (Limit && Limit < ActiveCalls) {
644 SkipStart = Limit / 2 + Limit % 2;
645 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000646 }
647
Richard Smithf6f003a2011-12-16 19:06:07 +0000648 // Walk the call stack and add the diagnostics.
649 unsigned CallIdx = 0;
650 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
651 Frame = Frame->Caller, ++CallIdx) {
652 // Skip this call?
653 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
654 if (CallIdx == SkipStart) {
655 // Note that we're skipping calls.
656 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
657 << unsigned(ActiveCalls - Limit);
658 }
659 continue;
660 }
661
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000662 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 llvm::raw_svector_ostream Out(Buffer);
664 describeCall(Frame, Out);
665 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
666 }
667}
668
669namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000670 struct ComplexValue {
671 private:
672 bool IsInt;
673
674 public:
675 APSInt IntReal, IntImag;
676 APFloat FloatReal, FloatImag;
677
678 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
679
680 void makeComplexFloat() { IsInt = false; }
681 bool isComplexFloat() const { return !IsInt; }
682 APFloat &getComplexFloatReal() { return FloatReal; }
683 APFloat &getComplexFloatImag() { return FloatImag; }
684
685 void makeComplexInt() { IsInt = true; }
686 bool isComplexInt() const { return IsInt; }
687 APSInt &getComplexIntReal() { return IntReal; }
688 APSInt &getComplexIntImag() { return IntImag; }
689
Richard Smith2e312c82012-03-03 22:46:17 +0000690 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000691 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000692 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000693 else
Richard Smith2e312c82012-03-03 22:46:17 +0000694 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000695 }
Richard Smith2e312c82012-03-03 22:46:17 +0000696 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000697 assert(v.isComplexFloat() || v.isComplexInt());
698 if (v.isComplexFloat()) {
699 makeComplexFloat();
700 FloatReal = v.getComplexFloatReal();
701 FloatImag = v.getComplexFloatImag();
702 } else {
703 makeComplexInt();
704 IntReal = v.getComplexIntReal();
705 IntImag = v.getComplexIntImag();
706 }
707 }
John McCall93d91dc2010-05-07 17:22:02 +0000708 };
John McCall45d55e42010-05-07 21:00:08 +0000709
710 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000711 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000712 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000713 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000714 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000715
Richard Smithce40ad62011-11-12 22:28:03 +0000716 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000717 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000718 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000719 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000720 SubobjectDesignator &getLValueDesignator() { return Designator; }
721 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000722
Richard Smith2e312c82012-03-03 22:46:17 +0000723 void moveInto(APValue &V) const {
724 if (Designator.Invalid)
725 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
726 else
727 V = APValue(Base, Offset, Designator.Entries,
728 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000729 }
Richard Smith2e312c82012-03-03 22:46:17 +0000730 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000731 assert(V.isLValue());
732 Base = V.getLValueBase();
733 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000734 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000735 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000736 }
737
Richard Smithb228a862012-02-15 02:18:13 +0000738 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000739 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000740 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000741 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000742 Designator = SubobjectDesignator(getType(B));
743 }
744
745 // Check that this LValue is not based on a null pointer. If it is, produce
746 // a diagnostic and mark the designator as invalid.
747 bool checkNullPointer(EvalInfo &Info, const Expr *E,
748 CheckSubobjectKind CSK) {
749 if (Designator.Invalid)
750 return false;
751 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000752 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000753 << CSK;
754 Designator.setInvalid();
755 return false;
756 }
757 return true;
758 }
759
760 // Check this LValue refers to an object. If not, set the designator to be
761 // invalid and emit a diagnostic.
762 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000763 // Outside C++11, do not build a designator referring to a subobject of
764 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000765 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000767 return checkNullPointer(Info, E, CSK) &&
768 Designator.checkSubobject(Info, E, CSK);
769 }
770
771 void addDecl(EvalInfo &Info, const Expr *E,
772 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000773 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
774 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000775 }
776 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000777 if (checkSubobject(Info, E, CSK_ArrayToPointer))
778 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000779 }
Richard Smith66c96992012-02-18 22:04:06 +0000780 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
782 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000783 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000784 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000785 if (checkNullPointer(Info, E, CSK_ArrayIndex))
786 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000787 }
John McCall45d55e42010-05-07 21:00:08 +0000788 };
Richard Smith027bf112011-11-17 22:56:20 +0000789
790 struct MemberPtr {
791 MemberPtr() {}
792 explicit MemberPtr(const ValueDecl *Decl) :
793 DeclAndIsDerivedMember(Decl, false), Path() {}
794
795 /// The member or (direct or indirect) field referred to by this member
796 /// pointer, or 0 if this is a null member pointer.
797 const ValueDecl *getDecl() const {
798 return DeclAndIsDerivedMember.getPointer();
799 }
800 /// Is this actually a member of some type derived from the relevant class?
801 bool isDerivedMember() const {
802 return DeclAndIsDerivedMember.getInt();
803 }
804 /// Get the class which the declaration actually lives in.
805 const CXXRecordDecl *getContainingRecord() const {
806 return cast<CXXRecordDecl>(
807 DeclAndIsDerivedMember.getPointer()->getDeclContext());
808 }
809
Richard Smith2e312c82012-03-03 22:46:17 +0000810 void moveInto(APValue &V) const {
811 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000812 }
Richard Smith2e312c82012-03-03 22:46:17 +0000813 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000814 assert(V.isMemberPointer());
815 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
816 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
817 Path.clear();
818 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
819 Path.insert(Path.end(), P.begin(), P.end());
820 }
821
822 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
823 /// whether the member is a member of some class derived from the class type
824 /// of the member pointer.
825 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
826 /// Path - The path of base/derived classes from the member declaration's
827 /// class (exclusive) to the class type of the member pointer (inclusive).
828 SmallVector<const CXXRecordDecl*, 4> Path;
829
830 /// Perform a cast towards the class of the Decl (either up or down the
831 /// hierarchy).
832 bool castBack(const CXXRecordDecl *Class) {
833 assert(!Path.empty());
834 const CXXRecordDecl *Expected;
835 if (Path.size() >= 2)
836 Expected = Path[Path.size() - 2];
837 else
838 Expected = getContainingRecord();
839 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
840 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
841 // if B does not contain the original member and is not a base or
842 // derived class of the class containing the original member, the result
843 // of the cast is undefined.
844 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
845 // (D::*). We consider that to be a language defect.
846 return false;
847 }
848 Path.pop_back();
849 return true;
850 }
851 /// Perform a base-to-derived member pointer cast.
852 bool castToDerived(const CXXRecordDecl *Derived) {
853 if (!getDecl())
854 return true;
855 if (!isDerivedMember()) {
856 Path.push_back(Derived);
857 return true;
858 }
859 if (!castBack(Derived))
860 return false;
861 if (Path.empty())
862 DeclAndIsDerivedMember.setInt(false);
863 return true;
864 }
865 /// Perform a derived-to-base member pointer cast.
866 bool castToBase(const CXXRecordDecl *Base) {
867 if (!getDecl())
868 return true;
869 if (Path.empty())
870 DeclAndIsDerivedMember.setInt(true);
871 if (isDerivedMember()) {
872 Path.push_back(Base);
873 return true;
874 }
875 return castBack(Base);
876 }
877 };
Richard Smith357362d2011-12-13 06:39:58 +0000878
Richard Smith7bb00672012-02-01 01:42:44 +0000879 /// Compare two member pointers, which are assumed to be of the same type.
880 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
881 if (!LHS.getDecl() || !RHS.getDecl())
882 return !LHS.getDecl() && !RHS.getDecl();
883 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
884 return false;
885 return LHS.Path == RHS.Path;
886 }
887
Richard Smith357362d2011-12-13 06:39:58 +0000888 /// Kinds of constant expression checking, for diagnostics.
889 enum CheckConstantExpressionKind {
890 CCEK_Constant, ///< A normal constant.
891 CCEK_ReturnValue, ///< A constexpr function return value.
892 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
893 };
John McCall93d91dc2010-05-07 17:22:02 +0000894}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000895
Richard Smith2e312c82012-03-03 22:46:17 +0000896static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000897static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
898 const LValue &This, const Expr *E,
899 CheckConstantExpressionKind CCEK = CCEK_Constant,
900 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000901static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
902static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000903static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
904 EvalInfo &Info);
905static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000906static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000907static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000908 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000909static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000910static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000911
912//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000913// Misc utilities
914//===----------------------------------------------------------------------===//
915
Richard Smithd9f663b2013-04-22 15:31:51 +0000916/// Evaluate an expression to see if it had side-effects, and discard its
917/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +0000918/// \return \c true if the caller should keep evaluating.
919static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000920 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000921 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000922 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000923 return Info.keepEvaluatingAfterFailure();
924 }
925 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000926}
927
Richard Smithd62306a2011-11-10 06:34:14 +0000928/// Should this call expression be treated as a string literal?
929static bool IsStringLiteralCall(const CallExpr *E) {
930 unsigned Builtin = E->isBuiltinCall();
931 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
932 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
933}
934
Richard Smithce40ad62011-11-12 22:28:03 +0000935static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000936 // C++11 [expr.const]p3 An address constant expression is a prvalue core
937 // constant expression of pointer type that evaluates to...
938
939 // ... a null pointer value, or a prvalue core constant expression of type
940 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000941 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000942
Richard Smithce40ad62011-11-12 22:28:03 +0000943 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
944 // ... the address of an object with static storage duration,
945 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
946 return VD->hasGlobalStorage();
947 // ... the address of a function,
948 return isa<FunctionDecl>(D);
949 }
950
951 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000952 switch (E->getStmtClass()) {
953 default:
954 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000955 case Expr::CompoundLiteralExprClass: {
956 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
957 return CLE->isFileScope() && CLE->isLValue();
958 }
Richard Smithd62306a2011-11-10 06:34:14 +0000959 // A string literal has static storage duration.
960 case Expr::StringLiteralClass:
961 case Expr::PredefinedExprClass:
962 case Expr::ObjCStringLiteralClass:
963 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000964 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000965 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000966 return true;
967 case Expr::CallExprClass:
968 return IsStringLiteralCall(cast<CallExpr>(E));
969 // For GCC compatibility, &&label has static storage duration.
970 case Expr::AddrLabelExprClass:
971 return true;
972 // A Block literal expression may be used as the initialization value for
973 // Block variables at global or local static scope.
974 case Expr::BlockExprClass:
975 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000976 case Expr::ImplicitValueInitExprClass:
977 // FIXME:
978 // We can never form an lvalue with an implicit value initialization as its
979 // base through expression evaluation, so these only appear in one case: the
980 // implicit variable declaration we invent when checking whether a constexpr
981 // constructor can produce a constant expression. We must assume that such
982 // an expression might be a global lvalue.
983 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000984 }
John McCall95007602010-05-10 23:27:23 +0000985}
986
Richard Smithb228a862012-02-15 02:18:13 +0000987static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
988 assert(Base && "no location for a null lvalue");
989 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
990 if (VD)
991 Info.Note(VD->getLocation(), diag::note_declared_at);
992 else
Ted Kremenek28831752012-08-23 20:46:57 +0000993 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000994 diag::note_constexpr_temporary_here);
995}
996
Richard Smith80815602011-11-07 05:07:52 +0000997/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000998/// value for an address or reference constant expression. Return true if we
999/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001000static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1001 QualType Type, const LValue &LVal) {
1002 bool IsReferenceType = Type->isReferenceType();
1003
Richard Smith357362d2011-12-13 06:39:58 +00001004 APValue::LValueBase Base = LVal.getLValueBase();
1005 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1006
Richard Smith0dea49e2012-02-18 04:58:18 +00001007 // Check that the object is a global. Note that the fake 'this' object we
1008 // manufacture when checking potential constant expressions is conservatively
1009 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001010 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001011 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001013 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1014 << IsReferenceType << !Designator.Entries.empty()
1015 << !!VD << VD;
1016 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001017 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001018 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001019 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001020 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001021 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001022 }
Richard Smithb228a862012-02-15 02:18:13 +00001023 assert((Info.CheckingPotentialConstantExpression ||
1024 LVal.getLValueCallIndex() == 0) &&
1025 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001026
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001027 // Check if this is a thread-local variable.
1028 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1029 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001030 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001031 return false;
1032 }
1033 }
1034
Richard Smitha8105bc2012-01-06 16:39:00 +00001035 // Allow address constant expressions to be past-the-end pointers. This is
1036 // an extension: the standard requires them to point to an object.
1037 if (!IsReferenceType)
1038 return true;
1039
1040 // A reference constant expression must refer to an object.
1041 if (!Base) {
1042 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001043 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001044 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001045 }
1046
Richard Smith357362d2011-12-13 06:39:58 +00001047 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001048 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001049 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001050 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001051 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001052 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001053 }
1054
Richard Smith80815602011-11-07 05:07:52 +00001055 return true;
1056}
1057
Richard Smithfddd3842011-12-30 21:15:51 +00001058/// Check that this core constant expression is of literal type, and if not,
1059/// produce an appropriate diagnostic.
1060static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001061 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001062 return true;
1063
1064 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001065 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001066 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001067 << E->getType();
1068 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001069 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001070 return false;
1071}
1072
Richard Smith0b0a0b62011-10-29 20:57:55 +00001073/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001074/// constant expression. If not, report an appropriate diagnostic. Does not
1075/// check that the expression is of literal type.
1076static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1077 QualType Type, const APValue &Value) {
1078 // Core issue 1454: For a literal constant expression of array or class type,
1079 // each subobject of its value shall have been initialized by a constant
1080 // expression.
1081 if (Value.isArray()) {
1082 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1083 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1084 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1085 Value.getArrayInitializedElt(I)))
1086 return false;
1087 }
1088 if (!Value.hasArrayFiller())
1089 return true;
1090 return CheckConstantExpression(Info, DiagLoc, EltTy,
1091 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001092 }
Richard Smithb228a862012-02-15 02:18:13 +00001093 if (Value.isUnion() && Value.getUnionField()) {
1094 return CheckConstantExpression(Info, DiagLoc,
1095 Value.getUnionField()->getType(),
1096 Value.getUnionValue());
1097 }
1098 if (Value.isStruct()) {
1099 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1100 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1101 unsigned BaseIndex = 0;
1102 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1103 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1104 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1105 Value.getStructBase(BaseIndex)))
1106 return false;
1107 }
1108 }
1109 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1110 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001111 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1112 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001113 return false;
1114 }
1115 }
1116
1117 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001118 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001119 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001120 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1121 }
1122
1123 // Everything else is fine.
1124 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001125}
1126
Richard Smith83c68212011-10-31 05:11:32 +00001127const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001128 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001129}
1130
1131static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001132 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001133}
1134
Richard Smithcecf1842011-11-01 21:06:14 +00001135static bool IsWeakLValue(const LValue &Value) {
1136 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001137 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001138}
1139
Richard Smith2e312c82012-03-03 22:46:17 +00001140static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001141 // A null base expression indicates a null pointer. These are always
1142 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001143 if (!Value.getLValueBase()) {
1144 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001145 return true;
1146 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001147
Richard Smith027bf112011-11-17 22:56:20 +00001148 // We have a non-null base. These are generally known to be true, but if it's
1149 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001150 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001151 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001152 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001153}
1154
Richard Smith2e312c82012-03-03 22:46:17 +00001155static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001156 switch (Val.getKind()) {
1157 case APValue::Uninitialized:
1158 return false;
1159 case APValue::Int:
1160 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001161 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001162 case APValue::Float:
1163 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001164 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001165 case APValue::ComplexInt:
1166 Result = Val.getComplexIntReal().getBoolValue() ||
1167 Val.getComplexIntImag().getBoolValue();
1168 return true;
1169 case APValue::ComplexFloat:
1170 Result = !Val.getComplexFloatReal().isZero() ||
1171 !Val.getComplexFloatImag().isZero();
1172 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001173 case APValue::LValue:
1174 return EvalPointerValueAsBool(Val, Result);
1175 case APValue::MemberPointer:
1176 Result = Val.getMemberPointerDecl();
1177 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001178 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001179 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001180 case APValue::Struct:
1181 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001182 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001183 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001184 }
1185
Richard Smith11562c52011-10-28 17:51:58 +00001186 llvm_unreachable("unknown APValue kind");
1187}
1188
1189static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1190 EvalInfo &Info) {
1191 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001192 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001193 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001194 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001195 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001196}
1197
Richard Smith357362d2011-12-13 06:39:58 +00001198template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001199static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001200 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001201 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001202 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001203}
1204
1205static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1206 QualType SrcType, const APFloat &Value,
1207 QualType DestType, APSInt &Result) {
1208 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001209 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001210 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001211
Richard Smith357362d2011-12-13 06:39:58 +00001212 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001213 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001214 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1215 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001216 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001217 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001218}
1219
Richard Smith357362d2011-12-13 06:39:58 +00001220static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1221 QualType SrcType, QualType DestType,
1222 APFloat &Result) {
1223 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001224 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001225 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1226 APFloat::rmNearestTiesToEven, &ignored)
1227 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001228 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001229 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001230}
1231
Richard Smith911e1422012-01-30 22:27:01 +00001232static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1233 QualType DestType, QualType SrcType,
1234 APSInt &Value) {
1235 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001236 APSInt Result = Value;
1237 // Figure out if this is a truncate, extend or noop cast.
1238 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001239 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001240 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001241 return Result;
1242}
1243
Richard Smith357362d2011-12-13 06:39:58 +00001244static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1245 QualType SrcType, const APSInt &Value,
1246 QualType DestType, APFloat &Result) {
1247 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1248 if (Result.convertFromAPInt(Value, Value.isSigned(),
1249 APFloat::rmNearestTiesToEven)
1250 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001251 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001252 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001253}
1254
Eli Friedman803acb32011-12-22 03:51:45 +00001255static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1256 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001257 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001258 if (!Evaluate(SVal, Info, E))
1259 return false;
1260 if (SVal.isInt()) {
1261 Res = SVal.getInt();
1262 return true;
1263 }
1264 if (SVal.isFloat()) {
1265 Res = SVal.getFloat().bitcastToAPInt();
1266 return true;
1267 }
1268 if (SVal.isVector()) {
1269 QualType VecTy = E->getType();
1270 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1271 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1272 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1273 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1274 Res = llvm::APInt::getNullValue(VecSize);
1275 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1276 APValue &Elt = SVal.getVectorElt(i);
1277 llvm::APInt EltAsInt;
1278 if (Elt.isInt()) {
1279 EltAsInt = Elt.getInt();
1280 } else if (Elt.isFloat()) {
1281 EltAsInt = Elt.getFloat().bitcastToAPInt();
1282 } else {
1283 // Don't try to handle vectors of anything other than int or float
1284 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001285 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001286 return false;
1287 }
1288 unsigned BaseEltSize = EltAsInt.getBitWidth();
1289 if (BigEndian)
1290 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1291 else
1292 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1293 }
1294 return true;
1295 }
1296 // Give up if the input isn't an int, float, or vector. For example, we
1297 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001298 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001299 return false;
1300}
1301
Richard Smitha8105bc2012-01-06 16:39:00 +00001302/// Cast an lvalue referring to a base subobject to a derived class, by
1303/// truncating the lvalue's path to the given length.
1304static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1305 const RecordDecl *TruncatedType,
1306 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001307 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001308
1309 // Check we actually point to a derived class object.
1310 if (TruncatedElements == D.Entries.size())
1311 return true;
1312 assert(TruncatedElements >= D.MostDerivedPathLength &&
1313 "not casting to a derived class");
1314 if (!Result.checkSubobject(Info, E, CSK_Derived))
1315 return false;
1316
1317 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001318 const RecordDecl *RD = TruncatedType;
1319 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001320 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001321 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1322 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001323 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001324 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001325 else
Richard Smithd62306a2011-11-10 06:34:14 +00001326 Result.Offset -= Layout.getBaseClassOffset(Base);
1327 RD = Base;
1328 }
Richard Smith027bf112011-11-17 22:56:20 +00001329 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001330 return true;
1331}
1332
John McCalld7bca762012-05-01 00:38:49 +00001333static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001334 const CXXRecordDecl *Derived,
1335 const CXXRecordDecl *Base,
1336 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001337 if (!RL) {
1338 if (Derived->isInvalidDecl()) return false;
1339 RL = &Info.Ctx.getASTRecordLayout(Derived);
1340 }
1341
Richard Smithd62306a2011-11-10 06:34:14 +00001342 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001343 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001344 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001345}
1346
Richard Smitha8105bc2012-01-06 16:39:00 +00001347static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001348 const CXXRecordDecl *DerivedDecl,
1349 const CXXBaseSpecifier *Base) {
1350 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1351
John McCalld7bca762012-05-01 00:38:49 +00001352 if (!Base->isVirtual())
1353 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001354
Richard Smitha8105bc2012-01-06 16:39:00 +00001355 SubobjectDesignator &D = Obj.Designator;
1356 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001357 return false;
1358
Richard Smitha8105bc2012-01-06 16:39:00 +00001359 // Extract most-derived object and corresponding type.
1360 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1361 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1362 return false;
1363
1364 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001365 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001366 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1367 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001368 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001369 return true;
1370}
1371
1372/// Update LVal to refer to the given field, which must be a member of the type
1373/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001374static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001375 const FieldDecl *FD,
1376 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001377 if (!RL) {
1378 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001379 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001380 }
Richard Smithd62306a2011-11-10 06:34:14 +00001381
1382 unsigned I = FD->getFieldIndex();
1383 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001384 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001385 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001386}
1387
Richard Smith1b78b3d2012-01-25 22:15:11 +00001388/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001389static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001390 LValue &LVal,
1391 const IndirectFieldDecl *IFD) {
1392 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1393 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001394 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1395 return false;
1396 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001397}
1398
Richard Smithd62306a2011-11-10 06:34:14 +00001399/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001400static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1401 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001402 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1403 // extension.
1404 if (Type->isVoidType() || Type->isFunctionType()) {
1405 Size = CharUnits::One();
1406 return true;
1407 }
1408
1409 if (!Type->isConstantSizeType()) {
1410 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001411 // FIXME: Better diagnostic.
1412 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001413 return false;
1414 }
1415
1416 Size = Info.Ctx.getTypeSizeInChars(Type);
1417 return true;
1418}
1419
1420/// Update a pointer value to model pointer arithmetic.
1421/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001422/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001423/// \param LVal - The pointer value to be updated.
1424/// \param EltTy - The pointee type represented by LVal.
1425/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001426static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1427 LValue &LVal, QualType EltTy,
1428 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001429 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001430 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001431 return false;
1432
1433 // Compute the new offset in the appropriate width.
1434 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001435 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001436 return true;
1437}
1438
Richard Smith66c96992012-02-18 22:04:06 +00001439/// Update an lvalue to refer to a component of a complex number.
1440/// \param Info - Information about the ongoing evaluation.
1441/// \param LVal - The lvalue to be updated.
1442/// \param EltTy - The complex number's component type.
1443/// \param Imag - False for the real component, true for the imaginary.
1444static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1445 LValue &LVal, QualType EltTy,
1446 bool Imag) {
1447 if (Imag) {
1448 CharUnits SizeOfComponent;
1449 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1450 return false;
1451 LVal.Offset += SizeOfComponent;
1452 }
1453 LVal.addComplex(Info, E, EltTy, Imag);
1454 return true;
1455}
1456
Richard Smith27908702011-10-24 17:54:18 +00001457/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001458///
1459/// \param Info Information about the ongoing evaluation.
1460/// \param E An expression to be used when printing diagnostics.
1461/// \param VD The variable whose initializer should be obtained.
1462/// \param Frame The frame in which the variable was created. Must be null
1463/// if this variable is not local to the evaluation.
1464/// \param Result Filled in with a pointer to the value of the variable.
1465static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1466 const VarDecl *VD, CallStackFrame *Frame,
1467 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001468 // If this is a parameter to an active constexpr function call, perform
1469 // argument substitution.
1470 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001471 // Assume arguments of a potential constant expression are unknown
1472 // constant expressions.
1473 if (Info.CheckingPotentialConstantExpression)
1474 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001475 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001476 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001477 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001478 }
Richard Smith3229b742013-05-05 21:17:10 +00001479 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001480 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001481 }
Richard Smith27908702011-10-24 17:54:18 +00001482
Richard Smithd9f663b2013-04-22 15:31:51 +00001483 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001484 if (Frame) {
1485 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001486 // If we've carried on past an unevaluatable local variable initializer,
1487 // we can't go any further. This can happen during potential constant
1488 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001489 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001490 }
1491
Richard Smithd0b4dd62011-12-19 06:19:21 +00001492 // Dig out the initializer, and use the declaration which it's attached to.
1493 const Expr *Init = VD->getAnyInitializer(VD);
1494 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001495 // If we're checking a potential constant expression, the variable could be
1496 // initialized later.
1497 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001498 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001499 return false;
1500 }
1501
Richard Smithd62306a2011-11-10 06:34:14 +00001502 // If we're currently evaluating the initializer of this declaration, use that
1503 // in-flight value.
1504 if (Info.EvaluatingDecl == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001505 Result = Info.EvaluatingDeclValue;
1506 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001507 }
1508
Richard Smithcecf1842011-11-01 21:06:14 +00001509 // Never evaluate the initializer of a weak variable. We can't be sure that
1510 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001511 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001512 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001513 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001514 }
Richard Smithcecf1842011-11-01 21:06:14 +00001515
Richard Smithd0b4dd62011-12-19 06:19:21 +00001516 // Check that we can fold the initializer. In C++, we will have already done
1517 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001518 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001519 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001520 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001521 Notes.size() + 1) << VD;
1522 Info.Note(VD->getLocation(), diag::note_declared_at);
1523 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001524 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001525 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001526 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001527 Notes.size() + 1) << VD;
1528 Info.Note(VD->getLocation(), diag::note_declared_at);
1529 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001530 }
Richard Smith27908702011-10-24 17:54:18 +00001531
Richard Smith3229b742013-05-05 21:17:10 +00001532 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001533 return true;
Richard Smith27908702011-10-24 17:54:18 +00001534}
1535
Richard Smith11562c52011-10-28 17:51:58 +00001536static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001537 Qualifiers Quals = T.getQualifiers();
1538 return Quals.hasConst() && !Quals.hasVolatile();
1539}
1540
Richard Smithe97cbd72011-11-11 04:05:33 +00001541/// Get the base index of the given base class within an APValue representing
1542/// the given derived class.
1543static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1544 const CXXRecordDecl *Base) {
1545 Base = Base->getCanonicalDecl();
1546 unsigned Index = 0;
1547 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1548 E = Derived->bases_end(); I != E; ++I, ++Index) {
1549 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1550 return Index;
1551 }
1552
1553 llvm_unreachable("base class missing from derived class's bases list");
1554}
1555
Richard Smith3da88fa2013-04-26 14:36:30 +00001556/// Extract the value of a character from a string literal.
1557static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1558 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001559 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001560 const StringLiteral *S = cast<StringLiteral>(Lit);
1561 const ConstantArrayType *CAT =
1562 Info.Ctx.getAsConstantArrayType(S->getType());
1563 assert(CAT && "string literal isn't an array");
1564 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001565 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001566
1567 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001568 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001569 if (Index < S->getLength())
1570 Value = S->getCodeUnit(Index);
1571 return Value;
1572}
1573
Richard Smith3da88fa2013-04-26 14:36:30 +00001574// Expand a string literal into an array of characters.
1575static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1576 APValue &Result) {
1577 const StringLiteral *S = cast<StringLiteral>(Lit);
1578 const ConstantArrayType *CAT =
1579 Info.Ctx.getAsConstantArrayType(S->getType());
1580 assert(CAT && "string literal isn't an array");
1581 QualType CharType = CAT->getElementType();
1582 assert(CharType->isIntegerType() && "unexpected character type");
1583
1584 unsigned Elts = CAT->getSize().getZExtValue();
1585 Result = APValue(APValue::UninitArray(),
1586 std::min(S->getLength(), Elts), Elts);
1587 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1588 CharType->isUnsignedIntegerType());
1589 if (Result.hasArrayFiller())
1590 Result.getArrayFiller() = APValue(Value);
1591 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1592 Value = S->getCodeUnit(I);
1593 Result.getArrayInitializedElt(I) = APValue(Value);
1594 }
1595}
1596
1597// Expand an array so that it has more than Index filled elements.
1598static void expandArray(APValue &Array, unsigned Index) {
1599 unsigned Size = Array.getArraySize();
1600 assert(Index < Size);
1601
1602 // Always at least double the number of elements for which we store a value.
1603 unsigned OldElts = Array.getArrayInitializedElts();
1604 unsigned NewElts = std::max(Index+1, OldElts * 2);
1605 NewElts = std::min(Size, std::max(NewElts, 8u));
1606
1607 // Copy the data across.
1608 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1609 for (unsigned I = 0; I != OldElts; ++I)
1610 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1611 for (unsigned I = OldElts; I != NewElts; ++I)
1612 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1613 if (NewValue.hasArrayFiller())
1614 NewValue.getArrayFiller() = Array.getArrayFiller();
1615 Array.swap(NewValue);
1616}
1617
1618/// Kinds of access we can perform on an object.
1619enum AccessKinds {
1620 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001621 AK_Assign,
1622 AK_Increment,
1623 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001624};
1625
Richard Smith3229b742013-05-05 21:17:10 +00001626/// A handle to a complete object (an object that is not a subobject of
1627/// another object).
1628struct CompleteObject {
1629 /// The value of the complete object.
1630 APValue *Value;
1631 /// The type of the complete object.
1632 QualType Type;
1633
1634 CompleteObject() : Value(0) {}
1635 CompleteObject(APValue *Value, QualType Type)
1636 : Value(Value), Type(Type) {
1637 assert(Value && "missing value for complete object");
1638 }
1639
1640 operator bool() const { return Value; }
1641};
1642
Richard Smith3da88fa2013-04-26 14:36:30 +00001643/// Find the designated sub-object of an rvalue.
1644template<typename SubobjectHandler>
1645typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001646findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001647 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001648 if (Sub.Invalid)
1649 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001650 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001651 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001652 if (Info.getLangOpts().CPlusPlus11)
1653 Info.Diag(E, diag::note_constexpr_access_past_end)
1654 << handler.AccessKind;
1655 else
1656 Info.Diag(E);
1657 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001658 }
Richard Smith6804be52011-11-11 08:28:03 +00001659 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001660 return handler.found(*Obj.Value, Obj.Type);
1661 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001662 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001663 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001664
Richard Smith3229b742013-05-05 21:17:10 +00001665 APValue *O = Obj.Value;
1666 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001667 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001668 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001669 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001670 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001671 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001672 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001673 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001674 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001675 // Note, it should not be possible to form a pointer with a valid
1676 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001677 if (Info.getLangOpts().CPlusPlus11)
1678 Info.Diag(E, diag::note_constexpr_access_past_end)
1679 << handler.AccessKind;
1680 else
1681 Info.Diag(E);
1682 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001683 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001684
1685 ObjType = CAT->getElementType();
1686
Richard Smith14a94132012-02-17 03:35:37 +00001687 // An array object is represented as either an Array APValue or as an
1688 // LValue which refers to a string literal.
1689 if (O->isLValue()) {
1690 assert(I == N - 1 && "extracting subobject of character?");
1691 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001692 if (handler.AccessKind != AK_Read)
1693 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1694 *O);
1695 else
1696 return handler.foundString(*O, ObjType, Index);
1697 }
1698
1699 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001700 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001701 else if (handler.AccessKind != AK_Read) {
1702 expandArray(*O, Index);
1703 O = &O->getArrayInitializedElt(Index);
1704 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001705 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001706 } else if (ObjType->isAnyComplexType()) {
1707 // Next subobject is a complex number.
1708 uint64_t Index = Sub.Entries[I].ArrayIndex;
1709 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001710 if (Info.getLangOpts().CPlusPlus11)
1711 Info.Diag(E, diag::note_constexpr_access_past_end)
1712 << handler.AccessKind;
1713 else
1714 Info.Diag(E);
1715 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001716 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001717
1718 bool WasConstQualified = ObjType.isConstQualified();
1719 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1720 if (WasConstQualified)
1721 ObjType.addConst();
1722
Richard Smith66c96992012-02-18 22:04:06 +00001723 assert(I == N - 1 && "extracting subobject of scalar?");
1724 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001725 return handler.found(Index ? O->getComplexIntImag()
1726 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001727 } else {
1728 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001729 return handler.found(Index ? O->getComplexFloatImag()
1730 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001731 }
Richard Smithd62306a2011-11-10 06:34:14 +00001732 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001733 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001734 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001735 << Field;
1736 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001737 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001738 }
1739
Richard Smithd62306a2011-11-10 06:34:14 +00001740 // Next subobject is a class, struct or union field.
1741 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1742 if (RD->isUnion()) {
1743 const FieldDecl *UnionField = O->getUnionField();
1744 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001746 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1747 << handler.AccessKind << Field << !UnionField << UnionField;
1748 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001749 }
Richard Smithd62306a2011-11-10 06:34:14 +00001750 O = &O->getUnionValue();
1751 } else
1752 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001753
1754 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001755 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001756 if (WasConstQualified && !Field->isMutable())
1757 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001758
1759 if (ObjType.isVolatileQualified()) {
1760 if (Info.getLangOpts().CPlusPlus) {
1761 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001762 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1763 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001764 Info.Note(Field->getLocation(), diag::note_declared_at);
1765 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001766 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001767 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001768 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001769 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001770 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001771 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001772 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1773 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1774 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001775
1776 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001777 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001778 if (WasConstQualified)
1779 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001780 }
Richard Smithd62306a2011-11-10 06:34:14 +00001781
Richard Smithf57d8cb2011-12-09 22:58:01 +00001782 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001783 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001784 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1785 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001786 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001787 }
1788
Richard Smith3da88fa2013-04-26 14:36:30 +00001789 return handler.found(*O, ObjType);
1790}
1791
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001792namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001793struct ExtractSubobjectHandler {
1794 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001795 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001796
1797 static const AccessKinds AccessKind = AK_Read;
1798
1799 typedef bool result_type;
1800 bool failed() { return false; }
1801 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001802 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001803 return true;
1804 }
1805 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001806 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001807 return true;
1808 }
1809 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001810 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001811 return true;
1812 }
1813 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001814 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001815 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1816 return true;
1817 }
1818};
Richard Smith3229b742013-05-05 21:17:10 +00001819} // end anonymous namespace
1820
Richard Smith3da88fa2013-04-26 14:36:30 +00001821const AccessKinds ExtractSubobjectHandler::AccessKind;
1822
1823/// Extract the designated sub-object of an rvalue.
1824static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001825 const CompleteObject &Obj,
1826 const SubobjectDesignator &Sub,
1827 APValue &Result) {
1828 ExtractSubobjectHandler Handler = { Info, Result };
1829 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00001830}
1831
Richard Smith3229b742013-05-05 21:17:10 +00001832namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001833struct ModifySubobjectHandler {
1834 EvalInfo &Info;
1835 APValue &NewVal;
1836 const Expr *E;
1837
1838 typedef bool result_type;
1839 static const AccessKinds AccessKind = AK_Assign;
1840
1841 bool checkConst(QualType QT) {
1842 // Assigning to a const object has undefined behavior.
1843 if (QT.isConstQualified()) {
1844 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
1845 return false;
1846 }
1847 return true;
1848 }
1849
1850 bool failed() { return false; }
1851 bool found(APValue &Subobj, QualType SubobjType) {
1852 if (!checkConst(SubobjType))
1853 return false;
1854 // We've been given ownership of NewVal, so just swap it in.
1855 Subobj.swap(NewVal);
1856 return true;
1857 }
1858 bool found(APSInt &Value, QualType SubobjType) {
1859 if (!checkConst(SubobjType))
1860 return false;
1861 if (!NewVal.isInt()) {
1862 // Maybe trying to write a cast pointer value into a complex?
1863 Info.Diag(E);
1864 return false;
1865 }
1866 Value = NewVal.getInt();
1867 return true;
1868 }
1869 bool found(APFloat &Value, QualType SubobjType) {
1870 if (!checkConst(SubobjType))
1871 return false;
1872 Value = NewVal.getFloat();
1873 return true;
1874 }
1875 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1876 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
1877 }
1878};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001879} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00001880
Richard Smith3229b742013-05-05 21:17:10 +00001881const AccessKinds ModifySubobjectHandler::AccessKind;
1882
Richard Smith3da88fa2013-04-26 14:36:30 +00001883/// Update the designated sub-object of an rvalue to the given value.
1884static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001885 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001886 const SubobjectDesignator &Sub,
1887 APValue &NewVal) {
1888 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00001889 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00001890}
1891
Richard Smith84f6dcf2012-02-02 01:16:57 +00001892/// Find the position where two subobject designators diverge, or equivalently
1893/// the length of the common initial subsequence.
1894static unsigned FindDesignatorMismatch(QualType ObjType,
1895 const SubobjectDesignator &A,
1896 const SubobjectDesignator &B,
1897 bool &WasArrayIndex) {
1898 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1899 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001900 if (!ObjType.isNull() &&
1901 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001902 // Next subobject is an array element.
1903 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1904 WasArrayIndex = true;
1905 return I;
1906 }
Richard Smith66c96992012-02-18 22:04:06 +00001907 if (ObjType->isAnyComplexType())
1908 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1909 else
1910 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001911 } else {
1912 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1913 WasArrayIndex = false;
1914 return I;
1915 }
1916 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1917 // Next subobject is a field.
1918 ObjType = FD->getType();
1919 else
1920 // Next subobject is a base class.
1921 ObjType = QualType();
1922 }
1923 }
1924 WasArrayIndex = false;
1925 return I;
1926}
1927
1928/// Determine whether the given subobject designators refer to elements of the
1929/// same array object.
1930static bool AreElementsOfSameArray(QualType ObjType,
1931 const SubobjectDesignator &A,
1932 const SubobjectDesignator &B) {
1933 if (A.Entries.size() != B.Entries.size())
1934 return false;
1935
1936 bool IsArray = A.MostDerivedArraySize != 0;
1937 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1938 // A is a subobject of the array element.
1939 return false;
1940
1941 // If A (and B) designates an array element, the last entry will be the array
1942 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1943 // of length 1' case, and the entire path must match.
1944 bool WasArrayIndex;
1945 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1946 return CommonLength >= A.Entries.size() - IsArray;
1947}
1948
Richard Smith3229b742013-05-05 21:17:10 +00001949/// Find the complete object to which an LValue refers.
1950CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
1951 const LValue &LVal, QualType LValType) {
1952 if (!LVal.Base) {
1953 Info.Diag(E, diag::note_constexpr_access_null) << AK;
1954 return CompleteObject();
1955 }
1956
1957 CallStackFrame *Frame = 0;
1958 if (LVal.CallIndex) {
1959 Frame = Info.getCallFrame(LVal.CallIndex);
1960 if (!Frame) {
1961 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
1962 << AK << LVal.Base.is<const ValueDecl*>();
1963 NoteLValueLocation(Info, LVal.Base);
1964 return CompleteObject();
1965 }
1966 } else if (AK != AK_Read) {
1967 Info.Diag(E, diag::note_constexpr_modify_global);
1968 return CompleteObject();
1969 }
1970
1971 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1972 // is not a constant expression (even if the object is non-volatile). We also
1973 // apply this rule to C++98, in order to conform to the expected 'volatile'
1974 // semantics.
1975 if (LValType.isVolatileQualified()) {
1976 if (Info.getLangOpts().CPlusPlus)
1977 Info.Diag(E, diag::note_constexpr_access_volatile_type)
1978 << AK << LValType;
1979 else
1980 Info.Diag(E);
1981 return CompleteObject();
1982 }
1983
1984 // Compute value storage location and type of base object.
1985 APValue *BaseVal = 0;
1986 QualType BaseType;
1987
1988 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1989 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1990 // In C++11, constexpr, non-volatile variables initialized with constant
1991 // expressions are constant expressions too. Inside constexpr functions,
1992 // parameters are constant expressions even if they're non-const.
1993 // In C++1y, objects local to a constant expression (those with a Frame) are
1994 // both readable and writable inside constant expressions.
1995 // In C, such things can also be folded, although they are not ICEs.
1996 const VarDecl *VD = dyn_cast<VarDecl>(D);
1997 if (VD) {
1998 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1999 VD = VDef;
2000 }
2001 if (!VD || VD->isInvalidDecl()) {
2002 Info.Diag(E);
2003 return CompleteObject();
2004 }
2005
2006 // Accesses of volatile-qualified objects are not allowed.
2007 BaseType = VD->getType();
2008 if (BaseType.isVolatileQualified()) {
2009 if (Info.getLangOpts().CPlusPlus) {
2010 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2011 << AK << 1 << VD;
2012 Info.Note(VD->getLocation(), diag::note_declared_at);
2013 } else {
2014 Info.Diag(E);
2015 }
2016 return CompleteObject();
2017 }
2018
2019 // Unless we're looking at a local variable or argument in a constexpr call,
2020 // the variable we're reading must be const.
2021 if (!Frame) {
2022 assert(AK == AK_Read && "can't modify non-local");
2023 if (VD->isConstexpr()) {
2024 // OK, we can read this variable.
2025 } else if (BaseType->isIntegralOrEnumerationType()) {
2026 if (!BaseType.isConstQualified()) {
2027 if (Info.getLangOpts().CPlusPlus) {
2028 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2029 Info.Note(VD->getLocation(), diag::note_declared_at);
2030 } else {
2031 Info.Diag(E);
2032 }
2033 return CompleteObject();
2034 }
2035 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2036 // We support folding of const floating-point types, in order to make
2037 // static const data members of such types (supported as an extension)
2038 // more useful.
2039 if (Info.getLangOpts().CPlusPlus11) {
2040 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2041 Info.Note(VD->getLocation(), diag::note_declared_at);
2042 } else {
2043 Info.CCEDiag(E);
2044 }
2045 } else {
2046 // FIXME: Allow folding of values of any literal type in all languages.
2047 if (Info.getLangOpts().CPlusPlus11) {
2048 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2049 Info.Note(VD->getLocation(), diag::note_declared_at);
2050 } else {
2051 Info.Diag(E);
2052 }
2053 return CompleteObject();
2054 }
2055 }
2056
2057 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2058 return CompleteObject();
2059 } else {
2060 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2061
2062 if (!Frame) {
2063 Info.Diag(E);
2064 return CompleteObject();
2065 }
2066
2067 BaseType = Base->getType();
2068 BaseVal = &Frame->Temporaries[Base];
2069
2070 // Volatile temporary objects cannot be accessed in constant expressions.
2071 if (BaseType.isVolatileQualified()) {
2072 if (Info.getLangOpts().CPlusPlus) {
2073 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2074 << AK << 0;
2075 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2076 } else {
2077 Info.Diag(E);
2078 }
2079 return CompleteObject();
2080 }
2081 }
2082
2083 // In C++1y, we can't safely access any mutable state when checking a
2084 // potential constant expression.
2085 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2086 Info.CheckingPotentialConstantExpression)
2087 return CompleteObject();
2088
2089 return CompleteObject(BaseVal, BaseType);
2090}
2091
Richard Smith243ef902013-05-05 23:31:59 +00002092/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2093/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2094/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002095///
2096/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002097/// \param Conv - The expression for which we are performing the conversion.
2098/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002099/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2100/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002101/// \param LVal - The glvalue on which we are attempting to perform this action.
2102/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002103static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002104 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002105 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002106 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002107 return false;
2108
Richard Smith3229b742013-05-05 21:17:10 +00002109 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002110 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002111 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2112 !Type.isVolatileQualified()) {
2113 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2114 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2115 // initializer until now for such expressions. Such an expression can't be
2116 // an ICE in C, so this only matters for fold.
2117 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2118 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002119 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002120 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002121 }
Richard Smith3229b742013-05-05 21:17:10 +00002122 APValue Lit;
2123 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2124 return false;
2125 CompleteObject LitObj(&Lit, Base->getType());
2126 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2127 } else if (isa<StringLiteral>(Base)) {
2128 // We represent a string literal array as an lvalue pointing at the
2129 // corresponding expression, rather than building an array of chars.
2130 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2131 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2132 CompleteObject StrObj(&Str, Base->getType());
2133 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002134 }
Richard Smith11562c52011-10-28 17:51:58 +00002135 }
2136
Richard Smith3229b742013-05-05 21:17:10 +00002137 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2138 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002139}
2140
2141/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002142static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002143 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002144 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002145 return false;
2146
Richard Smith3229b742013-05-05 21:17:10 +00002147 if (!Info.getLangOpts().CPlusPlus1y) {
2148 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002149 return false;
2150 }
2151
Richard Smith3229b742013-05-05 21:17:10 +00002152 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2153 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002154}
2155
Richard Smith243ef902013-05-05 23:31:59 +00002156static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2157 return T->isSignedIntegerType() &&
2158 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2159}
2160
2161namespace {
2162struct IncDecSubobjectHandler {
2163 EvalInfo &Info;
2164 const Expr *E;
2165 AccessKinds AccessKind;
2166 APValue *Old;
2167
2168 typedef bool result_type;
2169
2170 bool checkConst(QualType QT) {
2171 // Assigning to a const object has undefined behavior.
2172 if (QT.isConstQualified()) {
2173 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2174 return false;
2175 }
2176 return true;
2177 }
2178
2179 bool failed() { return false; }
2180 bool found(APValue &Subobj, QualType SubobjType) {
2181 // Stash the old value. Also clear Old, so we don't clobber it later
2182 // if we're post-incrementing a complex.
2183 if (Old) {
2184 *Old = Subobj;
2185 Old = 0;
2186 }
2187
2188 switch (Subobj.getKind()) {
2189 case APValue::Int:
2190 return found(Subobj.getInt(), SubobjType);
2191 case APValue::Float:
2192 return found(Subobj.getFloat(), SubobjType);
2193 case APValue::ComplexInt:
2194 return found(Subobj.getComplexIntReal(),
2195 SubobjType->castAs<ComplexType>()->getElementType()
2196 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2197 case APValue::ComplexFloat:
2198 return found(Subobj.getComplexFloatReal(),
2199 SubobjType->castAs<ComplexType>()->getElementType()
2200 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2201 case APValue::LValue:
2202 return foundPointer(Subobj, SubobjType);
2203 default:
2204 // FIXME: can this happen?
2205 Info.Diag(E);
2206 return false;
2207 }
2208 }
2209 bool found(APSInt &Value, QualType SubobjType) {
2210 if (!checkConst(SubobjType))
2211 return false;
2212
2213 if (!SubobjType->isIntegerType()) {
2214 // We don't support increment / decrement on integer-cast-to-pointer
2215 // values.
2216 Info.Diag(E);
2217 return false;
2218 }
2219
2220 if (Old) *Old = APValue(Value);
2221
2222 // bool arithmetic promotes to int, and the conversion back to bool
2223 // doesn't reduce mod 2^n, so special-case it.
2224 if (SubobjType->isBooleanType()) {
2225 if (AccessKind == AK_Increment)
2226 Value = 1;
2227 else
2228 Value = !Value;
2229 return true;
2230 }
2231
2232 bool WasNegative = Value.isNegative();
2233 if (AccessKind == AK_Increment) {
2234 ++Value;
2235
2236 if (!WasNegative && Value.isNegative() &&
2237 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2238 APSInt ActualValue(Value, /*IsUnsigned*/true);
2239 HandleOverflow(Info, E, ActualValue, SubobjType);
2240 }
2241 } else {
2242 --Value;
2243
2244 if (WasNegative && !Value.isNegative() &&
2245 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2246 unsigned BitWidth = Value.getBitWidth();
2247 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2248 ActualValue.setBit(BitWidth);
2249 HandleOverflow(Info, E, ActualValue, SubobjType);
2250 }
2251 }
2252 return true;
2253 }
2254 bool found(APFloat &Value, QualType SubobjType) {
2255 if (!checkConst(SubobjType))
2256 return false;
2257
2258 if (Old) *Old = APValue(Value);
2259
2260 APFloat One(Value.getSemantics(), 1);
2261 if (AccessKind == AK_Increment)
2262 Value.add(One, APFloat::rmNearestTiesToEven);
2263 else
2264 Value.subtract(One, APFloat::rmNearestTiesToEven);
2265 return true;
2266 }
2267 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2268 if (!checkConst(SubobjType))
2269 return false;
2270
2271 QualType PointeeType;
2272 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2273 PointeeType = PT->getPointeeType();
2274 else {
2275 Info.Diag(E);
2276 return false;
2277 }
2278
2279 LValue LVal;
2280 LVal.setFrom(Info.Ctx, Subobj);
2281 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2282 AccessKind == AK_Increment ? 1 : -1))
2283 return false;
2284 LVal.moveInto(Subobj);
2285 return true;
2286 }
2287 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2288 llvm_unreachable("shouldn't encounter string elements here");
2289 }
2290};
2291} // end anonymous namespace
2292
2293/// Perform an increment or decrement on LVal.
2294static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2295 QualType LValType, bool IsIncrement, APValue *Old) {
2296 if (LVal.Designator.Invalid)
2297 return false;
2298
2299 if (!Info.getLangOpts().CPlusPlus1y) {
2300 Info.Diag(E);
2301 return false;
2302 }
2303
2304 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2305 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2306 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2307 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2308}
2309
Richard Smithe97cbd72011-11-11 04:05:33 +00002310/// Build an lvalue for the object argument of a member function call.
2311static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2312 LValue &This) {
2313 if (Object->getType()->isPointerType())
2314 return EvaluatePointer(Object, This, Info);
2315
2316 if (Object->isGLValue())
2317 return EvaluateLValue(Object, This, Info);
2318
Richard Smithd9f663b2013-04-22 15:31:51 +00002319 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002320 return EvaluateTemporary(Object, This, Info);
2321
2322 return false;
2323}
2324
2325/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2326/// lvalue referring to the result.
2327///
2328/// \param Info - Information about the ongoing evaluation.
2329/// \param BO - The member pointer access operation.
2330/// \param LV - Filled in with a reference to the resulting object.
2331/// \param IncludeMember - Specifies whether the member itself is included in
2332/// the resulting LValue subobject designator. This is not possible when
2333/// creating a bound member function.
2334/// \return The field or method declaration to which the member pointer refers,
2335/// or 0 if evaluation fails.
2336static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2337 const BinaryOperator *BO,
2338 LValue &LV,
2339 bool IncludeMember = true) {
2340 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2341
Richard Smith253c2a32012-01-27 01:14:48 +00002342 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2343 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002344 return 0;
2345
2346 MemberPtr MemPtr;
2347 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2348 return 0;
2349
2350 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2351 // member value, the behavior is undefined.
2352 if (!MemPtr.getDecl())
2353 return 0;
2354
Richard Smith253c2a32012-01-27 01:14:48 +00002355 if (!EvalObjOK)
2356 return 0;
2357
Richard Smith027bf112011-11-17 22:56:20 +00002358 if (MemPtr.isDerivedMember()) {
2359 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002360 // The end of the derived-to-base path for the base object must match the
2361 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002362 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002363 LV.Designator.Entries.size())
2364 return 0;
2365 unsigned PathLengthToMember =
2366 LV.Designator.Entries.size() - MemPtr.Path.size();
2367 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2368 const CXXRecordDecl *LVDecl = getAsBaseClass(
2369 LV.Designator.Entries[PathLengthToMember + I]);
2370 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2371 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2372 return 0;
2373 }
2374
2375 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002376 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2377 PathLengthToMember))
2378 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002379 } else if (!MemPtr.Path.empty()) {
2380 // Extend the LValue path with the member pointer's path.
2381 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2382 MemPtr.Path.size() + IncludeMember);
2383
2384 // Walk down to the appropriate base class.
2385 QualType LVType = BO->getLHS()->getType();
2386 if (const PointerType *PT = LVType->getAs<PointerType>())
2387 LVType = PT->getPointeeType();
2388 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2389 assert(RD && "member pointer access on non-class-type expression");
2390 // The first class in the path is that of the lvalue.
2391 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2392 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002393 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2394 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002395 RD = Base;
2396 }
2397 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002398 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2399 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002400 }
2401
2402 // Add the member. Note that we cannot build bound member functions here.
2403 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002404 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2405 if (!HandleLValueMember(Info, BO, LV, FD))
2406 return 0;
2407 } else if (const IndirectFieldDecl *IFD =
2408 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2409 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2410 return 0;
2411 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002412 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002413 }
Richard Smith027bf112011-11-17 22:56:20 +00002414 }
2415
2416 return MemPtr.getDecl();
2417}
2418
2419/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2420/// the provided lvalue, which currently refers to the base object.
2421static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2422 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002423 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002424 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002425 return false;
2426
Richard Smitha8105bc2012-01-06 16:39:00 +00002427 QualType TargetQT = E->getType();
2428 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2429 TargetQT = PT->getPointeeType();
2430
2431 // Check this cast lands within the final derived-to-base subobject path.
2432 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002433 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002434 << D.MostDerivedType << TargetQT;
2435 return false;
2436 }
2437
Richard Smith027bf112011-11-17 22:56:20 +00002438 // Check the type of the final cast. We don't need to check the path,
2439 // since a cast can only be formed if the path is unique.
2440 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002441 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2442 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002443 if (NewEntriesSize == D.MostDerivedPathLength)
2444 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2445 else
Richard Smith027bf112011-11-17 22:56:20 +00002446 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002447 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002448 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002449 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002450 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002451 }
Richard Smith027bf112011-11-17 22:56:20 +00002452
2453 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002454 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002455}
2456
Mike Stump876387b2009-10-27 22:09:17 +00002457namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002458enum EvalStmtResult {
2459 /// Evaluation failed.
2460 ESR_Failed,
2461 /// Hit a 'return' statement.
2462 ESR_Returned,
2463 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002464 ESR_Succeeded,
2465 /// Hit a 'continue' statement.
2466 ESR_Continue,
2467 /// Hit a 'break' statement.
2468 ESR_Break
Richard Smith254a73d2011-10-28 22:34:42 +00002469};
2470}
2471
Richard Smithd9f663b2013-04-22 15:31:51 +00002472static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2473 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2474 // We don't need to evaluate the initializer for a static local.
2475 if (!VD->hasLocalStorage())
2476 return true;
2477
2478 LValue Result;
2479 Result.set(VD, Info.CurrentCall->Index);
2480 APValue &Val = Info.CurrentCall->Temporaries[VD];
2481
2482 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2483 // Wipe out any partially-computed value, to allow tracking that this
2484 // evaluation failed.
2485 Val = APValue();
2486 return false;
2487 }
2488 }
2489
2490 return true;
2491}
2492
Richard Smith4e18ca52013-05-06 05:56:11 +00002493/// Evaluate a condition (either a variable declaration or an expression).
2494static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2495 const Expr *Cond, bool &Result) {
2496 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2497 return false;
2498 return EvaluateAsBooleanCondition(Cond, Result, Info);
2499}
2500
2501static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2502 const Stmt *S);
2503
2504/// Evaluate the body of a loop, and translate the result as appropriate.
2505static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
2506 const Stmt *Body) {
2507 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body)) {
2508 case ESR_Break:
2509 return ESR_Succeeded;
2510 case ESR_Succeeded:
2511 case ESR_Continue:
2512 return ESR_Continue;
2513 case ESR_Failed:
2514 case ESR_Returned:
2515 return ESR;
2516 }
2517}
2518
Richard Smith254a73d2011-10-28 22:34:42 +00002519// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002520static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002521 const Stmt *S) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002522 // FIXME: Mark all temporaries in the current frame as destroyed at
2523 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002524 switch (S->getStmtClass()) {
2525 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002526 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002527 // Don't bother evaluating beyond an expression-statement which couldn't
2528 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00002529 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00002530 return ESR_Failed;
2531 return ESR_Succeeded;
2532 }
2533
2534 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002535 return ESR_Failed;
2536
2537 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002538 return ESR_Succeeded;
2539
Richard Smithd9f663b2013-04-22 15:31:51 +00002540 case Stmt::DeclStmtClass: {
2541 const DeclStmt *DS = cast<DeclStmt>(S);
2542 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2543 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2544 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2545 return ESR_Failed;
2546 return ESR_Succeeded;
2547 }
2548
Richard Smith357362d2011-12-13 06:39:58 +00002549 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002550 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002551 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002552 return ESR_Failed;
2553 return ESR_Returned;
2554 }
Richard Smith254a73d2011-10-28 22:34:42 +00002555
2556 case Stmt::CompoundStmtClass: {
2557 const CompoundStmt *CS = cast<CompoundStmt>(S);
2558 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2559 BE = CS->body_end(); BI != BE; ++BI) {
2560 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2561 if (ESR != ESR_Succeeded)
2562 return ESR;
2563 }
2564 return ESR_Succeeded;
2565 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002566
2567 case Stmt::IfStmtClass: {
2568 const IfStmt *IS = cast<IfStmt>(S);
2569
2570 // Evaluate the condition, as either a var decl or as an expression.
2571 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00002572 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00002573 return ESR_Failed;
2574
2575 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2576 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2577 if (ESR != ESR_Succeeded)
2578 return ESR;
2579 }
2580 return ESR_Succeeded;
2581 }
Richard Smith4e18ca52013-05-06 05:56:11 +00002582
2583 case Stmt::WhileStmtClass: {
2584 const WhileStmt *WS = cast<WhileStmt>(S);
2585 while (true) {
2586 bool Continue;
2587 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
2588 Continue))
2589 return ESR_Failed;
2590 if (!Continue)
2591 break;
2592
2593 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
2594 if (ESR != ESR_Continue)
2595 return ESR;
2596 }
2597 return ESR_Succeeded;
2598 }
2599
2600 case Stmt::DoStmtClass: {
2601 const DoStmt *DS = cast<DoStmt>(S);
2602 bool Continue;
2603 do {
2604 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody());
2605 if (ESR != ESR_Continue)
2606 return ESR;
2607
2608 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
2609 return ESR_Failed;
2610 } while (Continue);
2611 return ESR_Succeeded;
2612 }
2613
2614 case Stmt::ForStmtClass: {
2615 const ForStmt *FS = cast<ForStmt>(S);
2616 if (FS->getInit()) {
2617 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
2618 if (ESR != ESR_Succeeded)
2619 return ESR;
2620 }
2621 while (true) {
2622 bool Continue = true;
2623 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
2624 FS->getCond(), Continue))
2625 return ESR_Failed;
2626 if (!Continue)
2627 break;
2628
2629 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2630 if (ESR != ESR_Continue)
2631 return ESR;
2632
2633 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2634 return ESR_Failed;
2635 }
2636 return ESR_Succeeded;
2637 }
2638
2639 case Stmt::ContinueStmtClass:
2640 return ESR_Continue;
2641
2642 case Stmt::BreakStmtClass:
2643 return ESR_Break;
Richard Smith254a73d2011-10-28 22:34:42 +00002644 }
2645}
2646
Richard Smithcc36f692011-12-22 02:22:31 +00002647/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2648/// default constructor. If so, we'll fold it whether or not it's marked as
2649/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2650/// so we need special handling.
2651static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002652 const CXXConstructorDecl *CD,
2653 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002654 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2655 return false;
2656
Richard Smith66e05fe2012-01-18 05:21:49 +00002657 // Value-initialization does not call a trivial default constructor, so such a
2658 // call is a core constant expression whether or not the constructor is
2659 // constexpr.
2660 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002661 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002662 // FIXME: If DiagDecl is an implicitly-declared special member function,
2663 // we should be much more explicit about why it's not constexpr.
2664 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2665 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2666 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002667 } else {
2668 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2669 }
2670 }
2671 return true;
2672}
2673
Richard Smith357362d2011-12-13 06:39:58 +00002674/// CheckConstexprFunction - Check that a function can be called in a constant
2675/// expression.
2676static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2677 const FunctionDecl *Declaration,
2678 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002679 // Potential constant expressions can contain calls to declared, but not yet
2680 // defined, constexpr functions.
2681 if (Info.CheckingPotentialConstantExpression && !Definition &&
2682 Declaration->isConstexpr())
2683 return false;
2684
Richard Smith357362d2011-12-13 06:39:58 +00002685 // Can we evaluate this function call?
2686 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2687 return true;
2688
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002689 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002690 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002691 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2692 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002693 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2694 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2695 << DiagDecl;
2696 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2697 } else {
2698 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2699 }
2700 return false;
2701}
2702
Richard Smithd62306a2011-11-10 06:34:14 +00002703namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002704typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002705}
2706
2707/// EvaluateArgs - Evaluate the arguments to a function call.
2708static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2709 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002710 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002711 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002712 I != E; ++I) {
2713 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2714 // If we're checking for a potential constant expression, evaluate all
2715 // initializers even if some of them fail.
2716 if (!Info.keepEvaluatingAfterFailure())
2717 return false;
2718 Success = false;
2719 }
2720 }
2721 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002722}
2723
Richard Smith254a73d2011-10-28 22:34:42 +00002724/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002725static bool HandleFunctionCall(SourceLocation CallLoc,
2726 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002727 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002728 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002729 ArgVector ArgValues(Args.size());
2730 if (!EvaluateArgs(Args, ArgValues, Info))
2731 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002732
Richard Smith253c2a32012-01-27 01:14:48 +00002733 if (!Info.CheckCallLimit(CallLoc))
2734 return false;
2735
2736 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd9f663b2013-04-22 15:31:51 +00002737 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00002738 if (ESR == ESR_Succeeded) {
2739 if (Callee->getResultType()->isVoidType())
2740 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002741 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00002742 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002743 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00002744}
2745
Richard Smithd62306a2011-11-10 06:34:14 +00002746/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002747static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002748 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002749 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002750 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002751 ArgVector ArgValues(Args.size());
2752 if (!EvaluateArgs(Args, ArgValues, Info))
2753 return false;
2754
Richard Smith253c2a32012-01-27 01:14:48 +00002755 if (!Info.CheckCallLimit(CallLoc))
2756 return false;
2757
Richard Smith3607ffe2012-02-13 03:54:03 +00002758 const CXXRecordDecl *RD = Definition->getParent();
2759 if (RD->getNumVBases()) {
2760 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2761 return false;
2762 }
2763
Richard Smith253c2a32012-01-27 01:14:48 +00002764 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002765
2766 // If it's a delegating constructor, just delegate.
2767 if (Definition->isDelegatingConstructor()) {
2768 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00002769 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
2770 return false;
2771 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002772 }
2773
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002774 // For a trivial copy or move constructor, perform an APValue copy. This is
2775 // essential for unions, where the operations performed by the constructor
2776 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002777 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002778 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2779 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002780 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002781 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00002782 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00002783 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002784 }
2785
2786 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002787 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002788 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2789 std::distance(RD->field_begin(), RD->field_end()));
2790
John McCalld7bca762012-05-01 00:38:49 +00002791 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002792 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2793
Richard Smith253c2a32012-01-27 01:14:48 +00002794 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002795 unsigned BasesSeen = 0;
2796#ifndef NDEBUG
2797 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2798#endif
2799 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2800 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002801 LValue Subobject = This;
2802 APValue *Value = &Result;
2803
2804 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002805 if ((*I)->isBaseInitializer()) {
2806 QualType BaseType((*I)->getBaseClass(), 0);
2807#ifndef NDEBUG
2808 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002809 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002810 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2811 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2812 "base class initializers not in expected order");
2813 ++BaseIt;
2814#endif
John McCalld7bca762012-05-01 00:38:49 +00002815 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2816 BaseType->getAsCXXRecordDecl(), &Layout))
2817 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002818 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002819 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002820 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2821 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002822 if (RD->isUnion()) {
2823 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002824 Value = &Result.getUnionValue();
2825 } else {
2826 Value = &Result.getStructField(FD->getFieldIndex());
2827 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002828 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002829 // Walk the indirect field decl's chain to find the object to initialize,
2830 // and make sure we've initialized every step along it.
2831 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2832 CE = IFD->chain_end();
2833 C != CE; ++C) {
2834 FieldDecl *FD = cast<FieldDecl>(*C);
2835 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2836 // Switch the union field if it differs. This happens if we had
2837 // preceding zero-initialization, and we're now initializing a union
2838 // subobject other than the first.
2839 // FIXME: In this case, the values of the other subobjects are
2840 // specified, since zero-initialization sets all padding bits to zero.
2841 if (Value->isUninit() ||
2842 (Value->isUnion() && Value->getUnionField() != FD)) {
2843 if (CD->isUnion())
2844 *Value = APValue(FD);
2845 else
2846 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2847 std::distance(CD->field_begin(), CD->field_end()));
2848 }
John McCalld7bca762012-05-01 00:38:49 +00002849 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2850 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002851 if (CD->isUnion())
2852 Value = &Value->getUnionValue();
2853 else
2854 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002855 }
Richard Smithd62306a2011-11-10 06:34:14 +00002856 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002857 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002858 }
Richard Smith253c2a32012-01-27 01:14:48 +00002859
Richard Smithb228a862012-02-15 02:18:13 +00002860 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2861 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002862 ? CCEK_Constant : CCEK_MemberInit)) {
2863 // If we're checking for a potential constant expression, evaluate all
2864 // initializers even if some of them fail.
2865 if (!Info.keepEvaluatingAfterFailure())
2866 return false;
2867 Success = false;
2868 }
Richard Smithd62306a2011-11-10 06:34:14 +00002869 }
2870
Richard Smithd9f663b2013-04-22 15:31:51 +00002871 return Success &&
2872 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002873}
2874
Eli Friedman9a156e52008-11-12 09:44:48 +00002875//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002876// Generic Evaluation
2877//===----------------------------------------------------------------------===//
2878namespace {
2879
Richard Smithf57d8cb2011-12-09 22:58:01 +00002880// FIXME: RetTy is always bool. Remove it.
2881template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002882class ExprEvaluatorBase
2883 : public ConstStmtVisitor<Derived, RetTy> {
2884private:
Richard Smith2e312c82012-03-03 22:46:17 +00002885 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002886 return static_cast<Derived*>(this)->Success(V, E);
2887 }
Richard Smithfddd3842011-12-30 21:15:51 +00002888 RetTy DerivedZeroInitialization(const Expr *E) {
2889 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002890 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002891
Richard Smith17100ba2012-02-16 02:46:34 +00002892 // Check whether a conditional operator with a non-constant condition is a
2893 // potential constant expression. If neither arm is a potential constant
2894 // expression, then the conditional operator is not either.
2895 template<typename ConditionalOperator>
2896 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2897 assert(Info.CheckingPotentialConstantExpression);
2898
2899 // Speculatively evaluate both arms.
2900 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002901 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002902 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2903
2904 StmtVisitorTy::Visit(E->getFalseExpr());
2905 if (Diag.empty())
2906 return;
2907
2908 Diag.clear();
2909 StmtVisitorTy::Visit(E->getTrueExpr());
2910 if (Diag.empty())
2911 return;
2912 }
2913
2914 Error(E, diag::note_constexpr_conditional_never_const);
2915 }
2916
2917
2918 template<typename ConditionalOperator>
2919 bool HandleConditionalOperator(const ConditionalOperator *E) {
2920 bool BoolResult;
2921 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2922 if (Info.CheckingPotentialConstantExpression)
2923 CheckPotentialConstantConditional(E);
2924 return false;
2925 }
2926
2927 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2928 return StmtVisitorTy::Visit(EvalExpr);
2929 }
2930
Peter Collingbournee9200682011-05-13 03:29:01 +00002931protected:
2932 EvalInfo &Info;
2933 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2934 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2935
Richard Smith92b1ce02011-12-12 09:28:41 +00002936 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002937 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002938 }
2939
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002940 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2941
2942public:
2943 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2944
2945 EvalInfo &getEvalInfo() { return Info; }
2946
Richard Smithf57d8cb2011-12-09 22:58:01 +00002947 /// Report an evaluation error. This should only be called when an error is
2948 /// first discovered. When propagating an error, just return false.
2949 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002950 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002951 return false;
2952 }
2953 bool Error(const Expr *E) {
2954 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2955 }
2956
Peter Collingbournee9200682011-05-13 03:29:01 +00002957 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002958 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002959 }
2960 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002961 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002962 }
2963
2964 RetTy VisitParenExpr(const ParenExpr *E)
2965 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2966 RetTy VisitUnaryExtension(const UnaryOperator *E)
2967 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2968 RetTy VisitUnaryPlus(const UnaryOperator *E)
2969 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2970 RetTy VisitChooseExpr(const ChooseExpr *E)
2971 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2972 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2973 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002974 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2975 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002976 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2977 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00002978 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
2979 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002980 // We cannot create any objects for which cleanups are required, so there is
2981 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2982 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2983 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002984
Richard Smith6d6ecc32011-12-12 12:46:16 +00002985 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2986 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2987 return static_cast<Derived*>(this)->VisitCastExpr(E);
2988 }
2989 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2990 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2991 return static_cast<Derived*>(this)->VisitCastExpr(E);
2992 }
2993
Richard Smith027bf112011-11-17 22:56:20 +00002994 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2995 switch (E->getOpcode()) {
2996 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002997 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002998
2999 case BO_Comma:
3000 VisitIgnoredValue(E->getLHS());
3001 return StmtVisitorTy::Visit(E->getRHS());
3002
3003 case BO_PtrMemD:
3004 case BO_PtrMemI: {
3005 LValue Obj;
3006 if (!HandleMemberPointerAccess(Info, E, Obj))
3007 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003008 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003009 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003010 return false;
3011 return DerivedSuccess(Result, E);
3012 }
3013 }
3014 }
3015
Peter Collingbournee9200682011-05-13 03:29:01 +00003016 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003017 // Evaluate and cache the common expression. We treat it as a temporary,
3018 // even though it's not quite the same thing.
3019 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3020 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003021 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003022
Richard Smith17100ba2012-02-16 02:46:34 +00003023 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003024 }
3025
3026 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003027 bool IsBcpCall = false;
3028 // If the condition (ignoring parens) is a __builtin_constant_p call,
3029 // the result is a constant expression if it can be folded without
3030 // side-effects. This is an important GNU extension. See GCC PR38377
3031 // for discussion.
3032 if (const CallExpr *CallCE =
3033 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3034 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3035 IsBcpCall = true;
3036
3037 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3038 // constant expression; we can't check whether it's potentially foldable.
3039 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3040 return false;
3041
3042 FoldConstant Fold(Info);
3043
Richard Smith17100ba2012-02-16 02:46:34 +00003044 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003045 return false;
3046
3047 if (IsBcpCall)
3048 Fold.Fold(Info);
3049
3050 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003051 }
3052
3053 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003054 APValue &Value = Info.CurrentCall->Temporaries[E];
3055 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003056 const Expr *Source = E->getSourceExpr();
3057 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003058 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003059 if (Source == E) { // sanity checking.
3060 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003061 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003062 }
3063 return StmtVisitorTy::Visit(Source);
3064 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003065 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003066 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003067
Richard Smith254a73d2011-10-28 22:34:42 +00003068 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003069 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003070 QualType CalleeType = Callee->getType();
3071
Richard Smith254a73d2011-10-28 22:34:42 +00003072 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003073 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003074 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003075 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003076
Richard Smithe97cbd72011-11-11 04:05:33 +00003077 // Extract function decl and 'this' pointer from the callee.
3078 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003079 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003080 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3081 // Explicit bound member calls, such as x.f() or p->g();
3082 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003083 return false;
3084 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003085 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003086 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003087 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3088 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003089 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3090 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003091 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003092 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003093 return Error(Callee);
3094
3095 FD = dyn_cast<FunctionDecl>(Member);
3096 if (!FD)
3097 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003098 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003099 LValue Call;
3100 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003101 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003102
Richard Smitha8105bc2012-01-06 16:39:00 +00003103 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003104 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003105 FD = dyn_cast_or_null<FunctionDecl>(
3106 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003107 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003108 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003109
3110 // Overloaded operator calls to member functions are represented as normal
3111 // calls with '*this' as the first argument.
3112 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3113 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003114 // FIXME: When selecting an implicit conversion for an overloaded
3115 // operator delete, we sometimes try to evaluate calls to conversion
3116 // operators without a 'this' parameter!
3117 if (Args.empty())
3118 return Error(E);
3119
Richard Smithe97cbd72011-11-11 04:05:33 +00003120 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3121 return false;
3122 This = &ThisVal;
3123 Args = Args.slice(1);
3124 }
3125
3126 // Don't call function pointers which have been cast to some other type.
3127 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003128 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003129 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003130 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003131
Richard Smith47b34932012-02-01 02:39:43 +00003132 if (This && !This->checkSubobject(Info, E, CSK_This))
3133 return false;
3134
Richard Smith3607ffe2012-02-13 03:54:03 +00003135 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3136 // calls to such functions in constant expressions.
3137 if (This && !HasQualifier &&
3138 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3139 return Error(E, diag::note_constexpr_virtual_call);
3140
Richard Smith357362d2011-12-13 06:39:58 +00003141 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003142 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003143 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003144
Richard Smith357362d2011-12-13 06:39:58 +00003145 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003146 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3147 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003148 return false;
3149
Richard Smithb228a862012-02-15 02:18:13 +00003150 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003151 }
3152
Richard Smith11562c52011-10-28 17:51:58 +00003153 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3154 return StmtVisitorTy::Visit(E->getInitializer());
3155 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003156 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003157 if (E->getNumInits() == 0)
3158 return DerivedZeroInitialization(E);
3159 if (E->getNumInits() == 1)
3160 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003161 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003162 }
3163 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003164 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003165 }
3166 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003167 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003168 }
Richard Smith027bf112011-11-17 22:56:20 +00003169 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003170 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003171 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003172
Richard Smithd62306a2011-11-10 06:34:14 +00003173 /// A member expression where the object is a prvalue is itself a prvalue.
3174 RetTy VisitMemberExpr(const MemberExpr *E) {
3175 assert(!E->isArrow() && "missing call to bound member function?");
3176
Richard Smith2e312c82012-03-03 22:46:17 +00003177 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003178 if (!Evaluate(Val, Info, E->getBase()))
3179 return false;
3180
3181 QualType BaseTy = E->getBase()->getType();
3182
3183 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003184 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003185 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003186 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003187 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3188
Richard Smith3229b742013-05-05 21:17:10 +00003189 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003190 SubobjectDesignator Designator(BaseTy);
3191 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003192
Richard Smith3229b742013-05-05 21:17:10 +00003193 APValue Result;
3194 return extractSubobject(Info, E, Obj, Designator, Result) &&
3195 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003196 }
3197
Richard Smith11562c52011-10-28 17:51:58 +00003198 RetTy VisitCastExpr(const CastExpr *E) {
3199 switch (E->getCastKind()) {
3200 default:
3201 break;
3202
David Chisnallfa35df62012-01-16 17:27:18 +00003203 case CK_AtomicToNonAtomic:
3204 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003205 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003206 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003207 return StmtVisitorTy::Visit(E->getSubExpr());
3208
3209 case CK_LValueToRValue: {
3210 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003211 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3212 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003213 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003214 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003215 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003216 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003217 return false;
3218 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003219 }
3220 }
3221
Richard Smithf57d8cb2011-12-09 22:58:01 +00003222 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003223 }
3224
Richard Smith243ef902013-05-05 23:31:59 +00003225 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3226 return VisitUnaryPostIncDec(UO);
3227 }
3228 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3229 return VisitUnaryPostIncDec(UO);
3230 }
3231 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3232 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3233 return Error(UO);
3234
3235 LValue LVal;
3236 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3237 return false;
3238 APValue RVal;
3239 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3240 UO->isIncrementOp(), &RVal))
3241 return false;
3242 return DerivedSuccess(RVal, UO);
3243 }
3244
Richard Smith4a678122011-10-24 18:44:57 +00003245 /// Visit a value which is evaluated, but whose value is ignored.
3246 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003247 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003248 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003249};
3250
3251}
3252
3253//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003254// Common base class for lvalue and temporary evaluation.
3255//===----------------------------------------------------------------------===//
3256namespace {
3257template<class Derived>
3258class LValueExprEvaluatorBase
3259 : public ExprEvaluatorBase<Derived, bool> {
3260protected:
3261 LValue &Result;
3262 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3263 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3264
3265 bool Success(APValue::LValueBase B) {
3266 Result.set(B);
3267 return true;
3268 }
3269
3270public:
3271 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3272 ExprEvaluatorBaseTy(Info), Result(Result) {}
3273
Richard Smith2e312c82012-03-03 22:46:17 +00003274 bool Success(const APValue &V, const Expr *E) {
3275 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003276 return true;
3277 }
Richard Smith027bf112011-11-17 22:56:20 +00003278
Richard Smith027bf112011-11-17 22:56:20 +00003279 bool VisitMemberExpr(const MemberExpr *E) {
3280 // Handle non-static data members.
3281 QualType BaseTy;
3282 if (E->isArrow()) {
3283 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3284 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003285 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003286 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003287 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003288 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3289 return false;
3290 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003291 } else {
3292 if (!this->Visit(E->getBase()))
3293 return false;
3294 BaseTy = E->getBase()->getType();
3295 }
Richard Smith027bf112011-11-17 22:56:20 +00003296
Richard Smith1b78b3d2012-01-25 22:15:11 +00003297 const ValueDecl *MD = E->getMemberDecl();
3298 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3299 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3300 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3301 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003302 if (!HandleLValueMember(this->Info, E, Result, FD))
3303 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003304 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003305 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3306 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003307 } else
3308 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003309
Richard Smith1b78b3d2012-01-25 22:15:11 +00003310 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003311 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003312 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003313 RefValue))
3314 return false;
3315 return Success(RefValue, E);
3316 }
3317 return true;
3318 }
3319
3320 bool VisitBinaryOperator(const BinaryOperator *E) {
3321 switch (E->getOpcode()) {
3322 default:
3323 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3324
3325 case BO_PtrMemD:
3326 case BO_PtrMemI:
3327 return HandleMemberPointerAccess(this->Info, E, Result);
3328 }
3329 }
3330
3331 bool VisitCastExpr(const CastExpr *E) {
3332 switch (E->getCastKind()) {
3333 default:
3334 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3335
3336 case CK_DerivedToBase:
3337 case CK_UncheckedDerivedToBase: {
3338 if (!this->Visit(E->getSubExpr()))
3339 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003340
3341 // Now figure out the necessary offset to add to the base LV to get from
3342 // the derived class to the base class.
3343 QualType Type = E->getSubExpr()->getType();
3344
3345 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3346 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003347 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003348 *PathI))
3349 return false;
3350 Type = (*PathI)->getType();
3351 }
3352
3353 return true;
3354 }
3355 }
3356 }
3357};
3358}
3359
3360//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003361// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003362//
3363// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3364// function designators (in C), decl references to void objects (in C), and
3365// temporaries (if building with -Wno-address-of-temporary).
3366//
3367// LValue evaluation produces values comprising a base expression of one of the
3368// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003369// - Declarations
3370// * VarDecl
3371// * FunctionDecl
3372// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003373// * CompoundLiteralExpr in C
3374// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003375// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003376// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003377// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003378// * ObjCEncodeExpr
3379// * AddrLabelExpr
3380// * BlockExpr
3381// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003382// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003383// * Any Expr, with a CallIndex indicating the function in which the temporary
3384// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003385// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003386//===----------------------------------------------------------------------===//
3387namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003388class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003389 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003390public:
Richard Smith027bf112011-11-17 22:56:20 +00003391 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3392 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003393
Richard Smith11562c52011-10-28 17:51:58 +00003394 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003395 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003396
Peter Collingbournee9200682011-05-13 03:29:01 +00003397 bool VisitDeclRefExpr(const DeclRefExpr *E);
3398 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003399 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003400 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3401 bool VisitMemberExpr(const MemberExpr *E);
3402 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3403 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003404 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003405 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003406 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3407 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003408 bool VisitUnaryReal(const UnaryOperator *E);
3409 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003410 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3411 return VisitUnaryPreIncDec(UO);
3412 }
3413 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3414 return VisitUnaryPreIncDec(UO);
3415 }
Richard Smith3229b742013-05-05 21:17:10 +00003416 bool VisitBinAssign(const BinaryOperator *BO);
3417 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003418
Peter Collingbournee9200682011-05-13 03:29:01 +00003419 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003420 switch (E->getCastKind()) {
3421 default:
Richard Smith027bf112011-11-17 22:56:20 +00003422 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003423
Eli Friedmance3e02a2011-10-11 00:13:24 +00003424 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003425 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003426 if (!Visit(E->getSubExpr()))
3427 return false;
3428 Result.Designator.setInvalid();
3429 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003430
Richard Smith027bf112011-11-17 22:56:20 +00003431 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003432 if (!Visit(E->getSubExpr()))
3433 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003434 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003435 }
3436 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003437};
3438} // end anonymous namespace
3439
Richard Smith11562c52011-10-28 17:51:58 +00003440/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003441/// expressions which are not glvalues, in two cases:
3442/// * function designators in C, and
3443/// * "extern void" objects
3444static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3445 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3446 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003447 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003448}
3449
Peter Collingbournee9200682011-05-13 03:29:01 +00003450bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003451 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3452 return Success(FD);
3453 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003454 return VisitVarDecl(E, VD);
3455 return Error(E);
3456}
Richard Smith733237d2011-10-24 23:14:33 +00003457
Richard Smith11562c52011-10-28 17:51:58 +00003458bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003459 CallStackFrame *Frame = 0;
3460 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3461 Frame = Info.CurrentCall;
3462
Richard Smithfec09922011-11-01 16:57:24 +00003463 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003464 if (Frame) {
3465 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003466 return true;
3467 }
Richard Smithce40ad62011-11-12 22:28:03 +00003468 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003469 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003470
Richard Smith3229b742013-05-05 21:17:10 +00003471 APValue *V;
3472 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003473 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003474 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003475}
3476
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003477bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3478 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003479 if (E->getType()->isRecordType())
3480 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003481
Richard Smithb228a862012-02-15 02:18:13 +00003482 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003483 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3484 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003485}
3486
Peter Collingbournee9200682011-05-13 03:29:01 +00003487bool
3488LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003489 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3490 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3491 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003492 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003493}
3494
Richard Smith6e525142011-12-27 12:18:28 +00003495bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003496 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003497 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003498
3499 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3500 << E->getExprOperand()->getType()
3501 << E->getExprOperand()->getSourceRange();
3502 return false;
Richard Smith6e525142011-12-27 12:18:28 +00003503}
3504
Francois Pichet0066db92012-04-16 04:08:35 +00003505bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3506 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00003507}
Francois Pichet0066db92012-04-16 04:08:35 +00003508
Peter Collingbournee9200682011-05-13 03:29:01 +00003509bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003510 // Handle static data members.
3511 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3512 VisitIgnoredValue(E->getBase());
3513 return VisitVarDecl(E, VD);
3514 }
3515
Richard Smith254a73d2011-10-28 22:34:42 +00003516 // Handle static member functions.
3517 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3518 if (MD->isStatic()) {
3519 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003520 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003521 }
3522 }
3523
Richard Smithd62306a2011-11-10 06:34:14 +00003524 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003525 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003526}
3527
Peter Collingbournee9200682011-05-13 03:29:01 +00003528bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003529 // FIXME: Deal with vectors as array subscript bases.
3530 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003531 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003532
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003533 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003534 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003535
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003536 APSInt Index;
3537 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003538 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003539 int64_t IndexValue
3540 = Index.isSigned() ? Index.getSExtValue()
3541 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003542
Richard Smitha8105bc2012-01-06 16:39:00 +00003543 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003544}
Eli Friedman9a156e52008-11-12 09:44:48 +00003545
Peter Collingbournee9200682011-05-13 03:29:01 +00003546bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003547 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003548}
3549
Richard Smith66c96992012-02-18 22:04:06 +00003550bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3551 if (!Visit(E->getSubExpr()))
3552 return false;
3553 // __real is a no-op on scalar lvalues.
3554 if (E->getSubExpr()->getType()->isAnyComplexType())
3555 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3556 return true;
3557}
3558
3559bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3560 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3561 "lvalue __imag__ on scalar?");
3562 if (!Visit(E->getSubExpr()))
3563 return false;
3564 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3565 return true;
3566}
3567
Richard Smith243ef902013-05-05 23:31:59 +00003568bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
3569 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003570 return Error(UO);
3571
3572 if (!this->Visit(UO->getSubExpr()))
3573 return false;
3574
Richard Smith243ef902013-05-05 23:31:59 +00003575 return handleIncDec(
3576 this->Info, UO, Result, UO->getSubExpr()->getType(),
3577 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00003578}
3579
3580bool LValueExprEvaluator::VisitCompoundAssignOperator(
3581 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00003582 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003583 return Error(CAO);
3584
Richard Smith3229b742013-05-05 21:17:10 +00003585 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00003586
3587 // The overall lvalue result is the result of evaluating the LHS.
3588 if (!this->Visit(CAO->getLHS())) {
3589 if (Info.keepEvaluatingAfterFailure())
3590 Evaluate(RHS, this->Info, CAO->getRHS());
3591 return false;
3592 }
3593
Richard Smith3229b742013-05-05 21:17:10 +00003594 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
3595 return false;
3596
3597 // FIXME:
3598 //return handleCompoundAssignment(
3599 // this->Info, CAO,
3600 // Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
3601 // RHS, CAO->getRHS()->getType(),
3602 // CAO->getOpForCompoundAssignment(CAO->getOpcode()),
3603 // CAO->getComputationResultType());
3604 return Error(CAO);
3605}
3606
3607bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00003608 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3609 return Error(E);
3610
Richard Smith3229b742013-05-05 21:17:10 +00003611 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00003612
3613 if (!this->Visit(E->getLHS())) {
3614 if (Info.keepEvaluatingAfterFailure())
3615 Evaluate(NewVal, this->Info, E->getRHS());
3616 return false;
3617 }
3618
Richard Smith3229b742013-05-05 21:17:10 +00003619 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3620 return false;
Richard Smith243ef902013-05-05 23:31:59 +00003621
3622 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00003623 NewVal);
3624}
3625
Eli Friedman9a156e52008-11-12 09:44:48 +00003626//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003627// Pointer Evaluation
3628//===----------------------------------------------------------------------===//
3629
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003630namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003631class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003632 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003633 LValue &Result;
3634
Peter Collingbournee9200682011-05-13 03:29:01 +00003635 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003636 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003637 return true;
3638 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003639public:
Mike Stump11289f42009-09-09 15:08:12 +00003640
John McCall45d55e42010-05-07 21:00:08 +00003641 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003642 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003643
Richard Smith2e312c82012-03-03 22:46:17 +00003644 bool Success(const APValue &V, const Expr *E) {
3645 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00003646 return true;
3647 }
Richard Smithfddd3842011-12-30 21:15:51 +00003648 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003649 return Success((Expr*)0);
3650 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003651
John McCall45d55e42010-05-07 21:00:08 +00003652 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003653 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003654 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003655 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003656 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003657 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003658 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003659 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003660 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003661 bool VisitCallExpr(const CallExpr *E);
3662 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003663 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003664 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003665 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003666 }
Richard Smithd62306a2011-11-10 06:34:14 +00003667 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3668 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003669 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003670 Result = *Info.CurrentCall->This;
3671 return true;
3672 }
John McCallc07a0c72011-02-17 10:25:35 +00003673
Eli Friedman449fe542009-03-23 04:56:01 +00003674 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003675};
Chris Lattner05706e882008-07-11 18:11:29 +00003676} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003677
John McCall45d55e42010-05-07 21:00:08 +00003678static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003679 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003680 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003681}
3682
John McCall45d55e42010-05-07 21:00:08 +00003683bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003684 if (E->getOpcode() != BO_Add &&
3685 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003686 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003687
Chris Lattner05706e882008-07-11 18:11:29 +00003688 const Expr *PExp = E->getLHS();
3689 const Expr *IExp = E->getRHS();
3690 if (IExp->getType()->isPointerType())
3691 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003692
Richard Smith253c2a32012-01-27 01:14:48 +00003693 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3694 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003695 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003696
John McCall45d55e42010-05-07 21:00:08 +00003697 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003698 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003699 return false;
3700 int64_t AdditionalOffset
3701 = Offset.isSigned() ? Offset.getSExtValue()
3702 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003703 if (E->getOpcode() == BO_Sub)
3704 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003705
Ted Kremenek28831752012-08-23 20:46:57 +00003706 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003707 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3708 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003709}
Eli Friedman9a156e52008-11-12 09:44:48 +00003710
John McCall45d55e42010-05-07 21:00:08 +00003711bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3712 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003713}
Mike Stump11289f42009-09-09 15:08:12 +00003714
Peter Collingbournee9200682011-05-13 03:29:01 +00003715bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3716 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003717
Eli Friedman847a2bc2009-12-27 05:43:15 +00003718 switch (E->getCastKind()) {
3719 default:
3720 break;
3721
John McCalle3027922010-08-25 11:45:40 +00003722 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003723 case CK_CPointerToObjCPointerCast:
3724 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003725 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003726 if (!Visit(SubExpr))
3727 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003728 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3729 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3730 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003731 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003732 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003733 if (SubExpr->getType()->isVoidPointerType())
3734 CCEDiag(E, diag::note_constexpr_invalid_cast)
3735 << 3 << SubExpr->getType();
3736 else
3737 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3738 }
Richard Smith96e0c102011-11-04 02:25:55 +00003739 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003740
Anders Carlsson18275092010-10-31 20:41:46 +00003741 case CK_DerivedToBase:
3742 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003743 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003744 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003745 if (!Result.Base && Result.Offset.isZero())
3746 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003747
Richard Smithd62306a2011-11-10 06:34:14 +00003748 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003749 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003750 QualType Type =
3751 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003752
Richard Smithd62306a2011-11-10 06:34:14 +00003753 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003754 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003755 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3756 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003757 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003758 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003759 }
3760
Anders Carlsson18275092010-10-31 20:41:46 +00003761 return true;
3762 }
3763
Richard Smith027bf112011-11-17 22:56:20 +00003764 case CK_BaseToDerived:
3765 if (!Visit(E->getSubExpr()))
3766 return false;
3767 if (!Result.Base && Result.Offset.isZero())
3768 return true;
3769 return HandleBaseToDerivedCast(Info, E, Result);
3770
Richard Smith0b0a0b62011-10-29 20:57:55 +00003771 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003772 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003773 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003774
John McCalle3027922010-08-25 11:45:40 +00003775 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003776 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3777
Richard Smith2e312c82012-03-03 22:46:17 +00003778 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003779 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003780 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003781
John McCall45d55e42010-05-07 21:00:08 +00003782 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003783 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3784 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003785 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003786 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003787 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003788 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003789 return true;
3790 } else {
3791 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003792 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003793 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003794 }
3795 }
John McCalle3027922010-08-25 11:45:40 +00003796 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003797 if (SubExpr->isGLValue()) {
3798 if (!EvaluateLValue(SubExpr, Result, Info))
3799 return false;
3800 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003801 Result.set(SubExpr, Info.CurrentCall->Index);
3802 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3803 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003804 return false;
3805 }
Richard Smith96e0c102011-11-04 02:25:55 +00003806 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003807 if (const ConstantArrayType *CAT
3808 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3809 Result.addArray(Info, E, CAT);
3810 else
3811 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003812 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003813
John McCalle3027922010-08-25 11:45:40 +00003814 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003815 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003816 }
3817
Richard Smith11562c52011-10-28 17:51:58 +00003818 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003819}
Chris Lattner05706e882008-07-11 18:11:29 +00003820
Peter Collingbournee9200682011-05-13 03:29:01 +00003821bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003822 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003823 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003824
Peter Collingbournee9200682011-05-13 03:29:01 +00003825 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003826}
Chris Lattner05706e882008-07-11 18:11:29 +00003827
3828//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003829// Member Pointer Evaluation
3830//===----------------------------------------------------------------------===//
3831
3832namespace {
3833class MemberPointerExprEvaluator
3834 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3835 MemberPtr &Result;
3836
3837 bool Success(const ValueDecl *D) {
3838 Result = MemberPtr(D);
3839 return true;
3840 }
3841public:
3842
3843 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3844 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3845
Richard Smith2e312c82012-03-03 22:46:17 +00003846 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003847 Result.setFrom(V);
3848 return true;
3849 }
Richard Smithfddd3842011-12-30 21:15:51 +00003850 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003851 return Success((const ValueDecl*)0);
3852 }
3853
3854 bool VisitCastExpr(const CastExpr *E);
3855 bool VisitUnaryAddrOf(const UnaryOperator *E);
3856};
3857} // end anonymous namespace
3858
3859static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3860 EvalInfo &Info) {
3861 assert(E->isRValue() && E->getType()->isMemberPointerType());
3862 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3863}
3864
3865bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3866 switch (E->getCastKind()) {
3867 default:
3868 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3869
3870 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003871 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003872 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003873
3874 case CK_BaseToDerivedMemberPointer: {
3875 if (!Visit(E->getSubExpr()))
3876 return false;
3877 if (E->path_empty())
3878 return true;
3879 // Base-to-derived member pointer casts store the path in derived-to-base
3880 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3881 // the wrong end of the derived->base arc, so stagger the path by one class.
3882 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3883 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3884 PathI != PathE; ++PathI) {
3885 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3886 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3887 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003888 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003889 }
3890 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3891 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003892 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003893 return true;
3894 }
3895
3896 case CK_DerivedToBaseMemberPointer:
3897 if (!Visit(E->getSubExpr()))
3898 return false;
3899 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3900 PathE = E->path_end(); PathI != PathE; ++PathI) {
3901 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3902 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3903 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003904 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003905 }
3906 return true;
3907 }
3908}
3909
3910bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3911 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3912 // member can be formed.
3913 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3914}
3915
3916//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003917// Record Evaluation
3918//===----------------------------------------------------------------------===//
3919
3920namespace {
3921 class RecordExprEvaluator
3922 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3923 const LValue &This;
3924 APValue &Result;
3925 public:
3926
3927 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3928 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3929
Richard Smith2e312c82012-03-03 22:46:17 +00003930 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003931 Result = V;
3932 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003933 }
Richard Smithfddd3842011-12-30 21:15:51 +00003934 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003935
Richard Smithe97cbd72011-11-11 04:05:33 +00003936 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003937 bool VisitInitListExpr(const InitListExpr *E);
3938 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3939 };
3940}
3941
Richard Smithfddd3842011-12-30 21:15:51 +00003942/// Perform zero-initialization on an object of non-union class type.
3943/// C++11 [dcl.init]p5:
3944/// To zero-initialize an object or reference of type T means:
3945/// [...]
3946/// -- if T is a (possibly cv-qualified) non-union class type,
3947/// each non-static data member and each base-class subobject is
3948/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003949static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3950 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003951 const LValue &This, APValue &Result) {
3952 assert(!RD->isUnion() && "Expected non-union class type");
3953 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3954 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3955 std::distance(RD->field_begin(), RD->field_end()));
3956
John McCalld7bca762012-05-01 00:38:49 +00003957 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003958 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3959
3960 if (CD) {
3961 unsigned Index = 0;
3962 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003963 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00003964 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3965 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003966 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3967 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003968 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00003969 Result.getStructBase(Index)))
3970 return false;
3971 }
3972 }
3973
Richard Smitha8105bc2012-01-06 16:39:00 +00003974 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3975 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00003976 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00003977 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00003978 continue;
3979
3980 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003981 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003982 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003983
David Blaikie2d7c57e2012-04-30 02:36:29 +00003984 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003985 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00003986 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003987 return false;
3988 }
3989
3990 return true;
3991}
3992
3993bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3994 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003995 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003996 if (RD->isUnion()) {
3997 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3998 // object's first non-static named data member is zero-initialized
3999 RecordDecl::field_iterator I = RD->field_begin();
4000 if (I == RD->field_end()) {
4001 Result = APValue((const FieldDecl*)0);
4002 return true;
4003 }
4004
4005 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004006 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004007 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004008 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004009 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004010 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004011 }
4012
Richard Smith5d108602012-02-17 00:44:16 +00004013 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004014 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004015 return false;
4016 }
4017
Richard Smitha8105bc2012-01-06 16:39:00 +00004018 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004019}
4020
Richard Smithe97cbd72011-11-11 04:05:33 +00004021bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4022 switch (E->getCastKind()) {
4023 default:
4024 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4025
4026 case CK_ConstructorConversion:
4027 return Visit(E->getSubExpr());
4028
4029 case CK_DerivedToBase:
4030 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004031 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004032 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004033 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004034 if (!DerivedObject.isStruct())
4035 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004036
4037 // Derived-to-base rvalue conversion: just slice off the derived part.
4038 APValue *Value = &DerivedObject;
4039 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4040 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4041 PathE = E->path_end(); PathI != PathE; ++PathI) {
4042 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4043 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4044 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4045 RD = Base;
4046 }
4047 Result = *Value;
4048 return true;
4049 }
4050 }
4051}
4052
Richard Smithd62306a2011-11-10 06:34:14 +00004053bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004054 // Cannot constant-evaluate std::initializer_list inits.
4055 if (E->initializesStdInitializerList())
4056 return false;
4057
Richard Smithd62306a2011-11-10 06:34:14 +00004058 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004059 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004060 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4061
4062 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004063 const FieldDecl *Field = E->getInitializedFieldInUnion();
4064 Result = APValue(Field);
4065 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004066 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004067
4068 // If the initializer list for a union does not contain any elements, the
4069 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004070 // FIXME: The element should be initialized from an initializer list.
4071 // Is this difference ever observable for initializer lists which
4072 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004073 ImplicitValueInitExpr VIE(Field->getType());
4074 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4075
Richard Smithd62306a2011-11-10 06:34:14 +00004076 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004077 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4078 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004079
4080 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4081 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4082 isa<CXXDefaultInitExpr>(InitExpr));
4083
Richard Smithb228a862012-02-15 02:18:13 +00004084 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004085 }
4086
4087 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4088 "initializer list for class with base classes");
4089 Result = APValue(APValue::UninitStruct(), 0,
4090 std::distance(RD->field_begin(), RD->field_end()));
4091 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004092 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004093 for (RecordDecl::field_iterator Field = RD->field_begin(),
4094 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4095 // Anonymous bit-fields are not considered members of the class for
4096 // purposes of aggregate initialization.
4097 if (Field->isUnnamedBitfield())
4098 continue;
4099
4100 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004101
Richard Smith253c2a32012-01-27 01:14:48 +00004102 bool HaveInit = ElementNo < E->getNumInits();
4103
4104 // FIXME: Diagnostics here should point to the end of the initializer
4105 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004106 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004107 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004108 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004109
4110 // Perform an implicit value-initialization for members beyond the end of
4111 // the initializer list.
4112 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004113 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004114
Richard Smith852c9db2013-04-20 22:23:05 +00004115 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4116 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4117 isa<CXXDefaultInitExpr>(Init));
4118
4119 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4120 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004121 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004122 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004123 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004124 }
4125 }
4126
Richard Smith253c2a32012-01-27 01:14:48 +00004127 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004128}
4129
4130bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4131 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004132 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4133
Richard Smithfddd3842011-12-30 21:15:51 +00004134 bool ZeroInit = E->requiresZeroInitialization();
4135 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004136 // If we've already performed zero-initialization, we're already done.
4137 if (!Result.isUninit())
4138 return true;
4139
Richard Smithfddd3842011-12-30 21:15:51 +00004140 if (ZeroInit)
4141 return ZeroInitialization(E);
4142
Richard Smithcc36f692011-12-22 02:22:31 +00004143 const CXXRecordDecl *RD = FD->getParent();
4144 if (RD->isUnion())
4145 Result = APValue((FieldDecl*)0);
4146 else
4147 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4148 std::distance(RD->field_begin(), RD->field_end()));
4149 return true;
4150 }
4151
Richard Smithd62306a2011-11-10 06:34:14 +00004152 const FunctionDecl *Definition = 0;
4153 FD->getBody(Definition);
4154
Richard Smith357362d2011-12-13 06:39:58 +00004155 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4156 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004157
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004158 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004159 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004160 if (const MaterializeTemporaryExpr *ME
4161 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4162 return Visit(ME->GetTemporaryExpr());
4163
Richard Smithfddd3842011-12-30 21:15:51 +00004164 if (ZeroInit && !ZeroInitialization(E))
4165 return false;
4166
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004167 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004168 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004169 cast<CXXConstructorDecl>(Definition), Info,
4170 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004171}
4172
4173static bool EvaluateRecord(const Expr *E, const LValue &This,
4174 APValue &Result, EvalInfo &Info) {
4175 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004176 "can't evaluate expression as a record rvalue");
4177 return RecordExprEvaluator(Info, This, Result).Visit(E);
4178}
4179
4180//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004181// Temporary Evaluation
4182//
4183// Temporaries are represented in the AST as rvalues, but generally behave like
4184// lvalues. The full-object of which the temporary is a subobject is implicitly
4185// materialized so that a reference can bind to it.
4186//===----------------------------------------------------------------------===//
4187namespace {
4188class TemporaryExprEvaluator
4189 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4190public:
4191 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4192 LValueExprEvaluatorBaseTy(Info, Result) {}
4193
4194 /// Visit an expression which constructs the value of this temporary.
4195 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004196 Result.set(E, Info.CurrentCall->Index);
4197 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004198 }
4199
4200 bool VisitCastExpr(const CastExpr *E) {
4201 switch (E->getCastKind()) {
4202 default:
4203 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4204
4205 case CK_ConstructorConversion:
4206 return VisitConstructExpr(E->getSubExpr());
4207 }
4208 }
4209 bool VisitInitListExpr(const InitListExpr *E) {
4210 return VisitConstructExpr(E);
4211 }
4212 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4213 return VisitConstructExpr(E);
4214 }
4215 bool VisitCallExpr(const CallExpr *E) {
4216 return VisitConstructExpr(E);
4217 }
4218};
4219} // end anonymous namespace
4220
4221/// Evaluate an expression of record type as a temporary.
4222static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004223 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004224 return TemporaryExprEvaluator(Info, Result).Visit(E);
4225}
4226
4227//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004228// Vector Evaluation
4229//===----------------------------------------------------------------------===//
4230
4231namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004232 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004233 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4234 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004235 public:
Mike Stump11289f42009-09-09 15:08:12 +00004236
Richard Smith2d406342011-10-22 21:10:00 +00004237 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4238 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004239
Richard Smith2d406342011-10-22 21:10:00 +00004240 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4241 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4242 // FIXME: remove this APValue copy.
4243 Result = APValue(V.data(), V.size());
4244 return true;
4245 }
Richard Smith2e312c82012-03-03 22:46:17 +00004246 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004247 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004248 Result = V;
4249 return true;
4250 }
Richard Smithfddd3842011-12-30 21:15:51 +00004251 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004252
Richard Smith2d406342011-10-22 21:10:00 +00004253 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004254 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004255 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004256 bool VisitInitListExpr(const InitListExpr *E);
4257 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004258 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004259 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004260 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004261 };
4262} // end anonymous namespace
4263
4264static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004265 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004266 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004267}
4268
Richard Smith2d406342011-10-22 21:10:00 +00004269bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4270 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004271 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004272
Richard Smith161f09a2011-12-06 22:44:34 +00004273 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004274 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004275
Eli Friedmanc757de22011-03-25 00:43:55 +00004276 switch (E->getCastKind()) {
4277 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004278 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004279 if (SETy->isIntegerType()) {
4280 APSInt IntResult;
4281 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004282 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004283 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004284 } else if (SETy->isRealFloatingType()) {
4285 APFloat F(0.0);
4286 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004287 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004288 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004289 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004290 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004291 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004292
4293 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004294 SmallVector<APValue, 4> Elts(NElts, Val);
4295 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004296 }
Eli Friedman803acb32011-12-22 03:51:45 +00004297 case CK_BitCast: {
4298 // Evaluate the operand into an APInt we can extract from.
4299 llvm::APInt SValInt;
4300 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4301 return false;
4302 // Extract the elements
4303 QualType EltTy = VTy->getElementType();
4304 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4305 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4306 SmallVector<APValue, 4> Elts;
4307 if (EltTy->isRealFloatingType()) {
4308 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004309 unsigned FloatEltSize = EltSize;
4310 if (&Sem == &APFloat::x87DoubleExtended)
4311 FloatEltSize = 80;
4312 for (unsigned i = 0; i < NElts; i++) {
4313 llvm::APInt Elt;
4314 if (BigEndian)
4315 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4316 else
4317 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004318 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004319 }
4320 } else if (EltTy->isIntegerType()) {
4321 for (unsigned i = 0; i < NElts; i++) {
4322 llvm::APInt Elt;
4323 if (BigEndian)
4324 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4325 else
4326 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4327 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4328 }
4329 } else {
4330 return Error(E);
4331 }
4332 return Success(Elts, E);
4333 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004334 default:
Richard Smith11562c52011-10-28 17:51:58 +00004335 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004336 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004337}
4338
Richard Smith2d406342011-10-22 21:10:00 +00004339bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004340VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004341 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004342 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004343 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004344
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004345 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004346 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004347
Eli Friedmanb9c71292012-01-03 23:24:20 +00004348 // The number of initializers can be less than the number of
4349 // vector elements. For OpenCL, this can be due to nested vector
4350 // initialization. For GCC compatibility, missing trailing elements
4351 // should be initialized with zeroes.
4352 unsigned CountInits = 0, CountElts = 0;
4353 while (CountElts < NumElements) {
4354 // Handle nested vector initialization.
4355 if (CountInits < NumInits
4356 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4357 APValue v;
4358 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4359 return Error(E);
4360 unsigned vlen = v.getVectorLength();
4361 for (unsigned j = 0; j < vlen; j++)
4362 Elements.push_back(v.getVectorElt(j));
4363 CountElts += vlen;
4364 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004365 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004366 if (CountInits < NumInits) {
4367 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004368 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004369 } else // trailing integer zero.
4370 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4371 Elements.push_back(APValue(sInt));
4372 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004373 } else {
4374 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004375 if (CountInits < NumInits) {
4376 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004377 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004378 } else // trailing float zero.
4379 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4380 Elements.push_back(APValue(f));
4381 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004382 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004383 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004384 }
Richard Smith2d406342011-10-22 21:10:00 +00004385 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004386}
4387
Richard Smith2d406342011-10-22 21:10:00 +00004388bool
Richard Smithfddd3842011-12-30 21:15:51 +00004389VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004390 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004391 QualType EltTy = VT->getElementType();
4392 APValue ZeroElement;
4393 if (EltTy->isIntegerType())
4394 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4395 else
4396 ZeroElement =
4397 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4398
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004399 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004400 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004401}
4402
Richard Smith2d406342011-10-22 21:10:00 +00004403bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004404 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004405 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004406}
4407
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004408//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004409// Array Evaluation
4410//===----------------------------------------------------------------------===//
4411
4412namespace {
4413 class ArrayExprEvaluator
4414 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004415 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004416 APValue &Result;
4417 public:
4418
Richard Smithd62306a2011-11-10 06:34:14 +00004419 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4420 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004421
4422 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004423 assert((V.isArray() || V.isLValue()) &&
4424 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004425 Result = V;
4426 return true;
4427 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004428
Richard Smithfddd3842011-12-30 21:15:51 +00004429 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004430 const ConstantArrayType *CAT =
4431 Info.Ctx.getAsConstantArrayType(E->getType());
4432 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004433 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004434
4435 Result = APValue(APValue::UninitArray(), 0,
4436 CAT->getSize().getZExtValue());
4437 if (!Result.hasArrayFiller()) return true;
4438
Richard Smithfddd3842011-12-30 21:15:51 +00004439 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004440 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004441 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004442 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004443 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004444 }
4445
Richard Smithf3e9e432011-11-07 09:22:26 +00004446 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004447 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004448 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4449 const LValue &Subobject,
4450 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004451 };
4452} // end anonymous namespace
4453
Richard Smithd62306a2011-11-10 06:34:14 +00004454static bool EvaluateArray(const Expr *E, const LValue &This,
4455 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004456 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004457 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004458}
4459
4460bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4461 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4462 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004463 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004464
Richard Smithca2cfbf2011-12-22 01:07:19 +00004465 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4466 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004467 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004468 LValue LV;
4469 if (!EvaluateLValue(E->getInit(0), LV, Info))
4470 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004471 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004472 LV.moveInto(Val);
4473 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004474 }
4475
Richard Smith253c2a32012-01-27 01:14:48 +00004476 bool Success = true;
4477
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004478 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4479 "zero-initialized array shouldn't have any initialized elts");
4480 APValue Filler;
4481 if (Result.isArray() && Result.hasArrayFiller())
4482 Filler = Result.getArrayFiller();
4483
Richard Smith9543c5e2013-04-22 14:44:29 +00004484 unsigned NumEltsToInit = E->getNumInits();
4485 unsigned NumElts = CAT->getSize().getZExtValue();
4486 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4487
4488 // If the initializer might depend on the array index, run it for each
4489 // array element. For now, just whitelist non-class value-initialization.
4490 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4491 NumEltsToInit = NumElts;
4492
4493 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004494
4495 // If the array was previously zero-initialized, preserve the
4496 // zero-initialized values.
4497 if (!Filler.isUninit()) {
4498 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4499 Result.getArrayInitializedElt(I) = Filler;
4500 if (Result.hasArrayFiller())
4501 Result.getArrayFiller() = Filler;
4502 }
4503
Richard Smithd62306a2011-11-10 06:34:14 +00004504 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004505 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004506 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4507 const Expr *Init =
4508 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00004509 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00004510 Info, Subobject, Init) ||
4511 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00004512 CAT->getElementType(), 1)) {
4513 if (!Info.keepEvaluatingAfterFailure())
4514 return false;
4515 Success = false;
4516 }
Richard Smithd62306a2011-11-10 06:34:14 +00004517 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004518
Richard Smith9543c5e2013-04-22 14:44:29 +00004519 if (!Result.hasArrayFiller())
4520 return Success;
4521
4522 // If we get here, we have a trivial filler, which we can just evaluate
4523 // once and splat over the rest of the array elements.
4524 assert(FillerExpr && "no array filler for incomplete init list");
4525 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4526 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00004527}
4528
Richard Smith027bf112011-11-17 22:56:20 +00004529bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004530 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4531}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004532
Richard Smith9543c5e2013-04-22 14:44:29 +00004533bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4534 const LValue &Subobject,
4535 APValue *Value,
4536 QualType Type) {
4537 bool HadZeroInit = !Value->isUninit();
4538
4539 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4540 unsigned N = CAT->getSize().getZExtValue();
4541
4542 // Preserve the array filler if we had prior zero-initialization.
4543 APValue Filler =
4544 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4545 : APValue();
4546
4547 *Value = APValue(APValue::UninitArray(), N, N);
4548
4549 if (HadZeroInit)
4550 for (unsigned I = 0; I != N; ++I)
4551 Value->getArrayInitializedElt(I) = Filler;
4552
4553 // Initialize the elements.
4554 LValue ArrayElt = Subobject;
4555 ArrayElt.addArray(Info, E, CAT);
4556 for (unsigned I = 0; I != N; ++I)
4557 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4558 CAT->getElementType()) ||
4559 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4560 CAT->getElementType(), 1))
4561 return false;
4562
4563 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004564 }
Richard Smith027bf112011-11-17 22:56:20 +00004565
Richard Smith9543c5e2013-04-22 14:44:29 +00004566 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004567 return Error(E);
4568
Richard Smith027bf112011-11-17 22:56:20 +00004569 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004570
Richard Smithfddd3842011-12-30 21:15:51 +00004571 bool ZeroInit = E->requiresZeroInitialization();
4572 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004573 if (HadZeroInit)
4574 return true;
4575
Richard Smithfddd3842011-12-30 21:15:51 +00004576 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004577 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004578 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004579 }
4580
Richard Smithcc36f692011-12-22 02:22:31 +00004581 const CXXRecordDecl *RD = FD->getParent();
4582 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004583 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004584 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004585 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004586 APValue(APValue::UninitStruct(), RD->getNumBases(),
4587 std::distance(RD->field_begin(), RD->field_end()));
4588 return true;
4589 }
4590
Richard Smith027bf112011-11-17 22:56:20 +00004591 const FunctionDecl *Definition = 0;
4592 FD->getBody(Definition);
4593
Richard Smith357362d2011-12-13 06:39:58 +00004594 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4595 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004596
Richard Smith9eae7232012-01-12 18:54:33 +00004597 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004598 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004599 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004600 return false;
4601 }
4602
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004603 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004604 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004605 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004606 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004607}
4608
Richard Smithf3e9e432011-11-07 09:22:26 +00004609//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004610// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004611//
4612// As a GNU extension, we support casting pointers to sufficiently-wide integer
4613// types and back in constant folding. Integer values are thus represented
4614// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004615//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004616
4617namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004618class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004619 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004620 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004621public:
Richard Smith2e312c82012-03-03 22:46:17 +00004622 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004623 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004624
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004625 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004626 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004627 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004628 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004629 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004630 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004631 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004632 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004633 return true;
4634 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004635 bool Success(const llvm::APSInt &SI, const Expr *E) {
4636 return Success(SI, E, Result);
4637 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004638
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004639 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004640 assert(E->getType()->isIntegralOrEnumerationType() &&
4641 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004642 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004643 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004644 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004645 Result.getInt().setIsUnsigned(
4646 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004647 return true;
4648 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004649 bool Success(const llvm::APInt &I, const Expr *E) {
4650 return Success(I, E, Result);
4651 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004652
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004653 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004654 assert(E->getType()->isIntegralOrEnumerationType() &&
4655 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004656 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004657 return true;
4658 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004659 bool Success(uint64_t Value, const Expr *E) {
4660 return Success(Value, E, Result);
4661 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004662
Ken Dyckdbc01912011-03-11 02:13:43 +00004663 bool Success(CharUnits Size, const Expr *E) {
4664 return Success(Size.getQuantity(), E);
4665 }
4666
Richard Smith2e312c82012-03-03 22:46:17 +00004667 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004668 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00004669 Result = V;
4670 return true;
4671 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004672 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004673 }
Mike Stump11289f42009-09-09 15:08:12 +00004674
Richard Smithfddd3842011-12-30 21:15:51 +00004675 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00004676
Peter Collingbournee9200682011-05-13 03:29:01 +00004677 //===--------------------------------------------------------------------===//
4678 // Visitor Methods
4679 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004680
Chris Lattner7174bf32008-07-12 00:38:25 +00004681 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004682 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004683 }
4684 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004685 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004686 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004687
4688 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4689 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004690 if (CheckReferencedDecl(E, E->getDecl()))
4691 return true;
4692
4693 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004694 }
4695 bool VisitMemberExpr(const MemberExpr *E) {
4696 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004697 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004698 return true;
4699 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004700
4701 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004702 }
4703
Peter Collingbournee9200682011-05-13 03:29:01 +00004704 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004705 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004706 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004707 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004708
Peter Collingbournee9200682011-05-13 03:29:01 +00004709 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004710 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004711
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004712 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004713 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004714 }
Mike Stump11289f42009-09-09 15:08:12 +00004715
Ted Kremeneke65b0862012-03-06 20:05:56 +00004716 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4717 return Success(E->getValue(), E);
4718 }
4719
Richard Smith4ce706a2011-10-11 21:43:33 +00004720 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004721 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004722 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004723 }
4724
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004725 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004726 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004727 }
4728
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004729 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4730 return Success(E->getValue(), E);
4731 }
4732
Douglas Gregor29c42f22012-02-24 07:38:34 +00004733 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4734 return Success(E->getValue(), E);
4735 }
4736
John Wiegley6242b6a2011-04-28 00:16:57 +00004737 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4738 return Success(E->getValue(), E);
4739 }
4740
John Wiegleyf9f65842011-04-25 06:54:41 +00004741 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4742 return Success(E->getValue(), E);
4743 }
4744
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004745 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004746 bool VisitUnaryImag(const UnaryOperator *E);
4747
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004748 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004749 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004750
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004751private:
Ken Dyck160146e2010-01-27 17:10:57 +00004752 CharUnits GetAlignOfExpr(const Expr *E);
4753 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004754 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004755 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004756 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004757};
Chris Lattner05706e882008-07-11 18:11:29 +00004758} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004759
Richard Smith11562c52011-10-28 17:51:58 +00004760/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4761/// produce either the integer value or a pointer.
4762///
4763/// GCC has a heinous extension which folds casts between pointer types and
4764/// pointer-sized integral types. We support this by allowing the evaluation of
4765/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4766/// Some simple arithmetic on such values is supported (they are treated much
4767/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004768static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004769 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004770 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004771 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004772}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004773
Richard Smithf57d8cb2011-12-09 22:58:01 +00004774static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004775 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004776 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004777 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004778 if (!Val.isInt()) {
4779 // FIXME: It would be better to produce the diagnostic for casting
4780 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004781 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004782 return false;
4783 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004784 Result = Val.getInt();
4785 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004786}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004787
Richard Smithf57d8cb2011-12-09 22:58:01 +00004788/// Check whether the given declaration can be directly converted to an integral
4789/// rvalue. If not, no diagnostic is produced; there are other things we can
4790/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004791bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004792 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004793 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004794 // Check for signedness/width mismatches between E type and ECD value.
4795 bool SameSign = (ECD->getInitVal().isSigned()
4796 == E->getType()->isSignedIntegerOrEnumerationType());
4797 bool SameWidth = (ECD->getInitVal().getBitWidth()
4798 == Info.Ctx.getIntWidth(E->getType()));
4799 if (SameSign && SameWidth)
4800 return Success(ECD->getInitVal(), E);
4801 else {
4802 // Get rid of mismatch (otherwise Success assertions will fail)
4803 // by computing a new value matching the type of E.
4804 llvm::APSInt Val = ECD->getInitVal();
4805 if (!SameSign)
4806 Val.setIsSigned(!ECD->getInitVal().isSigned());
4807 if (!SameWidth)
4808 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4809 return Success(Val, E);
4810 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004811 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004812 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004813}
4814
Chris Lattner86ee2862008-10-06 06:40:35 +00004815/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4816/// as GCC.
4817static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4818 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004819 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004820 enum gcc_type_class {
4821 no_type_class = -1,
4822 void_type_class, integer_type_class, char_type_class,
4823 enumeral_type_class, boolean_type_class,
4824 pointer_type_class, reference_type_class, offset_type_class,
4825 real_type_class, complex_type_class,
4826 function_type_class, method_type_class,
4827 record_type_class, union_type_class,
4828 array_type_class, string_type_class,
4829 lang_type_class
4830 };
Mike Stump11289f42009-09-09 15:08:12 +00004831
4832 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004833 // ideal, however it is what gcc does.
4834 if (E->getNumArgs() == 0)
4835 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004836
Chris Lattner86ee2862008-10-06 06:40:35 +00004837 QualType ArgTy = E->getArg(0)->getType();
4838 if (ArgTy->isVoidType())
4839 return void_type_class;
4840 else if (ArgTy->isEnumeralType())
4841 return enumeral_type_class;
4842 else if (ArgTy->isBooleanType())
4843 return boolean_type_class;
4844 else if (ArgTy->isCharType())
4845 return string_type_class; // gcc doesn't appear to use char_type_class
4846 else if (ArgTy->isIntegerType())
4847 return integer_type_class;
4848 else if (ArgTy->isPointerType())
4849 return pointer_type_class;
4850 else if (ArgTy->isReferenceType())
4851 return reference_type_class;
4852 else if (ArgTy->isRealType())
4853 return real_type_class;
4854 else if (ArgTy->isComplexType())
4855 return complex_type_class;
4856 else if (ArgTy->isFunctionType())
4857 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004858 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004859 return record_type_class;
4860 else if (ArgTy->isUnionType())
4861 return union_type_class;
4862 else if (ArgTy->isArrayType())
4863 return array_type_class;
4864 else if (ArgTy->isUnionType())
4865 return union_type_class;
4866 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004867 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004868}
4869
Richard Smith5fab0c92011-12-28 19:48:30 +00004870/// EvaluateBuiltinConstantPForLValue - Determine the result of
4871/// __builtin_constant_p when applied to the given lvalue.
4872///
4873/// An lvalue is only "constant" if it is a pointer or reference to the first
4874/// character of a string literal.
4875template<typename LValue>
4876static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004877 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004878 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4879}
4880
4881/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4882/// GCC as we can manage.
4883static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4884 QualType ArgType = Arg->getType();
4885
4886 // __builtin_constant_p always has one operand. The rules which gcc follows
4887 // are not precisely documented, but are as follows:
4888 //
4889 // - If the operand is of integral, floating, complex or enumeration type,
4890 // and can be folded to a known value of that type, it returns 1.
4891 // - If the operand and can be folded to a pointer to the first character
4892 // of a string literal (or such a pointer cast to an integral type), it
4893 // returns 1.
4894 //
4895 // Otherwise, it returns 0.
4896 //
4897 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4898 // its support for this does not currently work.
4899 if (ArgType->isIntegralOrEnumerationType()) {
4900 Expr::EvalResult Result;
4901 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4902 return false;
4903
4904 APValue &V = Result.Val;
4905 if (V.getKind() == APValue::Int)
4906 return true;
4907
4908 return EvaluateBuiltinConstantPForLValue(V);
4909 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4910 return Arg->isEvaluatable(Ctx);
4911 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4912 LValue LV;
4913 Expr::EvalStatus Status;
4914 EvalInfo Info(Ctx, Status);
4915 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4916 : EvaluatePointer(Arg, LV, Info)) &&
4917 !Status.HasSideEffects)
4918 return EvaluateBuiltinConstantPForLValue(LV);
4919 }
4920
4921 // Anything else isn't considered to be sufficiently constant.
4922 return false;
4923}
4924
John McCall95007602010-05-10 23:27:23 +00004925/// Retrieves the "underlying object type" of the given expression,
4926/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004927QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4928 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4929 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004930 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004931 } else if (const Expr *E = B.get<const Expr*>()) {
4932 if (isa<CompoundLiteralExpr>(E))
4933 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004934 }
4935
4936 return QualType();
4937}
4938
Peter Collingbournee9200682011-05-13 03:29:01 +00004939bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004940 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004941
4942 {
4943 // The operand of __builtin_object_size is never evaluated for side-effects.
4944 // If there are any, but we can determine the pointed-to object anyway, then
4945 // ignore the side-effects.
4946 SpeculativeEvaluationRAII SpeculativeEval(Info);
4947 if (!EvaluatePointer(E->getArg(0), Base, Info))
4948 return false;
4949 }
John McCall95007602010-05-10 23:27:23 +00004950
4951 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004952 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004953
Richard Smithce40ad62011-11-12 22:28:03 +00004954 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004955 if (T.isNull() ||
4956 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004957 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004958 T->isVariablyModifiedType() ||
4959 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004960 return Error(E);
John McCall95007602010-05-10 23:27:23 +00004961
4962 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4963 CharUnits Offset = Base.getLValueOffset();
4964
4965 if (!Offset.isNegative() && Offset <= Size)
4966 Size -= Offset;
4967 else
4968 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00004969 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00004970}
4971
Peter Collingbournee9200682011-05-13 03:29:01 +00004972bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00004973 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004974 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00004975 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004976
4977 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00004978 if (TryEvaluateBuiltinObjectSize(E))
4979 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00004980
Richard Smith0421ce72012-08-07 04:16:51 +00004981 // If evaluating the argument has side-effects, we can't determine the size
4982 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4983 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004984 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00004985 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00004986 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00004987 return Success(0, E);
4988 }
Mike Stump876387b2009-10-27 22:09:17 +00004989
Richard Smith01ade172012-05-23 04:13:20 +00004990 // Expression had no side effects, but we couldn't statically determine the
4991 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004992 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004993 }
4994
Benjamin Kramera801f4a2012-10-06 14:42:22 +00004995 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00004996 case Builtin::BI__builtin_bswap32:
4997 case Builtin::BI__builtin_bswap64: {
4998 APSInt Val;
4999 if (!EvaluateInteger(E->getArg(0), Val, Info))
5000 return false;
5001
5002 return Success(Val.byteSwap(), E);
5003 }
5004
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005005 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005006 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005007
Richard Smith5fab0c92011-12-28 19:48:30 +00005008 case Builtin::BI__builtin_constant_p:
5009 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005010
Chris Lattnerd545ad12009-09-23 06:06:36 +00005011 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005012 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005013 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005014 return Success(Operand, E);
5015 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005016
5017 case Builtin::BI__builtin_expect:
5018 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005019
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005020 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005021 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005022 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005023 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005024 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5025 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005026 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005027 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005028 case Builtin::BI__builtin_strlen:
5029 // As an extension, we support strlen() and __builtin_strlen() as constant
5030 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005031 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005032 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5033 // The string literal may have embedded null characters. Find the first
5034 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005035 StringRef Str = S->getString();
5036 StringRef::size_type Pos = Str.find(0);
5037 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005038 Str = Str.substr(0, Pos);
5039
5040 return Success(Str.size(), E);
5041 }
5042
Richard Smithf57d8cb2011-12-09 22:58:01 +00005043 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005044
Richard Smith01ba47d2012-04-13 00:45:38 +00005045 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005046 case Builtin::BI__atomic_is_lock_free:
5047 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005048 APSInt SizeVal;
5049 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5050 return false;
5051
5052 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5053 // of two less than the maximum inline atomic width, we know it is
5054 // lock-free. If the size isn't a power of two, or greater than the
5055 // maximum alignment where we promote atomics, we know it is not lock-free
5056 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5057 // the answer can only be determined at runtime; for example, 16-byte
5058 // atomics have lock-free implementations on some, but not all,
5059 // x86-64 processors.
5060
5061 // Check power-of-two.
5062 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005063 if (Size.isPowerOfTwo()) {
5064 // Check against inlining width.
5065 unsigned InlineWidthBits =
5066 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5067 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5068 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5069 Size == CharUnits::One() ||
5070 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5071 Expr::NPC_NeverValueDependent))
5072 // OK, we will inline appropriately-aligned operations of this size,
5073 // and _Atomic(T) is appropriately-aligned.
5074 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005075
Richard Smith01ba47d2012-04-13 00:45:38 +00005076 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5077 castAs<PointerType>()->getPointeeType();
5078 if (!PointeeType->isIncompleteType() &&
5079 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5080 // OK, we will inline operations on this object.
5081 return Success(1, E);
5082 }
5083 }
5084 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005085
Richard Smith01ba47d2012-04-13 00:45:38 +00005086 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5087 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005088 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005089 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005090}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005091
Richard Smith8b3497e2011-10-31 01:37:14 +00005092static bool HasSameBase(const LValue &A, const LValue &B) {
5093 if (!A.getLValueBase())
5094 return !B.getLValueBase();
5095 if (!B.getLValueBase())
5096 return false;
5097
Richard Smithce40ad62011-11-12 22:28:03 +00005098 if (A.getLValueBase().getOpaqueValue() !=
5099 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005100 const Decl *ADecl = GetLValueBaseDecl(A);
5101 if (!ADecl)
5102 return false;
5103 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005104 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005105 return false;
5106 }
5107
5108 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005109 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005110}
5111
Richard Smithc8042322012-02-01 05:53:12 +00005112/// Perform the given integer operation, which is known to need at most BitWidth
5113/// bits, and check for overflow in the original type (if that type was not an
5114/// unsigned type).
5115template<typename Operation>
5116static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
5117 const APSInt &LHS, const APSInt &RHS,
5118 unsigned BitWidth, Operation Op) {
5119 if (LHS.isUnsigned())
5120 return Op(LHS, RHS);
5121
5122 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
5123 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005124 if (Result.extend(BitWidth) != Value) {
5125 if (Info.getIntOverflowCheckMode())
5126 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
5127 diag::warn_integer_constant_overflow)
5128 << Result.toString(10) << E->getType();
5129 else
5130 HandleOverflow(Info, E, Value, E->getType());
5131 }
Richard Smithc8042322012-02-01 05:53:12 +00005132 return Result;
5133}
5134
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005135namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005136
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005137/// \brief Data recursive integer evaluator of certain binary operators.
5138///
5139/// We use a data recursive algorithm for binary operators so that we are able
5140/// to handle extreme cases of chained binary operators without causing stack
5141/// overflow.
5142class DataRecursiveIntBinOpEvaluator {
5143 struct EvalResult {
5144 APValue Val;
5145 bool Failed;
5146
5147 EvalResult() : Failed(false) { }
5148
5149 void swap(EvalResult &RHS) {
5150 Val.swap(RHS.Val);
5151 Failed = RHS.Failed;
5152 RHS.Failed = false;
5153 }
5154 };
5155
5156 struct Job {
5157 const Expr *E;
5158 EvalResult LHSResult; // meaningful only for binary operator expression.
5159 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5160
5161 Job() : StoredInfo(0) { }
5162 void startSpeculativeEval(EvalInfo &Info) {
5163 OldEvalStatus = Info.EvalStatus;
5164 Info.EvalStatus.Diag = 0;
5165 StoredInfo = &Info;
5166 }
5167 ~Job() {
5168 if (StoredInfo) {
5169 StoredInfo->EvalStatus = OldEvalStatus;
5170 }
5171 }
5172 private:
5173 EvalInfo *StoredInfo; // non-null if status changed.
5174 Expr::EvalStatus OldEvalStatus;
5175 };
5176
5177 SmallVector<Job, 16> Queue;
5178
5179 IntExprEvaluator &IntEval;
5180 EvalInfo &Info;
5181 APValue &FinalResult;
5182
5183public:
5184 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5185 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5186
5187 /// \brief True if \param E is a binary operator that we are going to handle
5188 /// data recursively.
5189 /// We handle binary operators that are comma, logical, or that have operands
5190 /// with integral or enumeration type.
5191 static bool shouldEnqueue(const BinaryOperator *E) {
5192 return E->getOpcode() == BO_Comma ||
5193 E->isLogicalOp() ||
5194 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5195 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005196 }
5197
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005198 bool Traverse(const BinaryOperator *E) {
5199 enqueue(E);
5200 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005201 while (!Queue.empty())
5202 process(PrevResult);
5203
5204 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005205
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005206 FinalResult.swap(PrevResult.Val);
5207 return true;
5208 }
5209
5210private:
5211 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5212 return IntEval.Success(Value, E, Result);
5213 }
5214 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5215 return IntEval.Success(Value, E, Result);
5216 }
5217 bool Error(const Expr *E) {
5218 return IntEval.Error(E);
5219 }
5220 bool Error(const Expr *E, diag::kind D) {
5221 return IntEval.Error(E, D);
5222 }
5223
5224 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5225 return Info.CCEDiag(E, D);
5226 }
5227
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005228 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5229 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005230 bool &SuppressRHSDiags);
5231
5232 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5233 const BinaryOperator *E, APValue &Result);
5234
5235 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5236 Result.Failed = !Evaluate(Result.Val, Info, E);
5237 if (Result.Failed)
5238 Result.Val = APValue();
5239 }
5240
Richard Trieuba4d0872012-03-21 23:30:30 +00005241 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005242
5243 void enqueue(const Expr *E) {
5244 E = E->IgnoreParens();
5245 Queue.resize(Queue.size()+1);
5246 Queue.back().E = E;
5247 Queue.back().Kind = Job::AnyExprKind;
5248 }
5249};
5250
5251}
5252
5253bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005254 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005255 bool &SuppressRHSDiags) {
5256 if (E->getOpcode() == BO_Comma) {
5257 // Ignore LHS but note if we could not evaluate it.
5258 if (LHSResult.Failed)
5259 Info.EvalStatus.HasSideEffects = true;
5260 return true;
5261 }
5262
5263 if (E->isLogicalOp()) {
5264 bool lhsResult;
5265 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005266 // We were able to evaluate the LHS, see if we can get away with not
5267 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005268 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005269 Success(lhsResult, E, LHSResult.Val);
5270 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005271 }
5272 } else {
5273 // Since we weren't able to evaluate the left hand side, it
5274 // must have had side effects.
5275 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005276
5277 // We can't evaluate the LHS; however, sometimes the result
5278 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5279 // Don't ignore RHS and suppress diagnostics from this arm.
5280 SuppressRHSDiags = true;
5281 }
5282
5283 return true;
5284 }
5285
5286 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5287 E->getRHS()->getType()->isIntegralOrEnumerationType());
5288
5289 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005290 return false; // Ignore RHS;
5291
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005292 return true;
5293}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005294
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005295bool DataRecursiveIntBinOpEvaluator::
5296 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5297 const BinaryOperator *E, APValue &Result) {
5298 if (E->getOpcode() == BO_Comma) {
5299 if (RHSResult.Failed)
5300 return false;
5301 Result = RHSResult.Val;
5302 return true;
5303 }
5304
5305 if (E->isLogicalOp()) {
5306 bool lhsResult, rhsResult;
5307 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5308 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5309
5310 if (LHSIsOK) {
5311 if (RHSIsOK) {
5312 if (E->getOpcode() == BO_LOr)
5313 return Success(lhsResult || rhsResult, E, Result);
5314 else
5315 return Success(lhsResult && rhsResult, E, Result);
5316 }
5317 } else {
5318 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005319 // We can't evaluate the LHS; however, sometimes the result
5320 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5321 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005322 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005323 }
5324 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005325
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005326 return false;
5327 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005328
5329 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5330 E->getRHS()->getType()->isIntegralOrEnumerationType());
5331
5332 if (LHSResult.Failed || RHSResult.Failed)
5333 return false;
5334
5335 const APValue &LHSVal = LHSResult.Val;
5336 const APValue &RHSVal = RHSResult.Val;
5337
5338 // Handle cases like (unsigned long)&a + 4.
5339 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5340 Result = LHSVal;
5341 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5342 RHSVal.getInt().getZExtValue());
5343 if (E->getOpcode() == BO_Add)
5344 Result.getLValueOffset() += AdditionalOffset;
5345 else
5346 Result.getLValueOffset() -= AdditionalOffset;
5347 return true;
5348 }
5349
5350 // Handle cases like 4 + (unsigned long)&a
5351 if (E->getOpcode() == BO_Add &&
5352 RHSVal.isLValue() && LHSVal.isInt()) {
5353 Result = RHSVal;
5354 Result.getLValueOffset() += CharUnits::fromQuantity(
5355 LHSVal.getInt().getZExtValue());
5356 return true;
5357 }
5358
5359 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5360 // Handle (intptr_t)&&A - (intptr_t)&&B.
5361 if (!LHSVal.getLValueOffset().isZero() ||
5362 !RHSVal.getLValueOffset().isZero())
5363 return false;
5364 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5365 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5366 if (!LHSExpr || !RHSExpr)
5367 return false;
5368 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5369 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5370 if (!LHSAddrExpr || !RHSAddrExpr)
5371 return false;
5372 // Make sure both labels come from the same function.
5373 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5374 RHSAddrExpr->getLabel()->getDeclContext())
5375 return false;
5376 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5377 return true;
5378 }
5379
5380 // All the following cases expect both operands to be an integer
5381 if (!LHSVal.isInt() || !RHSVal.isInt())
5382 return Error(E);
5383
5384 const APSInt &LHS = LHSVal.getInt();
5385 APSInt RHS = RHSVal.getInt();
5386
5387 switch (E->getOpcode()) {
5388 default:
5389 return Error(E);
5390 case BO_Mul:
5391 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5392 LHS.getBitWidth() * 2,
5393 std::multiplies<APSInt>()), E,
5394 Result);
5395 case BO_Add:
5396 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5397 LHS.getBitWidth() + 1,
5398 std::plus<APSInt>()), E, Result);
5399 case BO_Sub:
5400 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5401 LHS.getBitWidth() + 1,
5402 std::minus<APSInt>()), E, Result);
5403 case BO_And: return Success(LHS & RHS, E, Result);
5404 case BO_Xor: return Success(LHS ^ RHS, E, Result);
5405 case BO_Or: return Success(LHS | RHS, E, Result);
5406 case BO_Div:
5407 case BO_Rem:
5408 if (RHS == 0)
5409 return Error(E, diag::note_expr_divide_by_zero);
5410 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
5411 // not actually undefined behavior in C++11 due to a language defect.
5412 if (RHS.isNegative() && RHS.isAllOnesValue() &&
5413 LHS.isSigned() && LHS.isMinSignedValue())
5414 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
5415 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
5416 Result);
5417 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00005418 if (Info.getLangOpts().OpenCL)
5419 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005420 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005421 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5422 RHS.isUnsigned());
5423 else if (RHS.isSigned() && RHS.isNegative()) {
5424 // During constant-folding, a negative shift is an opposite shift. Such
5425 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005426 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5427 RHS = -RHS;
5428 goto shift_right;
5429 }
5430
5431 shift_left:
5432 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
5433 // the shifted type.
5434 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5435 if (SA != RHS) {
5436 CCEDiag(E, diag::note_constexpr_large_shift)
5437 << RHS << E->getType() << LHS.getBitWidth();
5438 } else if (LHS.isSigned()) {
5439 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
5440 // operand, and must not overflow the corresponding unsigned type.
5441 if (LHS.isNegative())
5442 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
5443 else if (LHS.countLeadingZeros() < SA)
5444 CCEDiag(E, diag::note_constexpr_lshift_discards);
5445 }
5446
5447 return Success(LHS << SA, E, Result);
5448 }
5449 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00005450 if (Info.getLangOpts().OpenCL)
5451 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005452 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005453 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5454 RHS.isUnsigned());
5455 else if (RHS.isSigned() && RHS.isNegative()) {
5456 // During constant-folding, a negative shift is an opposite shift. Such a
5457 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005458 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5459 RHS = -RHS;
5460 goto shift_left;
5461 }
5462
5463 shift_right:
5464 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
5465 // shifted type.
5466 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5467 if (SA != RHS)
5468 CCEDiag(E, diag::note_constexpr_large_shift)
5469 << RHS << E->getType() << LHS.getBitWidth();
5470
5471 return Success(LHS >> SA, E, Result);
5472 }
5473
5474 case BO_LT: return Success(LHS < RHS, E, Result);
5475 case BO_GT: return Success(LHS > RHS, E, Result);
5476 case BO_LE: return Success(LHS <= RHS, E, Result);
5477 case BO_GE: return Success(LHS >= RHS, E, Result);
5478 case BO_EQ: return Success(LHS == RHS, E, Result);
5479 case BO_NE: return Success(LHS != RHS, E, Result);
5480 }
5481}
5482
Richard Trieuba4d0872012-03-21 23:30:30 +00005483void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005484 Job &job = Queue.back();
5485
5486 switch (job.Kind) {
5487 case Job::AnyExprKind: {
5488 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5489 if (shouldEnqueue(Bop)) {
5490 job.Kind = Job::BinOpKind;
5491 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005492 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005493 }
5494 }
5495
5496 EvaluateExpr(job.E, Result);
5497 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005498 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005499 }
5500
5501 case Job::BinOpKind: {
5502 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005503 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005504 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005505 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005506 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005507 }
5508 if (SuppressRHSDiags)
5509 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005510 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005511 job.Kind = Job::BinOpVisitedLHSKind;
5512 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005513 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005514 }
5515
5516 case Job::BinOpVisitedLHSKind: {
5517 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5518 EvalResult RHS;
5519 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005520 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005521 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005522 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005523 }
5524 }
5525
5526 llvm_unreachable("Invalid Job::Kind!");
5527}
5528
5529bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5530 if (E->isAssignmentOp())
5531 return Error(E);
5532
5533 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5534 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005535
Anders Carlssonacc79812008-11-16 07:17:21 +00005536 QualType LHSTy = E->getLHS()->getType();
5537 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005538
5539 if (LHSTy->isAnyComplexType()) {
5540 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005541 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005542
Richard Smith253c2a32012-01-27 01:14:48 +00005543 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5544 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005545 return false;
5546
Richard Smith253c2a32012-01-27 01:14:48 +00005547 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005548 return false;
5549
5550 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005551 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005552 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005553 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005554 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5555
John McCalle3027922010-08-25 11:45:40 +00005556 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005557 return Success((CR_r == APFloat::cmpEqual &&
5558 CR_i == APFloat::cmpEqual), E);
5559 else {
John McCalle3027922010-08-25 11:45:40 +00005560 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005561 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005562 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005563 CR_r == APFloat::cmpLessThan ||
5564 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005565 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005566 CR_i == APFloat::cmpLessThan ||
5567 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005568 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005569 } else {
John McCalle3027922010-08-25 11:45:40 +00005570 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005571 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5572 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5573 else {
John McCalle3027922010-08-25 11:45:40 +00005574 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005575 "Invalid compex comparison.");
5576 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5577 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5578 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005579 }
5580 }
Mike Stump11289f42009-09-09 15:08:12 +00005581
Anders Carlssonacc79812008-11-16 07:17:21 +00005582 if (LHSTy->isRealFloatingType() &&
5583 RHSTy->isRealFloatingType()) {
5584 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005585
Richard Smith253c2a32012-01-27 01:14:48 +00005586 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5587 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005588 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005589
Richard Smith253c2a32012-01-27 01:14:48 +00005590 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005591 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005592
Anders Carlssonacc79812008-11-16 07:17:21 +00005593 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005594
Anders Carlssonacc79812008-11-16 07:17:21 +00005595 switch (E->getOpcode()) {
5596 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005597 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005598 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005599 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005600 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005601 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005602 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005603 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005604 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005605 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005606 E);
John McCalle3027922010-08-25 11:45:40 +00005607 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005608 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005609 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005610 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005611 || CR == APFloat::cmpLessThan
5612 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005613 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005614 }
Mike Stump11289f42009-09-09 15:08:12 +00005615
Eli Friedmana38da572009-04-28 19:17:36 +00005616 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005617 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005618 LValue LHSValue, RHSValue;
5619
5620 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5621 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005622 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005623
Richard Smith253c2a32012-01-27 01:14:48 +00005624 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005625 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005626
Richard Smith8b3497e2011-10-31 01:37:14 +00005627 // Reject differing bases from the normal codepath; we special-case
5628 // comparisons to null.
5629 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005630 if (E->getOpcode() == BO_Sub) {
5631 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005632 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5633 return false;
5634 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005635 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005636 if (!LHSExpr || !RHSExpr)
5637 return false;
5638 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5639 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5640 if (!LHSAddrExpr || !RHSAddrExpr)
5641 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005642 // Make sure both labels come from the same function.
5643 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5644 RHSAddrExpr->getLabel()->getDeclContext())
5645 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005646 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005647 return true;
5648 }
Richard Smith83c68212011-10-31 05:11:32 +00005649 // Inequalities and subtractions between unrelated pointers have
5650 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005651 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005652 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005653 // A constant address may compare equal to the address of a symbol.
5654 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005655 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005656 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5657 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005658 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005659 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005660 // distinct addresses. In clang, the result of such a comparison is
5661 // unspecified, so it is not a constant expression. However, we do know
5662 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005663 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5664 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005665 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005666 // We can't tell whether weak symbols will end up pointing to the same
5667 // object.
5668 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005669 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005670 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005671 // (Note that clang defaults to -fmerge-all-constants, which can
5672 // lead to inconsistent results for comparisons involving the address
5673 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005674 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005675 }
Eli Friedman64004332009-03-23 04:38:34 +00005676
Richard Smith1b470412012-02-01 08:10:20 +00005677 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5678 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5679
Richard Smith84f6dcf2012-02-02 01:16:57 +00005680 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5681 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5682
John McCalle3027922010-08-25 11:45:40 +00005683 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005684 // C++11 [expr.add]p6:
5685 // Unless both pointers point to elements of the same array object, or
5686 // one past the last element of the array object, the behavior is
5687 // undefined.
5688 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5689 !AreElementsOfSameArray(getType(LHSValue.Base),
5690 LHSDesignator, RHSDesignator))
5691 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5692
Chris Lattner882bdf22010-04-20 17:13:14 +00005693 QualType Type = E->getLHS()->getType();
5694 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005695
Richard Smithd62306a2011-11-10 06:34:14 +00005696 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005697 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005698 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005699
Richard Smith1b470412012-02-01 08:10:20 +00005700 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5701 // and produce incorrect results when it overflows. Such behavior
5702 // appears to be non-conforming, but is common, so perhaps we should
5703 // assume the standard intended for such cases to be undefined behavior
5704 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005705
Richard Smith1b470412012-02-01 08:10:20 +00005706 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5707 // overflow in the final conversion to ptrdiff_t.
5708 APSInt LHS(
5709 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5710 APSInt RHS(
5711 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5712 APSInt ElemSize(
5713 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5714 APSInt TrueResult = (LHS - RHS) / ElemSize;
5715 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5716
5717 if (Result.extend(65) != TrueResult)
5718 HandleOverflow(Info, E, TrueResult, E->getType());
5719 return Success(Result, E);
5720 }
Richard Smithde21b242012-01-31 06:41:30 +00005721
5722 // C++11 [expr.rel]p3:
5723 // Pointers to void (after pointer conversions) can be compared, with a
5724 // result defined as follows: If both pointers represent the same
5725 // address or are both the null pointer value, the result is true if the
5726 // operator is <= or >= and false otherwise; otherwise the result is
5727 // unspecified.
5728 // We interpret this as applying to pointers to *cv* void.
5729 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005730 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005731 CCEDiag(E, diag::note_constexpr_void_comparison);
5732
Richard Smith84f6dcf2012-02-02 01:16:57 +00005733 // C++11 [expr.rel]p2:
5734 // - If two pointers point to non-static data members of the same object,
5735 // or to subobjects or array elements fo such members, recursively, the
5736 // pointer to the later declared member compares greater provided the
5737 // two members have the same access control and provided their class is
5738 // not a union.
5739 // [...]
5740 // - Otherwise pointer comparisons are unspecified.
5741 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5742 E->isRelationalOp()) {
5743 bool WasArrayIndex;
5744 unsigned Mismatch =
5745 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5746 RHSDesignator, WasArrayIndex);
5747 // At the point where the designators diverge, the comparison has a
5748 // specified value if:
5749 // - we are comparing array indices
5750 // - we are comparing fields of a union, or fields with the same access
5751 // Otherwise, the result is unspecified and thus the comparison is not a
5752 // constant expression.
5753 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5754 Mismatch < RHSDesignator.Entries.size()) {
5755 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5756 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5757 if (!LF && !RF)
5758 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5759 else if (!LF)
5760 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5761 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5762 << RF->getParent() << RF;
5763 else if (!RF)
5764 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5765 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5766 << LF->getParent() << LF;
5767 else if (!LF->getParent()->isUnion() &&
5768 LF->getAccess() != RF->getAccess())
5769 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5770 << LF << LF->getAccess() << RF << RF->getAccess()
5771 << LF->getParent();
5772 }
5773 }
5774
Eli Friedman6c31cb42012-04-16 04:30:08 +00005775 // The comparison here must be unsigned, and performed with the same
5776 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005777 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5778 uint64_t CompareLHS = LHSOffset.getQuantity();
5779 uint64_t CompareRHS = RHSOffset.getQuantity();
5780 assert(PtrSize <= 64 && "Unexpected pointer width");
5781 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5782 CompareLHS &= Mask;
5783 CompareRHS &= Mask;
5784
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005785 // If there is a base and this is a relational operator, we can only
5786 // compare pointers within the object in question; otherwise, the result
5787 // depends on where the object is located in memory.
5788 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5789 QualType BaseTy = getType(LHSValue.Base);
5790 if (BaseTy->isIncompleteType())
5791 return Error(E);
5792 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5793 uint64_t OffsetLimit = Size.getQuantity();
5794 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5795 return Error(E);
5796 }
5797
Richard Smith8b3497e2011-10-31 01:37:14 +00005798 switch (E->getOpcode()) {
5799 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005800 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5801 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5802 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5803 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5804 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5805 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005806 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005807 }
5808 }
Richard Smith7bb00672012-02-01 01:42:44 +00005809
5810 if (LHSTy->isMemberPointerType()) {
5811 assert(E->isEqualityOp() && "unexpected member pointer operation");
5812 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5813
5814 MemberPtr LHSValue, RHSValue;
5815
5816 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5817 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5818 return false;
5819
5820 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5821 return false;
5822
5823 // C++11 [expr.eq]p2:
5824 // If both operands are null, they compare equal. Otherwise if only one is
5825 // null, they compare unequal.
5826 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5827 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5828 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5829 }
5830
5831 // Otherwise if either is a pointer to a virtual member function, the
5832 // result is unspecified.
5833 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5834 if (MD->isVirtual())
5835 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5836 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5837 if (MD->isVirtual())
5838 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5839
5840 // Otherwise they compare equal if and only if they would refer to the
5841 // same member of the same most derived object or the same subobject if
5842 // they were dereferenced with a hypothetical object of the associated
5843 // class type.
5844 bool Equal = LHSValue == RHSValue;
5845 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5846 }
5847
Richard Smithab44d9b2012-02-14 22:35:28 +00005848 if (LHSTy->isNullPtrType()) {
5849 assert(E->isComparisonOp() && "unexpected nullptr operation");
5850 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5851 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5852 // are compared, the result is true of the operator is <=, >= or ==, and
5853 // false otherwise.
5854 BinaryOperator::Opcode Opcode = E->getOpcode();
5855 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5856 }
5857
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005858 assert((!LHSTy->isIntegralOrEnumerationType() ||
5859 !RHSTy->isIntegralOrEnumerationType()) &&
5860 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5861 // We can't continue from here for non-integral types.
5862 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005863}
5864
Ken Dyck160146e2010-01-27 17:10:57 +00005865CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005866 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5867 // result shall be the alignment of the referenced type."
5868 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5869 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005870
5871 // __alignof is defined to return the preferred alignment.
5872 return Info.Ctx.toCharUnitsFromBits(
5873 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005874}
5875
Ken Dyck160146e2010-01-27 17:10:57 +00005876CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005877 E = E->IgnoreParens();
5878
5879 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005880 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005881 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005882 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5883 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005884
Chris Lattner68061312009-01-24 21:53:27 +00005885 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005886 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5887 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005888
Chris Lattner24aeeab2009-01-24 21:09:06 +00005889 return GetAlignOfType(E->getType());
5890}
5891
5892
Peter Collingbournee190dee2011-03-11 19:24:49 +00005893/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5894/// a result as the expression's type.
5895bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5896 const UnaryExprOrTypeTraitExpr *E) {
5897 switch(E->getKind()) {
5898 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005899 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005900 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005901 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005902 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005903 }
Eli Friedman64004332009-03-23 04:38:34 +00005904
Peter Collingbournee190dee2011-03-11 19:24:49 +00005905 case UETT_VecStep: {
5906 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005907
Peter Collingbournee190dee2011-03-11 19:24:49 +00005908 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005909 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005910
Peter Collingbournee190dee2011-03-11 19:24:49 +00005911 // The vec_step built-in functions that take a 3-component
5912 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5913 if (n == 3)
5914 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005915
Peter Collingbournee190dee2011-03-11 19:24:49 +00005916 return Success(n, E);
5917 } else
5918 return Success(1, E);
5919 }
5920
5921 case UETT_SizeOf: {
5922 QualType SrcTy = E->getTypeOfArgument();
5923 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5924 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005925 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5926 SrcTy = Ref->getPointeeType();
5927
Richard Smithd62306a2011-11-10 06:34:14 +00005928 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005929 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005930 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005931 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005932 }
5933 }
5934
5935 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005936}
5937
Peter Collingbournee9200682011-05-13 03:29:01 +00005938bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005939 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005940 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005941 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005942 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005943 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005944 for (unsigned i = 0; i != n; ++i) {
5945 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5946 switch (ON.getKind()) {
5947 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005948 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005949 APSInt IdxResult;
5950 if (!EvaluateInteger(Idx, IdxResult, Info))
5951 return false;
5952 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5953 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005954 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005955 CurrentType = AT->getElementType();
5956 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5957 Result += IdxResult.getSExtValue() * ElementSize;
5958 break;
5959 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005960
Douglas Gregor882211c2010-04-28 22:16:22 +00005961 case OffsetOfExpr::OffsetOfNode::Field: {
5962 FieldDecl *MemberDecl = ON.getField();
5963 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005964 if (!RT)
5965 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005966 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005967 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00005968 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00005969 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00005970 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00005971 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00005972 CurrentType = MemberDecl->getType().getNonReferenceType();
5973 break;
5974 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005975
Douglas Gregor882211c2010-04-28 22:16:22 +00005976 case OffsetOfExpr::OffsetOfNode::Identifier:
5977 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005978
Douglas Gregord1702062010-04-29 00:18:15 +00005979 case OffsetOfExpr::OffsetOfNode::Base: {
5980 CXXBaseSpecifier *BaseSpec = ON.getBase();
5981 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005982 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005983
5984 // Find the layout of the class whose base we are looking into.
5985 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005986 if (!RT)
5987 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005988 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005989 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00005990 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5991
5992 // Find the base class itself.
5993 CurrentType = BaseSpec->getType();
5994 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5995 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005996 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005997
5998 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00005999 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006000 break;
6001 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006002 }
6003 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006004 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006005}
6006
Chris Lattnere13042c2008-07-11 19:10:17 +00006007bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006008 switch (E->getOpcode()) {
6009 default:
6010 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6011 // See C99 6.6p3.
6012 return Error(E);
6013 case UO_Extension:
6014 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6015 // If so, we could clear the diagnostic ID.
6016 return Visit(E->getSubExpr());
6017 case UO_Plus:
6018 // The result is just the value.
6019 return Visit(E->getSubExpr());
6020 case UO_Minus: {
6021 if (!Visit(E->getSubExpr()))
6022 return false;
6023 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006024 const APSInt &Value = Result.getInt();
6025 if (Value.isSigned() && Value.isMinSignedValue())
6026 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6027 E->getType());
6028 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006029 }
6030 case UO_Not: {
6031 if (!Visit(E->getSubExpr()))
6032 return false;
6033 if (!Result.isInt()) return Error(E);
6034 return Success(~Result.getInt(), E);
6035 }
6036 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006037 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006038 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006039 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006040 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006041 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006042 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006043}
Mike Stump11289f42009-09-09 15:08:12 +00006044
Chris Lattner477c4be2008-07-12 01:15:53 +00006045/// HandleCast - This is used to evaluate implicit or explicit casts where the
6046/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006047bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6048 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006049 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006050 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006051
Eli Friedmanc757de22011-03-25 00:43:55 +00006052 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006053 case CK_BaseToDerived:
6054 case CK_DerivedToBase:
6055 case CK_UncheckedDerivedToBase:
6056 case CK_Dynamic:
6057 case CK_ToUnion:
6058 case CK_ArrayToPointerDecay:
6059 case CK_FunctionToPointerDecay:
6060 case CK_NullToPointer:
6061 case CK_NullToMemberPointer:
6062 case CK_BaseToDerivedMemberPointer:
6063 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006064 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006065 case CK_ConstructorConversion:
6066 case CK_IntegralToPointer:
6067 case CK_ToVoid:
6068 case CK_VectorSplat:
6069 case CK_IntegralToFloating:
6070 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006071 case CK_CPointerToObjCPointerCast:
6072 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006073 case CK_AnyPointerToBlockPointerCast:
6074 case CK_ObjCObjectLValueCast:
6075 case CK_FloatingRealToComplex:
6076 case CK_FloatingComplexToReal:
6077 case CK_FloatingComplexCast:
6078 case CK_FloatingComplexToIntegralComplex:
6079 case CK_IntegralRealToComplex:
6080 case CK_IntegralComplexCast:
6081 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006082 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006083 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006084 llvm_unreachable("invalid cast kind for integral value");
6085
Eli Friedman9faf2f92011-03-25 19:07:11 +00006086 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006087 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006088 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006089 case CK_ARCProduceObject:
6090 case CK_ARCConsumeObject:
6091 case CK_ARCReclaimReturnedObject:
6092 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006093 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006094 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006095
Richard Smith4ef685b2012-01-17 21:17:26 +00006096 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006097 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006098 case CK_AtomicToNonAtomic:
6099 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006100 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006101 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006102
6103 case CK_MemberPointerToBoolean:
6104 case CK_PointerToBoolean:
6105 case CK_IntegralToBoolean:
6106 case CK_FloatingToBoolean:
6107 case CK_FloatingComplexToBoolean:
6108 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006109 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006110 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006111 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006112 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006113 }
6114
Eli Friedmanc757de22011-03-25 00:43:55 +00006115 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006116 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006117 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006118
Eli Friedman742421e2009-02-20 01:15:07 +00006119 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006120 // Allow casts of address-of-label differences if they are no-ops
6121 // or narrowing. (The narrowing case isn't actually guaranteed to
6122 // be constant-evaluatable except in some narrow cases which are hard
6123 // to detect here. We let it through on the assumption the user knows
6124 // what they are doing.)
6125 if (Result.isAddrLabelDiff())
6126 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006127 // Only allow casts of lvalues if they are lossless.
6128 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6129 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006130
Richard Smith911e1422012-01-30 22:27:01 +00006131 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6132 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006133 }
Mike Stump11289f42009-09-09 15:08:12 +00006134
Eli Friedmanc757de22011-03-25 00:43:55 +00006135 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006136 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6137
John McCall45d55e42010-05-07 21:00:08 +00006138 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006139 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006140 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006141
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006142 if (LV.getLValueBase()) {
6143 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006144 // FIXME: Allow a larger integer size than the pointer size, and allow
6145 // narrowing back down to pointer width in subsequent integral casts.
6146 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006147 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006148 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006149
Richard Smithcf74da72011-11-16 07:18:12 +00006150 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006151 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006152 return true;
6153 }
6154
Ken Dyck02990832010-01-15 12:37:54 +00006155 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6156 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006157 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006158 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006159
Eli Friedmanc757de22011-03-25 00:43:55 +00006160 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006161 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006162 if (!EvaluateComplex(SubExpr, C, Info))
6163 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006164 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006165 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006166
Eli Friedmanc757de22011-03-25 00:43:55 +00006167 case CK_FloatingToIntegral: {
6168 APFloat F(0.0);
6169 if (!EvaluateFloat(SubExpr, F, Info))
6170 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006171
Richard Smith357362d2011-12-13 06:39:58 +00006172 APSInt Value;
6173 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6174 return false;
6175 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006176 }
6177 }
Mike Stump11289f42009-09-09 15:08:12 +00006178
Eli Friedmanc757de22011-03-25 00:43:55 +00006179 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006180}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006181
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006182bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6183 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006184 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006185 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6186 return false;
6187 if (!LV.isComplexInt())
6188 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006189 return Success(LV.getComplexIntReal(), E);
6190 }
6191
6192 return Visit(E->getSubExpr());
6193}
6194
Eli Friedman4e7a2412009-02-27 04:45:43 +00006195bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006196 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006197 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006198 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6199 return false;
6200 if (!LV.isComplexInt())
6201 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006202 return Success(LV.getComplexIntImag(), E);
6203 }
6204
Richard Smith4a678122011-10-24 18:44:57 +00006205 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006206 return Success(0, E);
6207}
6208
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006209bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6210 return Success(E->getPackLength(), E);
6211}
6212
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006213bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6214 return Success(E->getValue(), E);
6215}
6216
Chris Lattner05706e882008-07-11 18:11:29 +00006217//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006218// Float Evaluation
6219//===----------------------------------------------------------------------===//
6220
6221namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006222class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006223 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006224 APFloat &Result;
6225public:
6226 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006227 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006228
Richard Smith2e312c82012-03-03 22:46:17 +00006229 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006230 Result = V.getFloat();
6231 return true;
6232 }
Eli Friedman24c01542008-08-22 00:06:13 +00006233
Richard Smithfddd3842011-12-30 21:15:51 +00006234 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006235 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6236 return true;
6237 }
6238
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006239 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006240
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006241 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006242 bool VisitBinaryOperator(const BinaryOperator *E);
6243 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006244 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006245
John McCallb1fb0d32010-05-07 22:08:54 +00006246 bool VisitUnaryReal(const UnaryOperator *E);
6247 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006248
Richard Smithfddd3842011-12-30 21:15:51 +00006249 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006250};
6251} // end anonymous namespace
6252
6253static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006254 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006255 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006256}
6257
Jay Foad39c79802011-01-12 09:06:06 +00006258static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006259 QualType ResultTy,
6260 const Expr *Arg,
6261 bool SNaN,
6262 llvm::APFloat &Result) {
6263 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6264 if (!S) return false;
6265
6266 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6267
6268 llvm::APInt fill;
6269
6270 // Treat empty strings as if they were zero.
6271 if (S->getString().empty())
6272 fill = llvm::APInt(32, 0);
6273 else if (S->getString().getAsInteger(0, fill))
6274 return false;
6275
6276 if (SNaN)
6277 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6278 else
6279 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6280 return true;
6281}
6282
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006283bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006284 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006285 default:
6286 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6287
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006288 case Builtin::BI__builtin_huge_val:
6289 case Builtin::BI__builtin_huge_valf:
6290 case Builtin::BI__builtin_huge_vall:
6291 case Builtin::BI__builtin_inf:
6292 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006293 case Builtin::BI__builtin_infl: {
6294 const llvm::fltSemantics &Sem =
6295 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006296 Result = llvm::APFloat::getInf(Sem);
6297 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006298 }
Mike Stump11289f42009-09-09 15:08:12 +00006299
John McCall16291492010-02-28 13:00:19 +00006300 case Builtin::BI__builtin_nans:
6301 case Builtin::BI__builtin_nansf:
6302 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006303 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6304 true, Result))
6305 return Error(E);
6306 return true;
John McCall16291492010-02-28 13:00:19 +00006307
Chris Lattner0b7282e2008-10-06 06:31:58 +00006308 case Builtin::BI__builtin_nan:
6309 case Builtin::BI__builtin_nanf:
6310 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006311 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006312 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006313 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6314 false, Result))
6315 return Error(E);
6316 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006317
6318 case Builtin::BI__builtin_fabs:
6319 case Builtin::BI__builtin_fabsf:
6320 case Builtin::BI__builtin_fabsl:
6321 if (!EvaluateFloat(E->getArg(0), Result, Info))
6322 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006323
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006324 if (Result.isNegative())
6325 Result.changeSign();
6326 return true;
6327
Mike Stump11289f42009-09-09 15:08:12 +00006328 case Builtin::BI__builtin_copysign:
6329 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006330 case Builtin::BI__builtin_copysignl: {
6331 APFloat RHS(0.);
6332 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6333 !EvaluateFloat(E->getArg(1), RHS, Info))
6334 return false;
6335 Result.copySign(RHS);
6336 return true;
6337 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006338 }
6339}
6340
John McCallb1fb0d32010-05-07 22:08:54 +00006341bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006342 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6343 ComplexValue CV;
6344 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6345 return false;
6346 Result = CV.FloatReal;
6347 return true;
6348 }
6349
6350 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006351}
6352
6353bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006354 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6355 ComplexValue CV;
6356 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6357 return false;
6358 Result = CV.FloatImag;
6359 return true;
6360 }
6361
Richard Smith4a678122011-10-24 18:44:57 +00006362 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006363 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6364 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006365 return true;
6366}
6367
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006368bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006369 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006370 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006371 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006372 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006373 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006374 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6375 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006376 Result.changeSign();
6377 return true;
6378 }
6379}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006380
Eli Friedman24c01542008-08-22 00:06:13 +00006381bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006382 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6383 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006384
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006385 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006386 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6387 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006388 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006389 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00006390 return false;
6391
6392 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006393 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006394 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00006395 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006396 break;
John McCalle3027922010-08-25 11:45:40 +00006397 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00006398 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006399 break;
John McCalle3027922010-08-25 11:45:40 +00006400 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00006401 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006402 break;
John McCalle3027922010-08-25 11:45:40 +00006403 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00006404 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006405 break;
Eli Friedman24c01542008-08-22 00:06:13 +00006406 }
Richard Smithc8042322012-02-01 05:53:12 +00006407
6408 if (Result.isInfinity() || Result.isNaN())
6409 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
6410 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00006411}
6412
6413bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6414 Result = E->getValue();
6415 return true;
6416}
6417
Peter Collingbournee9200682011-05-13 03:29:01 +00006418bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6419 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006420
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006421 switch (E->getCastKind()) {
6422 default:
Richard Smith11562c52011-10-28 17:51:58 +00006423 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006424
6425 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006426 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006427 return EvaluateInteger(SubExpr, IntResult, Info) &&
6428 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6429 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006430 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006431
6432 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006433 if (!Visit(SubExpr))
6434 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006435 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6436 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006437 }
John McCalld7646252010-11-14 08:17:51 +00006438
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006439 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006440 ComplexValue V;
6441 if (!EvaluateComplex(SubExpr, V, Info))
6442 return false;
6443 Result = V.getComplexFloatReal();
6444 return true;
6445 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006446 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006447}
6448
Eli Friedman24c01542008-08-22 00:06:13 +00006449//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006450// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006451//===----------------------------------------------------------------------===//
6452
6453namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006454class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006455 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006456 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006457
Anders Carlsson537969c2008-11-16 20:27:53 +00006458public:
John McCall93d91dc2010-05-07 17:22:02 +00006459 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006460 : ExprEvaluatorBaseTy(info), Result(Result) {}
6461
Richard Smith2e312c82012-03-03 22:46:17 +00006462 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006463 Result.setFrom(V);
6464 return true;
6465 }
Mike Stump11289f42009-09-09 15:08:12 +00006466
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006467 bool ZeroInitialization(const Expr *E);
6468
Anders Carlsson537969c2008-11-16 20:27:53 +00006469 //===--------------------------------------------------------------------===//
6470 // Visitor Methods
6471 //===--------------------------------------------------------------------===//
6472
Peter Collingbournee9200682011-05-13 03:29:01 +00006473 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006474 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006475 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006476 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006477 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006478};
6479} // end anonymous namespace
6480
John McCall93d91dc2010-05-07 17:22:02 +00006481static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6482 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006483 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006484 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006485}
6486
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006487bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006488 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006489 if (ElemTy->isRealFloatingType()) {
6490 Result.makeComplexFloat();
6491 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6492 Result.FloatReal = Zero;
6493 Result.FloatImag = Zero;
6494 } else {
6495 Result.makeComplexInt();
6496 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6497 Result.IntReal = Zero;
6498 Result.IntImag = Zero;
6499 }
6500 return true;
6501}
6502
Peter Collingbournee9200682011-05-13 03:29:01 +00006503bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6504 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006505
6506 if (SubExpr->getType()->isRealFloatingType()) {
6507 Result.makeComplexFloat();
6508 APFloat &Imag = Result.FloatImag;
6509 if (!EvaluateFloat(SubExpr, Imag, Info))
6510 return false;
6511
6512 Result.FloatReal = APFloat(Imag.getSemantics());
6513 return true;
6514 } else {
6515 assert(SubExpr->getType()->isIntegerType() &&
6516 "Unexpected imaginary literal.");
6517
6518 Result.makeComplexInt();
6519 APSInt &Imag = Result.IntImag;
6520 if (!EvaluateInteger(SubExpr, Imag, Info))
6521 return false;
6522
6523 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6524 return true;
6525 }
6526}
6527
Peter Collingbournee9200682011-05-13 03:29:01 +00006528bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006529
John McCallfcef3cf2010-12-14 17:51:41 +00006530 switch (E->getCastKind()) {
6531 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006532 case CK_BaseToDerived:
6533 case CK_DerivedToBase:
6534 case CK_UncheckedDerivedToBase:
6535 case CK_Dynamic:
6536 case CK_ToUnion:
6537 case CK_ArrayToPointerDecay:
6538 case CK_FunctionToPointerDecay:
6539 case CK_NullToPointer:
6540 case CK_NullToMemberPointer:
6541 case CK_BaseToDerivedMemberPointer:
6542 case CK_DerivedToBaseMemberPointer:
6543 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006544 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006545 case CK_ConstructorConversion:
6546 case CK_IntegralToPointer:
6547 case CK_PointerToIntegral:
6548 case CK_PointerToBoolean:
6549 case CK_ToVoid:
6550 case CK_VectorSplat:
6551 case CK_IntegralCast:
6552 case CK_IntegralToBoolean:
6553 case CK_IntegralToFloating:
6554 case CK_FloatingToIntegral:
6555 case CK_FloatingToBoolean:
6556 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006557 case CK_CPointerToObjCPointerCast:
6558 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006559 case CK_AnyPointerToBlockPointerCast:
6560 case CK_ObjCObjectLValueCast:
6561 case CK_FloatingComplexToReal:
6562 case CK_FloatingComplexToBoolean:
6563 case CK_IntegralComplexToReal:
6564 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006565 case CK_ARCProduceObject:
6566 case CK_ARCConsumeObject:
6567 case CK_ARCReclaimReturnedObject:
6568 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006569 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006570 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006571 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006572 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006573
John McCallfcef3cf2010-12-14 17:51:41 +00006574 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006575 case CK_AtomicToNonAtomic:
6576 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006577 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006578 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006579
6580 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006581 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006582 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006583 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006584
6585 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006586 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006587 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006588 return false;
6589
John McCallfcef3cf2010-12-14 17:51:41 +00006590 Result.makeComplexFloat();
6591 Result.FloatImag = APFloat(Real.getSemantics());
6592 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006593 }
6594
John McCallfcef3cf2010-12-14 17:51:41 +00006595 case CK_FloatingComplexCast: {
6596 if (!Visit(E->getSubExpr()))
6597 return false;
6598
6599 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6600 QualType From
6601 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6602
Richard Smith357362d2011-12-13 06:39:58 +00006603 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6604 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006605 }
6606
6607 case CK_FloatingComplexToIntegralComplex: {
6608 if (!Visit(E->getSubExpr()))
6609 return false;
6610
6611 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6612 QualType From
6613 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6614 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006615 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6616 To, Result.IntReal) &&
6617 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6618 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006619 }
6620
6621 case CK_IntegralRealToComplex: {
6622 APSInt &Real = Result.IntReal;
6623 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6624 return false;
6625
6626 Result.makeComplexInt();
6627 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6628 return true;
6629 }
6630
6631 case CK_IntegralComplexCast: {
6632 if (!Visit(E->getSubExpr()))
6633 return false;
6634
6635 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6636 QualType From
6637 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6638
Richard Smith911e1422012-01-30 22:27:01 +00006639 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6640 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006641 return true;
6642 }
6643
6644 case CK_IntegralComplexToFloatingComplex: {
6645 if (!Visit(E->getSubExpr()))
6646 return false;
6647
Ted Kremenek28831752012-08-23 20:46:57 +00006648 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006649 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006650 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006651 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006652 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6653 To, Result.FloatReal) &&
6654 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6655 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006656 }
6657 }
6658
6659 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006660}
6661
John McCall93d91dc2010-05-07 17:22:02 +00006662bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006663 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006664 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6665
Richard Smith253c2a32012-01-27 01:14:48 +00006666 bool LHSOK = Visit(E->getLHS());
6667 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006668 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006669
John McCall93d91dc2010-05-07 17:22:02 +00006670 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006671 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006672 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006673
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006674 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6675 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006676 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006677 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006678 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006679 if (Result.isComplexFloat()) {
6680 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6681 APFloat::rmNearestTiesToEven);
6682 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6683 APFloat::rmNearestTiesToEven);
6684 } else {
6685 Result.getComplexIntReal() += RHS.getComplexIntReal();
6686 Result.getComplexIntImag() += RHS.getComplexIntImag();
6687 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006688 break;
John McCalle3027922010-08-25 11:45:40 +00006689 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006690 if (Result.isComplexFloat()) {
6691 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6692 APFloat::rmNearestTiesToEven);
6693 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6694 APFloat::rmNearestTiesToEven);
6695 } else {
6696 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6697 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6698 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006699 break;
John McCalle3027922010-08-25 11:45:40 +00006700 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006701 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006702 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006703 APFloat &LHS_r = LHS.getComplexFloatReal();
6704 APFloat &LHS_i = LHS.getComplexFloatImag();
6705 APFloat &RHS_r = RHS.getComplexFloatReal();
6706 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006707
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006708 APFloat Tmp = LHS_r;
6709 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6710 Result.getComplexFloatReal() = Tmp;
6711 Tmp = LHS_i;
6712 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6713 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6714
6715 Tmp = LHS_r;
6716 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6717 Result.getComplexFloatImag() = Tmp;
6718 Tmp = LHS_i;
6719 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6720 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6721 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006722 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006723 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006724 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6725 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006726 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006727 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6728 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6729 }
6730 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006731 case BO_Div:
6732 if (Result.isComplexFloat()) {
6733 ComplexValue LHS = Result;
6734 APFloat &LHS_r = LHS.getComplexFloatReal();
6735 APFloat &LHS_i = LHS.getComplexFloatImag();
6736 APFloat &RHS_r = RHS.getComplexFloatReal();
6737 APFloat &RHS_i = RHS.getComplexFloatImag();
6738 APFloat &Res_r = Result.getComplexFloatReal();
6739 APFloat &Res_i = Result.getComplexFloatImag();
6740
6741 APFloat Den = RHS_r;
6742 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6743 APFloat Tmp = RHS_i;
6744 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6745 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6746
6747 Res_r = LHS_r;
6748 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6749 Tmp = LHS_i;
6750 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6751 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6752 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6753
6754 Res_i = LHS_i;
6755 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6756 Tmp = LHS_r;
6757 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6758 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6759 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6760 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006761 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6762 return Error(E, diag::note_expr_divide_by_zero);
6763
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006764 ComplexValue LHS = Result;
6765 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6766 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6767 Result.getComplexIntReal() =
6768 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6769 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6770 Result.getComplexIntImag() =
6771 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6772 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6773 }
6774 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006775 }
6776
John McCall93d91dc2010-05-07 17:22:02 +00006777 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006778}
6779
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006780bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6781 // Get the operand value into 'Result'.
6782 if (!Visit(E->getSubExpr()))
6783 return false;
6784
6785 switch (E->getOpcode()) {
6786 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006787 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006788 case UO_Extension:
6789 return true;
6790 case UO_Plus:
6791 // The result is always just the subexpr.
6792 return true;
6793 case UO_Minus:
6794 if (Result.isComplexFloat()) {
6795 Result.getComplexFloatReal().changeSign();
6796 Result.getComplexFloatImag().changeSign();
6797 }
6798 else {
6799 Result.getComplexIntReal() = -Result.getComplexIntReal();
6800 Result.getComplexIntImag() = -Result.getComplexIntImag();
6801 }
6802 return true;
6803 case UO_Not:
6804 if (Result.isComplexFloat())
6805 Result.getComplexFloatImag().changeSign();
6806 else
6807 Result.getComplexIntImag() = -Result.getComplexIntImag();
6808 return true;
6809 }
6810}
6811
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006812bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6813 if (E->getNumInits() == 2) {
6814 if (E->getType()->isComplexType()) {
6815 Result.makeComplexFloat();
6816 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6817 return false;
6818 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6819 return false;
6820 } else {
6821 Result.makeComplexInt();
6822 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6823 return false;
6824 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6825 return false;
6826 }
6827 return true;
6828 }
6829 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6830}
6831
Anders Carlsson537969c2008-11-16 20:27:53 +00006832//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006833// Void expression evaluation, primarily for a cast to void on the LHS of a
6834// comma operator
6835//===----------------------------------------------------------------------===//
6836
6837namespace {
6838class VoidExprEvaluator
6839 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6840public:
6841 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6842
Richard Smith2e312c82012-03-03 22:46:17 +00006843 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006844
6845 bool VisitCastExpr(const CastExpr *E) {
6846 switch (E->getCastKind()) {
6847 default:
6848 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6849 case CK_ToVoid:
6850 VisitIgnoredValue(E->getSubExpr());
6851 return true;
6852 }
6853 }
6854};
6855} // end anonymous namespace
6856
6857static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6858 assert(E->isRValue() && E->getType()->isVoidType());
6859 return VoidExprEvaluator(Info).Visit(E);
6860}
6861
6862//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006863// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006864//===----------------------------------------------------------------------===//
6865
Richard Smith2e312c82012-03-03 22:46:17 +00006866static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006867 // In C, function designators are not lvalues, but we evaluate them as if they
6868 // are.
6869 if (E->isGLValue() || E->getType()->isFunctionType()) {
6870 LValue LV;
6871 if (!EvaluateLValue(E, LV, Info))
6872 return false;
6873 LV.moveInto(Result);
6874 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006875 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006876 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006877 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006878 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006879 return false;
John McCall45d55e42010-05-07 21:00:08 +00006880 } else if (E->getType()->hasPointerRepresentation()) {
6881 LValue LV;
6882 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006883 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006884 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006885 } else if (E->getType()->isRealFloatingType()) {
6886 llvm::APFloat F(0.0);
6887 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006888 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006889 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006890 } else if (E->getType()->isAnyComplexType()) {
6891 ComplexValue C;
6892 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006893 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006894 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006895 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006896 MemberPtr P;
6897 if (!EvaluateMemberPointer(E, P, Info))
6898 return false;
6899 P.moveInto(Result);
6900 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006901 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006902 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006903 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006904 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006905 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006906 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006907 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006908 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006909 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006910 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6911 return false;
6912 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006913 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006914 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006915 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006916 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006917 if (!EvaluateVoid(E, Info))
6918 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006919 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006920 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006921 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006922 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006923 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006924 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006925 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006926
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006927 return true;
6928}
6929
Richard Smithb228a862012-02-15 02:18:13 +00006930/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6931/// cases, the in-place evaluation is essential, since later initializers for
6932/// an object can indirectly refer to subobjects which were initialized earlier.
6933static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6934 const Expr *E, CheckConstantExpressionKind CCEK,
6935 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006936 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006937 return false;
6938
6939 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006940 // Evaluate arrays and record types in-place, so that later initializers can
6941 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006942 if (E->getType()->isArrayType())
6943 return EvaluateArray(E, This, Result, Info);
6944 else if (E->getType()->isRecordType())
6945 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006946 }
6947
6948 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006949 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006950}
6951
Richard Smithf57d8cb2011-12-09 22:58:01 +00006952/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6953/// lvalue-to-rvalue cast if it is an lvalue.
6954static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006955 if (!CheckLiteralType(Info, E))
6956 return false;
6957
Richard Smith2e312c82012-03-03 22:46:17 +00006958 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006959 return false;
6960
6961 if (E->isGLValue()) {
6962 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00006963 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00006964 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006965 return false;
6966 }
6967
Richard Smith2e312c82012-03-03 22:46:17 +00006968 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00006969 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006970}
Richard Smith11562c52011-10-28 17:51:58 +00006971
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006972static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6973 const ASTContext &Ctx, bool &IsConst) {
6974 // Fast-path evaluations of integer literals, since we sometimes see files
6975 // containing vast quantities of these.
6976 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6977 Result.Val = APValue(APSInt(L->getValue(),
6978 L->getType()->isUnsignedIntegerType()));
6979 IsConst = true;
6980 return true;
6981 }
6982
6983 // FIXME: Evaluating values of large array and record types can cause
6984 // performance problems. Only do so in C++11 for now.
6985 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6986 Exp->getType()->isRecordType()) &&
6987 !Ctx.getLangOpts().CPlusPlus11) {
6988 IsConst = false;
6989 return true;
6990 }
6991 return false;
6992}
6993
6994
Richard Smith7b553f12011-10-29 00:50:52 +00006995/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00006996/// any crazy technique (that has nothing to do with language standards) that
6997/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00006998/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6999/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007000bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007001 bool IsConst;
7002 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7003 return IsConst;
7004
Richard Smithf57d8cb2011-12-09 22:58:01 +00007005 EvalInfo Info(Ctx, Result);
7006 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007007}
7008
Jay Foad39c79802011-01-12 09:06:06 +00007009bool Expr::EvaluateAsBooleanCondition(bool &Result,
7010 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007011 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007012 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007013 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007014}
7015
Richard Smith5fab0c92011-12-28 19:48:30 +00007016bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7017 SideEffectsKind AllowSideEffects) const {
7018 if (!getType()->isIntegralOrEnumerationType())
7019 return false;
7020
Richard Smith11562c52011-10-28 17:51:58 +00007021 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007022 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7023 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007024 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007025
Richard Smith11562c52011-10-28 17:51:58 +00007026 Result = ExprResult.Val.getInt();
7027 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007028}
7029
Jay Foad39c79802011-01-12 09:06:06 +00007030bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007031 EvalInfo Info(Ctx, Result);
7032
John McCall45d55e42010-05-07 21:00:08 +00007033 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007034 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7035 !CheckLValueConstantExpression(Info, getExprLoc(),
7036 Ctx.getLValueReferenceType(getType()), LV))
7037 return false;
7038
Richard Smith2e312c82012-03-03 22:46:17 +00007039 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007040 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007041}
7042
Richard Smithd0b4dd62011-12-19 06:19:21 +00007043bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7044 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007045 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007046 // FIXME: Evaluating initializers for large array and record types can cause
7047 // performance problems. Only do so in C++11 for now.
7048 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007049 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007050 return false;
7051
Richard Smithd0b4dd62011-12-19 06:19:21 +00007052 Expr::EvalStatus EStatus;
7053 EStatus.Diag = &Notes;
7054
7055 EvalInfo InitInfo(Ctx, EStatus);
7056 InitInfo.setEvaluatingDecl(VD, Value);
7057
7058 LValue LVal;
7059 LVal.set(VD);
7060
Richard Smithfddd3842011-12-30 21:15:51 +00007061 // C++11 [basic.start.init]p2:
7062 // Variables with static storage duration or thread storage duration shall be
7063 // zero-initialized before any other initialization takes place.
7064 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007065 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007066 !VD->getType()->isReferenceType()) {
7067 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007068 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
7069 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007070 return false;
7071 }
7072
Richard Smithb228a862012-02-15 02:18:13 +00007073 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
7074 /*AllowNonLiteralTypes=*/true) ||
7075 EStatus.HasSideEffects)
7076 return false;
7077
7078 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7079 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007080}
7081
Richard Smith7b553f12011-10-29 00:50:52 +00007082/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7083/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007084bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007085 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007086 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007087}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007088
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007089APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007090 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007091 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007092 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007093 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007094 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007095 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007096 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007097
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007098 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007099}
John McCall864e3962010-05-07 05:32:02 +00007100
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007101void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7102 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7103 bool IsConst;
7104 EvalResult EvalResult;
7105 EvalResult.Diag = Diags;
7106 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7107 EvalInfo Info(Ctx, EvalResult, true);
7108 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7109 }
7110}
7111
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007112 bool Expr::EvalResult::isGlobalLValue() const {
7113 assert(Val.isLValue());
7114 return IsGlobalLValue(Val.getLValueBase());
7115 }
7116
7117
John McCall864e3962010-05-07 05:32:02 +00007118/// isIntegerConstantExpr - this recursive routine will test if an expression is
7119/// an integer constant expression.
7120
7121/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7122/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007123
7124// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007125// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7126// and a (possibly null) SourceLocation indicating the location of the problem.
7127//
John McCall864e3962010-05-07 05:32:02 +00007128// Note that to reduce code duplication, this helper does no evaluation
7129// itself; the caller checks whether the expression is evaluatable, and
7130// in the rare cases where CheckICE actually cares about the evaluated
7131// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007132
Dan Gohman28ade552010-07-26 21:25:24 +00007133namespace {
7134
Richard Smith9e575da2012-12-28 13:25:52 +00007135enum ICEKind {
7136 /// This expression is an ICE.
7137 IK_ICE,
7138 /// This expression is not an ICE, but if it isn't evaluated, it's
7139 /// a legal subexpression for an ICE. This return value is used to handle
7140 /// the comma operator in C99 mode, and non-constant subexpressions.
7141 IK_ICEIfUnevaluated,
7142 /// This expression is not an ICE, and is not a legal subexpression for one.
7143 IK_NotICE
7144};
7145
John McCall864e3962010-05-07 05:32:02 +00007146struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007147 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007148 SourceLocation Loc;
7149
Richard Smith9e575da2012-12-28 13:25:52 +00007150 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007151};
7152
Dan Gohman28ade552010-07-26 21:25:24 +00007153}
7154
Richard Smith9e575da2012-12-28 13:25:52 +00007155static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7156
7157static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007158
7159static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7160 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007161 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007162 !EVResult.Val.isInt())
7163 return ICEDiag(IK_NotICE, E->getLocStart());
7164
John McCall864e3962010-05-07 05:32:02 +00007165 return NoDiag();
7166}
7167
7168static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7169 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007170 if (!E->getType()->isIntegralOrEnumerationType())
7171 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007172
7173 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007174#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007175#define STMT(Node, Base) case Expr::Node##Class:
7176#define EXPR(Node, Base)
7177#include "clang/AST/StmtNodes.inc"
7178 case Expr::PredefinedExprClass:
7179 case Expr::FloatingLiteralClass:
7180 case Expr::ImaginaryLiteralClass:
7181 case Expr::StringLiteralClass:
7182 case Expr::ArraySubscriptExprClass:
7183 case Expr::MemberExprClass:
7184 case Expr::CompoundAssignOperatorClass:
7185 case Expr::CompoundLiteralExprClass:
7186 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007187 case Expr::DesignatedInitExprClass:
7188 case Expr::ImplicitValueInitExprClass:
7189 case Expr::ParenListExprClass:
7190 case Expr::VAArgExprClass:
7191 case Expr::AddrLabelExprClass:
7192 case Expr::StmtExprClass:
7193 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007194 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007195 case Expr::CXXDynamicCastExprClass:
7196 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007197 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007198 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007199 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007200 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007201 case Expr::CXXThisExprClass:
7202 case Expr::CXXThrowExprClass:
7203 case Expr::CXXNewExprClass:
7204 case Expr::CXXDeleteExprClass:
7205 case Expr::CXXPseudoDestructorExprClass:
7206 case Expr::UnresolvedLookupExprClass:
7207 case Expr::DependentScopeDeclRefExprClass:
7208 case Expr::CXXConstructExprClass:
7209 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007210 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007211 case Expr::CXXTemporaryObjectExprClass:
7212 case Expr::CXXUnresolvedConstructExprClass:
7213 case Expr::CXXDependentScopeMemberExprClass:
7214 case Expr::UnresolvedMemberExprClass:
7215 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007216 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007217 case Expr::ObjCArrayLiteralClass:
7218 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007219 case Expr::ObjCEncodeExprClass:
7220 case Expr::ObjCMessageExprClass:
7221 case Expr::ObjCSelectorExprClass:
7222 case Expr::ObjCProtocolExprClass:
7223 case Expr::ObjCIvarRefExprClass:
7224 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007225 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007226 case Expr::ObjCIsaExprClass:
7227 case Expr::ShuffleVectorExprClass:
7228 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007229 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007230 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007231 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007232 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007233 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007234 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007235 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007236 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007237 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007238 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007239 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007240 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007241 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007242
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007243 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007244 case Expr::GNUNullExprClass:
7245 // GCC considers the GNU __null value to be an integral constant expression.
7246 return NoDiag();
7247
John McCall7c454bb2011-07-15 05:09:51 +00007248 case Expr::SubstNonTypeTemplateParmExprClass:
7249 return
7250 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7251
John McCall864e3962010-05-07 05:32:02 +00007252 case Expr::ParenExprClass:
7253 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007254 case Expr::GenericSelectionExprClass:
7255 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007256 case Expr::IntegerLiteralClass:
7257 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007258 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007259 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007260 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007261 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007262 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007263 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007264 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007265 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007266 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007267 return NoDiag();
7268 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007269 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007270 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7271 // constant expressions, but they can never be ICEs because an ICE cannot
7272 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007273 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007274 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007275 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007276 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007277 }
Richard Smith6365c912012-02-24 22:12:32 +00007278 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007279 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7280 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007281 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007282 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007283 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007284 // Parameter variables are never constants. Without this check,
7285 // getAnyInitializer() can find a default argument, which leads
7286 // to chaos.
7287 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007288 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007289
7290 // C++ 7.1.5.1p2
7291 // A variable of non-volatile const-qualified integral or enumeration
7292 // type initialized by an ICE can be used in ICEs.
7293 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007294 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007295 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007296
Richard Smithd0b4dd62011-12-19 06:19:21 +00007297 const VarDecl *VD;
7298 // Look for a declaration of this variable that has an initializer, and
7299 // check whether it is an ICE.
7300 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7301 return NoDiag();
7302 else
Richard Smith9e575da2012-12-28 13:25:52 +00007303 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007304 }
7305 }
Richard Smith9e575da2012-12-28 13:25:52 +00007306 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007307 }
John McCall864e3962010-05-07 05:32:02 +00007308 case Expr::UnaryOperatorClass: {
7309 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7310 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007311 case UO_PostInc:
7312 case UO_PostDec:
7313 case UO_PreInc:
7314 case UO_PreDec:
7315 case UO_AddrOf:
7316 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007317 // C99 6.6/3 allows increment and decrement within unevaluated
7318 // subexpressions of constant expressions, but they can never be ICEs
7319 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007320 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007321 case UO_Extension:
7322 case UO_LNot:
7323 case UO_Plus:
7324 case UO_Minus:
7325 case UO_Not:
7326 case UO_Real:
7327 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007328 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007329 }
Richard Smith9e575da2012-12-28 13:25:52 +00007330
John McCall864e3962010-05-07 05:32:02 +00007331 // OffsetOf falls through here.
7332 }
7333 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007334 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7335 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7336 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7337 // compliance: we should warn earlier for offsetof expressions with
7338 // array subscripts that aren't ICEs, and if the array subscripts
7339 // are ICEs, the value of the offsetof must be an integer constant.
7340 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007341 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007342 case Expr::UnaryExprOrTypeTraitExprClass: {
7343 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7344 if ((Exp->getKind() == UETT_SizeOf) &&
7345 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007346 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007347 return NoDiag();
7348 }
7349 case Expr::BinaryOperatorClass: {
7350 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7351 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007352 case BO_PtrMemD:
7353 case BO_PtrMemI:
7354 case BO_Assign:
7355 case BO_MulAssign:
7356 case BO_DivAssign:
7357 case BO_RemAssign:
7358 case BO_AddAssign:
7359 case BO_SubAssign:
7360 case BO_ShlAssign:
7361 case BO_ShrAssign:
7362 case BO_AndAssign:
7363 case BO_XorAssign:
7364 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007365 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7366 // constant expressions, but they can never be ICEs because an ICE cannot
7367 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007368 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007369
John McCalle3027922010-08-25 11:45:40 +00007370 case BO_Mul:
7371 case BO_Div:
7372 case BO_Rem:
7373 case BO_Add:
7374 case BO_Sub:
7375 case BO_Shl:
7376 case BO_Shr:
7377 case BO_LT:
7378 case BO_GT:
7379 case BO_LE:
7380 case BO_GE:
7381 case BO_EQ:
7382 case BO_NE:
7383 case BO_And:
7384 case BO_Xor:
7385 case BO_Or:
7386 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007387 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7388 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007389 if (Exp->getOpcode() == BO_Div ||
7390 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007391 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007392 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007393 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007394 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007395 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007396 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007397 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007398 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007399 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007400 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007401 }
7402 }
7403 }
John McCalle3027922010-08-25 11:45:40 +00007404 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007405 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007406 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7407 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007408 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7409 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007410 } else {
7411 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007412 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007413 }
7414 }
Richard Smith9e575da2012-12-28 13:25:52 +00007415 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007416 }
John McCalle3027922010-08-25 11:45:40 +00007417 case BO_LAnd:
7418 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007419 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7420 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007421 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007422 // Rare case where the RHS has a comma "side-effect"; we need
7423 // to actually check the condition to see whether the side
7424 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007425 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007426 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007427 return RHSResult;
7428 return NoDiag();
7429 }
7430
Richard Smith9e575da2012-12-28 13:25:52 +00007431 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007432 }
7433 }
7434 }
7435 case Expr::ImplicitCastExprClass:
7436 case Expr::CStyleCastExprClass:
7437 case Expr::CXXFunctionalCastExprClass:
7438 case Expr::CXXStaticCastExprClass:
7439 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007440 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007441 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007442 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007443 if (isa<ExplicitCastExpr>(E)) {
7444 if (const FloatingLiteral *FL
7445 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7446 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7447 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7448 APSInt IgnoredVal(DestWidth, !DestSigned);
7449 bool Ignored;
7450 // If the value does not fit in the destination type, the behavior is
7451 // undefined, so we are not required to treat it as a constant
7452 // expression.
7453 if (FL->getValue().convertToInteger(IgnoredVal,
7454 llvm::APFloat::rmTowardZero,
7455 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007456 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007457 return NoDiag();
7458 }
7459 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007460 switch (cast<CastExpr>(E)->getCastKind()) {
7461 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007462 case CK_AtomicToNonAtomic:
7463 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007464 case CK_NoOp:
7465 case CK_IntegralToBoolean:
7466 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007467 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007468 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007469 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007470 }
John McCall864e3962010-05-07 05:32:02 +00007471 }
John McCallc07a0c72011-02-17 10:25:35 +00007472 case Expr::BinaryConditionalOperatorClass: {
7473 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7474 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007475 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007476 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007477 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7478 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7479 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007480 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007481 return FalseResult;
7482 }
John McCall864e3962010-05-07 05:32:02 +00007483 case Expr::ConditionalOperatorClass: {
7484 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7485 // If the condition (ignoring parens) is a __builtin_constant_p call,
7486 // then only the true side is actually considered in an integer constant
7487 // expression, and it is fully evaluated. This is an important GNU
7488 // extension. See GCC PR38377 for discussion.
7489 if (const CallExpr *CallCE
7490 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007491 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7492 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007493 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007494 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007495 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007496
Richard Smithf57d8cb2011-12-09 22:58:01 +00007497 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7498 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007499
Richard Smith9e575da2012-12-28 13:25:52 +00007500 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007501 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007502 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007503 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007504 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007505 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007506 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007507 return NoDiag();
7508 // Rare case where the diagnostics depend on which side is evaluated
7509 // Note that if we get here, CondResult is 0, and at least one of
7510 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007511 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007512 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007513 return TrueResult;
7514 }
7515 case Expr::CXXDefaultArgExprClass:
7516 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007517 case Expr::CXXDefaultInitExprClass:
7518 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007519 case Expr::ChooseExprClass: {
7520 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7521 }
7522 }
7523
David Blaikiee4d798f2012-01-20 21:50:17 +00007524 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007525}
7526
Richard Smithf57d8cb2011-12-09 22:58:01 +00007527/// Evaluate an expression as a C++11 integral constant expression.
7528static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7529 const Expr *E,
7530 llvm::APSInt *Value,
7531 SourceLocation *Loc) {
7532 if (!E->getType()->isIntegralOrEnumerationType()) {
7533 if (Loc) *Loc = E->getExprLoc();
7534 return false;
7535 }
7536
Richard Smith66e05fe2012-01-18 05:21:49 +00007537 APValue Result;
7538 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007539 return false;
7540
Richard Smith66e05fe2012-01-18 05:21:49 +00007541 assert(Result.isInt() && "pointer cast to int is not an ICE");
7542 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007543 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007544}
7545
Richard Smith92b1ce02011-12-12 09:28:41 +00007546bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007547 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007548 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7549
Richard Smith9e575da2012-12-28 13:25:52 +00007550 ICEDiag D = CheckICE(this, Ctx);
7551 if (D.Kind != IK_ICE) {
7552 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007553 return false;
7554 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007555 return true;
7556}
7557
7558bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7559 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007560 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007561 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7562
7563 if (!isIntegerConstantExpr(Ctx, Loc))
7564 return false;
7565 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007566 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007567 return true;
7568}
Richard Smith66e05fe2012-01-18 05:21:49 +00007569
Richard Smith98a0a492012-02-14 21:38:30 +00007570bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007571 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007572}
7573
Richard Smith66e05fe2012-01-18 05:21:49 +00007574bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7575 SourceLocation *Loc) const {
7576 // We support this checking in C++98 mode in order to diagnose compatibility
7577 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007578 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007579
Richard Smith98a0a492012-02-14 21:38:30 +00007580 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007581 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007582 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007583 Status.Diag = &Diags;
7584 EvalInfo Info(Ctx, Status);
7585
7586 APValue Scratch;
7587 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7588
7589 if (!Diags.empty()) {
7590 IsConstExpr = false;
7591 if (Loc) *Loc = Diags[0].first;
7592 } else if (!IsConstExpr) {
7593 // FIXME: This shouldn't happen.
7594 if (Loc) *Loc = getExprLoc();
7595 }
7596
7597 return IsConstExpr;
7598}
Richard Smith253c2a32012-01-27 01:14:48 +00007599
7600bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007601 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007602 PartialDiagnosticAt> &Diags) {
7603 // FIXME: It would be useful to check constexpr function templates, but at the
7604 // moment the constant expression evaluator cannot cope with the non-rigorous
7605 // ASTs which we build for dependent expressions.
7606 if (FD->isDependentContext())
7607 return true;
7608
7609 Expr::EvalStatus Status;
7610 Status.Diag = &Diags;
7611
7612 EvalInfo Info(FD->getASTContext(), Status);
7613 Info.CheckingPotentialConstantExpression = true;
7614
7615 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7616 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7617
7618 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7619 // is a temporary being used as the 'this' pointer.
7620 LValue This;
7621 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007622 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007623
Richard Smith253c2a32012-01-27 01:14:48 +00007624 ArrayRef<const Expr*> Args;
7625
7626 SourceLocation Loc = FD->getLocation();
7627
Richard Smith2e312c82012-03-03 22:46:17 +00007628 APValue Scratch;
7629 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00007630 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00007631 else
Richard Smith253c2a32012-01-27 01:14:48 +00007632 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7633 Args, FD->getBody(), Info, Scratch);
7634
7635 return Diags.empty();
7636}