blob: 5d153c422f84a403b6417eae135ef7c69ab5deb2 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smithd62306a2011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000070 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000071 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +000092 }
93
Richard Smitha8105bc2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith80815602011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith80815602011-11-07 05:07:52 +0000122 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000124 }
125
Richard Smitha8105bc2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000130 };
131
Richard Smith96e0c102011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smitha8105bc2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000141
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000152
Richard Smith80815602011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smitha8105bc2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith96e0c102011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith96e0c102011-11-04 02:25:55 +0000229 }
Richard Smith66c96992012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith96e0c102011-11-04 02:25:55 +0000252 return;
253 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000263 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smith254a73d2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000274
Richard Smithf6f003a2011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smithb228a862012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smithd62306a2011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000289 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000290
Eli Friedman4830ec82012-06-25 21:21:08 +0000291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000293 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
296 MapTy Temporaries;
297
Richard Smithf6f003a2011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000300 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000302 };
303
Richard Smith852c9db2013-04-20 22:23:05 +0000304 /// Temporarily override 'this'.
305 class ThisOverrideRAII {
306 public:
307 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
308 : Frame(Frame), OldThis(Frame.This) {
309 if (Enable)
310 Frame.This = NewThis;
311 }
312 ~ThisOverrideRAII() {
313 Frame.This = OldThis;
314 }
315 private:
316 CallStackFrame &Frame;
317 const LValue *OldThis;
318 };
319
Richard Smith92b1ce02011-12-12 09:28:41 +0000320 /// A partial diagnostic which we might know in advance that we are not going
321 /// to emit.
322 class OptionalDiagnostic {
323 PartialDiagnostic *Diag;
324
325 public:
326 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
327
328 template<typename T>
329 OptionalDiagnostic &operator<<(const T &v) {
330 if (Diag)
331 *Diag << v;
332 return *this;
333 }
Richard Smithfe800032012-01-31 04:08:20 +0000334
335 OptionalDiagnostic &operator<<(const APSInt &I) {
336 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000337 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000338 I.toString(Buffer);
339 *Diag << StringRef(Buffer.data(), Buffer.size());
340 }
341 return *this;
342 }
343
344 OptionalDiagnostic &operator<<(const APFloat &F) {
345 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000346 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000347 F.toString(Buffer);
348 *Diag << StringRef(Buffer.data(), Buffer.size());
349 }
350 return *this;
351 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000352 };
353
Richard Smithb228a862012-02-15 02:18:13 +0000354 /// EvalInfo - This is a private struct used by the evaluator to capture
355 /// information about a subexpression as it is folded. It retains information
356 /// about the AST context, but also maintains information about the folded
357 /// expression.
358 ///
359 /// If an expression could be evaluated, it is still possible it is not a C
360 /// "integer constant expression" or constant expression. If not, this struct
361 /// captures information about how and why not.
362 ///
363 /// One bit of information passed *into* the request for constant folding
364 /// indicates whether the subexpression is "evaluated" or not according to C
365 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
366 /// evaluate the expression regardless of what the RHS is, but C only allows
367 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000368 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000369 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000370
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000371 /// EvalStatus - Contains information about the evaluation.
372 Expr::EvalStatus &EvalStatus;
373
374 /// CurrentCall - The top of the constexpr call stack.
375 CallStackFrame *CurrentCall;
376
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000377 /// CallStackDepth - The number of calls in the call stack right now.
378 unsigned CallStackDepth;
379
Richard Smithb228a862012-02-15 02:18:13 +0000380 /// NextCallIndex - The next call index to assign.
381 unsigned NextCallIndex;
382
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000383 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000384 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000385 CallStackFrame BottomFrame;
386
Richard Smithd62306a2011-11-10 06:34:14 +0000387 /// EvaluatingDecl - This is the declaration whose initializer is being
388 /// evaluated, if any.
389 const VarDecl *EvaluatingDecl;
390
391 /// EvaluatingDeclValue - This is the value being constructed for the
392 /// declaration whose initializer is being evaluated, if any.
393 APValue *EvaluatingDeclValue;
394
Richard Smith357362d2011-12-13 06:39:58 +0000395 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
396 /// notes attached to it will also be stored, otherwise they will not be.
397 bool HasActiveDiagnostic;
398
Richard Smith253c2a32012-01-27 01:14:48 +0000399 /// CheckingPotentialConstantExpression - Are we checking whether the
400 /// expression is a potential constant expression? If so, some diagnostics
401 /// are suppressed.
402 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000403
404 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000405
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000406 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
407 bool OverflowCheckMode=false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000408 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000409 CallStackDepth(0), NextCallIndex(1),
410 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith253c2a32012-01-27 01:14:48 +0000411 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000412 CheckingPotentialConstantExpression(false),
413 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000414
Richard Smithd62306a2011-11-10 06:34:14 +0000415 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
416 EvaluatingDecl = VD;
417 EvaluatingDeclValue = &Value;
418 }
419
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000421
Richard Smith357362d2011-12-13 06:39:58 +0000422 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000423 // Don't perform any constexpr calls (other than the call we're checking)
424 // when checking a potential constant expression.
425 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
426 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000427 if (NextCallIndex == 0) {
428 // NextCallIndex has wrapped around.
429 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
430 return false;
431 }
Richard Smith357362d2011-12-13 06:39:58 +0000432 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
433 return true;
434 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
435 << getLangOpts().ConstexprCallDepth;
436 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000437 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000438
Richard Smithb228a862012-02-15 02:18:13 +0000439 CallStackFrame *getCallFrame(unsigned CallIndex) {
440 assert(CallIndex && "no call index in getCallFrame");
441 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
442 // be null in this loop.
443 CallStackFrame *Frame = CurrentCall;
444 while (Frame->Index > CallIndex)
445 Frame = Frame->Caller;
446 return (Frame->Index == CallIndex) ? Frame : 0;
447 }
448
Richard Smith357362d2011-12-13 06:39:58 +0000449 private:
450 /// Add a diagnostic to the diagnostics list.
451 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
452 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
453 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
454 return EvalStatus.Diag->back().second;
455 }
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 /// Add notes containing a call stack to the current point of evaluation.
458 void addCallStack(unsigned Limit);
459
Richard Smith357362d2011-12-13 06:39:58 +0000460 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000461 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000462 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
463 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000464 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000465 // If we have a prior diagnostic, it will be noting that the expression
466 // isn't a constant expression. This diagnostic is more important.
467 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000468 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000469 unsigned CallStackNotes = CallStackDepth - 1;
470 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
471 if (Limit)
472 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000473 if (CheckingPotentialConstantExpression)
474 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000475
Richard Smith357362d2011-12-13 06:39:58 +0000476 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000477 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000478 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
479 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000480 if (!CheckingPotentialConstantExpression)
481 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000482 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 }
Richard Smith357362d2011-12-13 06:39:58 +0000484 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
486 }
487
Richard Smithce1ec5e2012-03-15 04:53:45 +0000488 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
489 = diag::note_invalid_subexpr_in_const_expr,
490 unsigned ExtraNotes = 0) {
491 if (EvalStatus.Diag)
492 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
493 HasActiveDiagnostic = false;
494 return OptionalDiagnostic();
495 }
496
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000497 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
498
Richard Smith92b1ce02011-12-12 09:28:41 +0000499 /// Diagnose that the evaluation does not produce a C++11 core constant
500 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000501 template<typename LocArg>
502 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000503 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000504 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000505 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000506 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
507 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000508 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000509 }
Richard Smith357362d2011-12-13 06:39:58 +0000510 return Diag(Loc, DiagId, ExtraNotes);
511 }
512
513 /// Add a note to a prior diagnostic.
514 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
515 if (!HasActiveDiagnostic)
516 return OptionalDiagnostic();
517 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000518 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000519
520 /// Add a stack of notes to a prior diagnostic.
521 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
522 if (HasActiveDiagnostic) {
523 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
524 Diags.begin(), Diags.end());
525 }
526 }
Richard Smith253c2a32012-01-27 01:14:48 +0000527
528 /// Should we continue evaluation as much as possible after encountering a
529 /// construct which can't be folded?
530 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000531 // Should return true in IntOverflowCheckMode, so that we check for
532 // overflow even if some subexpressions can't be evaluated as constants.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000533 return IntOverflowCheckMode ||
534 (CheckingPotentialConstantExpression &&
535 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith253c2a32012-01-27 01:14:48 +0000536 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000538
539 /// Object used to treat all foldable expressions as constant expressions.
540 struct FoldConstant {
541 bool Enabled;
542
543 explicit FoldConstant(EvalInfo &Info)
544 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
545 !Info.EvalStatus.HasSideEffects) {
546 }
547 // Treat the value we've computed since this object was created as constant.
548 void Fold(EvalInfo &Info) {
549 if (Enabled && !Info.EvalStatus.Diag->empty() &&
550 !Info.EvalStatus.HasSideEffects)
551 Info.EvalStatus.Diag->clear();
552 }
553 };
Richard Smith17100ba2012-02-16 02:46:34 +0000554
555 /// RAII object used to suppress diagnostics and side-effects from a
556 /// speculative evaluation.
557 class SpeculativeEvaluationRAII {
558 EvalInfo &Info;
559 Expr::EvalStatus Old;
560
561 public:
562 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000563 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000564 : Info(Info), Old(Info.EvalStatus) {
565 Info.EvalStatus.Diag = NewDiag;
566 }
567 ~SpeculativeEvaluationRAII() {
568 Info.EvalStatus = Old;
569 }
570 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000571}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572
Richard Smitha8105bc2012-01-06 16:39:00 +0000573bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
574 CheckSubobjectKind CSK) {
575 if (Invalid)
576 return false;
577 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000578 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000579 << CSK;
580 setInvalid();
581 return false;
582 }
583 return true;
584}
585
586void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
587 const Expr *E, uint64_t N) {
588 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000589 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000590 << static_cast<int>(N) << /*array*/ 0
591 << static_cast<unsigned>(MostDerivedArraySize);
592 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << static_cast<int>(N) << /*non-array*/ 1;
595 setInvalid();
596}
597
Richard Smithf6f003a2011-12-16 19:06:07 +0000598CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
599 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000600 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000601 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000602 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 Info.CurrentCall = this;
604 ++Info.CallStackDepth;
605}
606
607CallStackFrame::~CallStackFrame() {
608 assert(Info.CurrentCall == this && "calls retired out of order");
609 --Info.CallStackDepth;
610 Info.CurrentCall = Caller;
611}
612
613/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000614static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000615 unsigned ArgIndex = 0;
616 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000617 !isa<CXXConstructorDecl>(Frame->Callee) &&
618 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000619
620 if (!IsMemberCall)
621 Out << *Frame->Callee << '(';
622
623 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
624 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000625 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000626 Out << ", ";
627
628 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000629 const APValue &Arg = Frame->Arguments[ArgIndex];
630 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000631
632 if (ArgIndex == 0 && IsMemberCall)
633 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000634 }
635
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 Out << ')';
637}
638
639void EvalInfo::addCallStack(unsigned Limit) {
640 // Determine which calls to skip, if any.
641 unsigned ActiveCalls = CallStackDepth - 1;
642 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
643 if (Limit && Limit < ActiveCalls) {
644 SkipStart = Limit / 2 + Limit % 2;
645 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000646 }
647
Richard Smithf6f003a2011-12-16 19:06:07 +0000648 // Walk the call stack and add the diagnostics.
649 unsigned CallIdx = 0;
650 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
651 Frame = Frame->Caller, ++CallIdx) {
652 // Skip this call?
653 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
654 if (CallIdx == SkipStart) {
655 // Note that we're skipping calls.
656 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
657 << unsigned(ActiveCalls - Limit);
658 }
659 continue;
660 }
661
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000662 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 llvm::raw_svector_ostream Out(Buffer);
664 describeCall(Frame, Out);
665 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
666 }
667}
668
669namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000670 struct ComplexValue {
671 private:
672 bool IsInt;
673
674 public:
675 APSInt IntReal, IntImag;
676 APFloat FloatReal, FloatImag;
677
678 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
679
680 void makeComplexFloat() { IsInt = false; }
681 bool isComplexFloat() const { return !IsInt; }
682 APFloat &getComplexFloatReal() { return FloatReal; }
683 APFloat &getComplexFloatImag() { return FloatImag; }
684
685 void makeComplexInt() { IsInt = true; }
686 bool isComplexInt() const { return IsInt; }
687 APSInt &getComplexIntReal() { return IntReal; }
688 APSInt &getComplexIntImag() { return IntImag; }
689
Richard Smith2e312c82012-03-03 22:46:17 +0000690 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000691 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000692 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000693 else
Richard Smith2e312c82012-03-03 22:46:17 +0000694 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000695 }
Richard Smith2e312c82012-03-03 22:46:17 +0000696 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000697 assert(v.isComplexFloat() || v.isComplexInt());
698 if (v.isComplexFloat()) {
699 makeComplexFloat();
700 FloatReal = v.getComplexFloatReal();
701 FloatImag = v.getComplexFloatImag();
702 } else {
703 makeComplexInt();
704 IntReal = v.getComplexIntReal();
705 IntImag = v.getComplexIntImag();
706 }
707 }
John McCall93d91dc2010-05-07 17:22:02 +0000708 };
John McCall45d55e42010-05-07 21:00:08 +0000709
710 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000711 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000712 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000713 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000714 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000715
Richard Smithce40ad62011-11-12 22:28:03 +0000716 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000717 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000718 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000719 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000720 SubobjectDesignator &getLValueDesignator() { return Designator; }
721 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000722
Richard Smith2e312c82012-03-03 22:46:17 +0000723 void moveInto(APValue &V) const {
724 if (Designator.Invalid)
725 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
726 else
727 V = APValue(Base, Offset, Designator.Entries,
728 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000729 }
Richard Smith2e312c82012-03-03 22:46:17 +0000730 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000731 assert(V.isLValue());
732 Base = V.getLValueBase();
733 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000734 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000735 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000736 }
737
Richard Smithb228a862012-02-15 02:18:13 +0000738 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000739 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000740 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000741 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000742 Designator = SubobjectDesignator(getType(B));
743 }
744
745 // Check that this LValue is not based on a null pointer. If it is, produce
746 // a diagnostic and mark the designator as invalid.
747 bool checkNullPointer(EvalInfo &Info, const Expr *E,
748 CheckSubobjectKind CSK) {
749 if (Designator.Invalid)
750 return false;
751 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000752 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000753 << CSK;
754 Designator.setInvalid();
755 return false;
756 }
757 return true;
758 }
759
760 // Check this LValue refers to an object. If not, set the designator to be
761 // invalid and emit a diagnostic.
762 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000763 // Outside C++11, do not build a designator referring to a subobject of
764 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000765 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000767 return checkNullPointer(Info, E, CSK) &&
768 Designator.checkSubobject(Info, E, CSK);
769 }
770
771 void addDecl(EvalInfo &Info, const Expr *E,
772 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000773 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
774 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000775 }
776 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000777 if (checkSubobject(Info, E, CSK_ArrayToPointer))
778 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000779 }
Richard Smith66c96992012-02-18 22:04:06 +0000780 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
782 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000783 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000784 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000785 if (checkNullPointer(Info, E, CSK_ArrayIndex))
786 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000787 }
John McCall45d55e42010-05-07 21:00:08 +0000788 };
Richard Smith027bf112011-11-17 22:56:20 +0000789
790 struct MemberPtr {
791 MemberPtr() {}
792 explicit MemberPtr(const ValueDecl *Decl) :
793 DeclAndIsDerivedMember(Decl, false), Path() {}
794
795 /// The member or (direct or indirect) field referred to by this member
796 /// pointer, or 0 if this is a null member pointer.
797 const ValueDecl *getDecl() const {
798 return DeclAndIsDerivedMember.getPointer();
799 }
800 /// Is this actually a member of some type derived from the relevant class?
801 bool isDerivedMember() const {
802 return DeclAndIsDerivedMember.getInt();
803 }
804 /// Get the class which the declaration actually lives in.
805 const CXXRecordDecl *getContainingRecord() const {
806 return cast<CXXRecordDecl>(
807 DeclAndIsDerivedMember.getPointer()->getDeclContext());
808 }
809
Richard Smith2e312c82012-03-03 22:46:17 +0000810 void moveInto(APValue &V) const {
811 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000812 }
Richard Smith2e312c82012-03-03 22:46:17 +0000813 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000814 assert(V.isMemberPointer());
815 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
816 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
817 Path.clear();
818 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
819 Path.insert(Path.end(), P.begin(), P.end());
820 }
821
822 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
823 /// whether the member is a member of some class derived from the class type
824 /// of the member pointer.
825 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
826 /// Path - The path of base/derived classes from the member declaration's
827 /// class (exclusive) to the class type of the member pointer (inclusive).
828 SmallVector<const CXXRecordDecl*, 4> Path;
829
830 /// Perform a cast towards the class of the Decl (either up or down the
831 /// hierarchy).
832 bool castBack(const CXXRecordDecl *Class) {
833 assert(!Path.empty());
834 const CXXRecordDecl *Expected;
835 if (Path.size() >= 2)
836 Expected = Path[Path.size() - 2];
837 else
838 Expected = getContainingRecord();
839 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
840 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
841 // if B does not contain the original member and is not a base or
842 // derived class of the class containing the original member, the result
843 // of the cast is undefined.
844 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
845 // (D::*). We consider that to be a language defect.
846 return false;
847 }
848 Path.pop_back();
849 return true;
850 }
851 /// Perform a base-to-derived member pointer cast.
852 bool castToDerived(const CXXRecordDecl *Derived) {
853 if (!getDecl())
854 return true;
855 if (!isDerivedMember()) {
856 Path.push_back(Derived);
857 return true;
858 }
859 if (!castBack(Derived))
860 return false;
861 if (Path.empty())
862 DeclAndIsDerivedMember.setInt(false);
863 return true;
864 }
865 /// Perform a derived-to-base member pointer cast.
866 bool castToBase(const CXXRecordDecl *Base) {
867 if (!getDecl())
868 return true;
869 if (Path.empty())
870 DeclAndIsDerivedMember.setInt(true);
871 if (isDerivedMember()) {
872 Path.push_back(Base);
873 return true;
874 }
875 return castBack(Base);
876 }
877 };
Richard Smith357362d2011-12-13 06:39:58 +0000878
Richard Smith7bb00672012-02-01 01:42:44 +0000879 /// Compare two member pointers, which are assumed to be of the same type.
880 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
881 if (!LHS.getDecl() || !RHS.getDecl())
882 return !LHS.getDecl() && !RHS.getDecl();
883 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
884 return false;
885 return LHS.Path == RHS.Path;
886 }
887
Richard Smith357362d2011-12-13 06:39:58 +0000888 /// Kinds of constant expression checking, for diagnostics.
889 enum CheckConstantExpressionKind {
890 CCEK_Constant, ///< A normal constant.
891 CCEK_ReturnValue, ///< A constexpr function return value.
892 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
893 };
John McCall93d91dc2010-05-07 17:22:02 +0000894}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000895
Richard Smith2e312c82012-03-03 22:46:17 +0000896static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000897static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
898 const LValue &This, const Expr *E,
899 CheckConstantExpressionKind CCEK = CCEK_Constant,
900 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000901static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
902static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000903static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
904 EvalInfo &Info);
905static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000906static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000907static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000908 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000909static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000910static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000911
912//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000913// Misc utilities
914//===----------------------------------------------------------------------===//
915
Richard Smithd9f663b2013-04-22 15:31:51 +0000916/// Evaluate an expression to see if it had side-effects, and discard its
917/// result.
918static void EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
919 APValue Scratch;
920 if (!Evaluate(Scratch, Info, E))
921 Info.EvalStatus.HasSideEffects = true;
922}
923
Richard Smithd62306a2011-11-10 06:34:14 +0000924/// Should this call expression be treated as a string literal?
925static bool IsStringLiteralCall(const CallExpr *E) {
926 unsigned Builtin = E->isBuiltinCall();
927 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
928 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
929}
930
Richard Smithce40ad62011-11-12 22:28:03 +0000931static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000932 // C++11 [expr.const]p3 An address constant expression is a prvalue core
933 // constant expression of pointer type that evaluates to...
934
935 // ... a null pointer value, or a prvalue core constant expression of type
936 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000937 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000938
Richard Smithce40ad62011-11-12 22:28:03 +0000939 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
940 // ... the address of an object with static storage duration,
941 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
942 return VD->hasGlobalStorage();
943 // ... the address of a function,
944 return isa<FunctionDecl>(D);
945 }
946
947 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000948 switch (E->getStmtClass()) {
949 default:
950 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000951 case Expr::CompoundLiteralExprClass: {
952 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
953 return CLE->isFileScope() && CLE->isLValue();
954 }
Richard Smithd62306a2011-11-10 06:34:14 +0000955 // A string literal has static storage duration.
956 case Expr::StringLiteralClass:
957 case Expr::PredefinedExprClass:
958 case Expr::ObjCStringLiteralClass:
959 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000960 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000961 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000962 return true;
963 case Expr::CallExprClass:
964 return IsStringLiteralCall(cast<CallExpr>(E));
965 // For GCC compatibility, &&label has static storage duration.
966 case Expr::AddrLabelExprClass:
967 return true;
968 // A Block literal expression may be used as the initialization value for
969 // Block variables at global or local static scope.
970 case Expr::BlockExprClass:
971 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000972 case Expr::ImplicitValueInitExprClass:
973 // FIXME:
974 // We can never form an lvalue with an implicit value initialization as its
975 // base through expression evaluation, so these only appear in one case: the
976 // implicit variable declaration we invent when checking whether a constexpr
977 // constructor can produce a constant expression. We must assume that such
978 // an expression might be a global lvalue.
979 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000980 }
John McCall95007602010-05-10 23:27:23 +0000981}
982
Richard Smithb228a862012-02-15 02:18:13 +0000983static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
984 assert(Base && "no location for a null lvalue");
985 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
986 if (VD)
987 Info.Note(VD->getLocation(), diag::note_declared_at);
988 else
Ted Kremenek28831752012-08-23 20:46:57 +0000989 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000990 diag::note_constexpr_temporary_here);
991}
992
Richard Smith80815602011-11-07 05:07:52 +0000993/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000994/// value for an address or reference constant expression. Return true if we
995/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +0000996static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
997 QualType Type, const LValue &LVal) {
998 bool IsReferenceType = Type->isReferenceType();
999
Richard Smith357362d2011-12-13 06:39:58 +00001000 APValue::LValueBase Base = LVal.getLValueBase();
1001 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1002
Richard Smith0dea49e2012-02-18 04:58:18 +00001003 // Check that the object is a global. Note that the fake 'this' object we
1004 // manufacture when checking potential constant expressions is conservatively
1005 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001006 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001007 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001008 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001009 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1010 << IsReferenceType << !Designator.Entries.empty()
1011 << !!VD << VD;
1012 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001013 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001014 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001015 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001016 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001017 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001018 }
Richard Smithb228a862012-02-15 02:18:13 +00001019 assert((Info.CheckingPotentialConstantExpression ||
1020 LVal.getLValueCallIndex() == 0) &&
1021 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001022
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001023 // Check if this is a thread-local variable.
1024 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1025 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001026 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001027 return false;
1028 }
1029 }
1030
Richard Smitha8105bc2012-01-06 16:39:00 +00001031 // Allow address constant expressions to be past-the-end pointers. This is
1032 // an extension: the standard requires them to point to an object.
1033 if (!IsReferenceType)
1034 return true;
1035
1036 // A reference constant expression must refer to an object.
1037 if (!Base) {
1038 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001039 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001040 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001041 }
1042
Richard Smith357362d2011-12-13 06:39:58 +00001043 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001044 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001045 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001046 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001047 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001048 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001049 }
1050
Richard Smith80815602011-11-07 05:07:52 +00001051 return true;
1052}
1053
Richard Smithfddd3842011-12-30 21:15:51 +00001054/// Check that this core constant expression is of literal type, and if not,
1055/// produce an appropriate diagnostic.
1056static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001057 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001058 return true;
1059
1060 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001061 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001062 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001063 << E->getType();
1064 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001065 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001066 return false;
1067}
1068
Richard Smith0b0a0b62011-10-29 20:57:55 +00001069/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001070/// constant expression. If not, report an appropriate diagnostic. Does not
1071/// check that the expression is of literal type.
1072static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1073 QualType Type, const APValue &Value) {
1074 // Core issue 1454: For a literal constant expression of array or class type,
1075 // each subobject of its value shall have been initialized by a constant
1076 // expression.
1077 if (Value.isArray()) {
1078 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1079 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1080 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1081 Value.getArrayInitializedElt(I)))
1082 return false;
1083 }
1084 if (!Value.hasArrayFiller())
1085 return true;
1086 return CheckConstantExpression(Info, DiagLoc, EltTy,
1087 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001088 }
Richard Smithb228a862012-02-15 02:18:13 +00001089 if (Value.isUnion() && Value.getUnionField()) {
1090 return CheckConstantExpression(Info, DiagLoc,
1091 Value.getUnionField()->getType(),
1092 Value.getUnionValue());
1093 }
1094 if (Value.isStruct()) {
1095 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1096 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1097 unsigned BaseIndex = 0;
1098 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1099 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1100 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1101 Value.getStructBase(BaseIndex)))
1102 return false;
1103 }
1104 }
1105 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1106 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001107 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1108 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001109 return false;
1110 }
1111 }
1112
1113 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001114 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001115 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001116 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1117 }
1118
1119 // Everything else is fine.
1120 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001121}
1122
Richard Smith83c68212011-10-31 05:11:32 +00001123const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001124 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001125}
1126
1127static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001128 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001129}
1130
Richard Smithcecf1842011-11-01 21:06:14 +00001131static bool IsWeakLValue(const LValue &Value) {
1132 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001133 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001134}
1135
Richard Smith2e312c82012-03-03 22:46:17 +00001136static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001137 // A null base expression indicates a null pointer. These are always
1138 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001139 if (!Value.getLValueBase()) {
1140 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001141 return true;
1142 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001143
Richard Smith027bf112011-11-17 22:56:20 +00001144 // We have a non-null base. These are generally known to be true, but if it's
1145 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001146 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001147 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001148 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001149}
1150
Richard Smith2e312c82012-03-03 22:46:17 +00001151static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001152 switch (Val.getKind()) {
1153 case APValue::Uninitialized:
1154 return false;
1155 case APValue::Int:
1156 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001157 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001158 case APValue::Float:
1159 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001160 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001161 case APValue::ComplexInt:
1162 Result = Val.getComplexIntReal().getBoolValue() ||
1163 Val.getComplexIntImag().getBoolValue();
1164 return true;
1165 case APValue::ComplexFloat:
1166 Result = !Val.getComplexFloatReal().isZero() ||
1167 !Val.getComplexFloatImag().isZero();
1168 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001169 case APValue::LValue:
1170 return EvalPointerValueAsBool(Val, Result);
1171 case APValue::MemberPointer:
1172 Result = Val.getMemberPointerDecl();
1173 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001174 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001175 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001176 case APValue::Struct:
1177 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001178 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001179 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001180 }
1181
Richard Smith11562c52011-10-28 17:51:58 +00001182 llvm_unreachable("unknown APValue kind");
1183}
1184
1185static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1186 EvalInfo &Info) {
1187 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001188 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001189 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001190 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001191 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001192}
1193
Richard Smith357362d2011-12-13 06:39:58 +00001194template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001195static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001196 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001197 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001198 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001199}
1200
1201static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1202 QualType SrcType, const APFloat &Value,
1203 QualType DestType, APSInt &Result) {
1204 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001205 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001206 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001207
Richard Smith357362d2011-12-13 06:39:58 +00001208 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001209 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001210 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1211 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001212 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001213 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001214}
1215
Richard Smith357362d2011-12-13 06:39:58 +00001216static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1217 QualType SrcType, QualType DestType,
1218 APFloat &Result) {
1219 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001220 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001221 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1222 APFloat::rmNearestTiesToEven, &ignored)
1223 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001224 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001225 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001226}
1227
Richard Smith911e1422012-01-30 22:27:01 +00001228static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1229 QualType DestType, QualType SrcType,
1230 APSInt &Value) {
1231 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001232 APSInt Result = Value;
1233 // Figure out if this is a truncate, extend or noop cast.
1234 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001235 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001236 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001237 return Result;
1238}
1239
Richard Smith357362d2011-12-13 06:39:58 +00001240static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1241 QualType SrcType, const APSInt &Value,
1242 QualType DestType, APFloat &Result) {
1243 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1244 if (Result.convertFromAPInt(Value, Value.isSigned(),
1245 APFloat::rmNearestTiesToEven)
1246 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001247 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001248 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001249}
1250
Eli Friedman803acb32011-12-22 03:51:45 +00001251static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1252 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001253 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001254 if (!Evaluate(SVal, Info, E))
1255 return false;
1256 if (SVal.isInt()) {
1257 Res = SVal.getInt();
1258 return true;
1259 }
1260 if (SVal.isFloat()) {
1261 Res = SVal.getFloat().bitcastToAPInt();
1262 return true;
1263 }
1264 if (SVal.isVector()) {
1265 QualType VecTy = E->getType();
1266 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1267 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1268 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1269 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1270 Res = llvm::APInt::getNullValue(VecSize);
1271 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1272 APValue &Elt = SVal.getVectorElt(i);
1273 llvm::APInt EltAsInt;
1274 if (Elt.isInt()) {
1275 EltAsInt = Elt.getInt();
1276 } else if (Elt.isFloat()) {
1277 EltAsInt = Elt.getFloat().bitcastToAPInt();
1278 } else {
1279 // Don't try to handle vectors of anything other than int or float
1280 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001281 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001282 return false;
1283 }
1284 unsigned BaseEltSize = EltAsInt.getBitWidth();
1285 if (BigEndian)
1286 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1287 else
1288 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1289 }
1290 return true;
1291 }
1292 // Give up if the input isn't an int, float, or vector. For example, we
1293 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001294 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001295 return false;
1296}
1297
Richard Smitha8105bc2012-01-06 16:39:00 +00001298/// Cast an lvalue referring to a base subobject to a derived class, by
1299/// truncating the lvalue's path to the given length.
1300static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1301 const RecordDecl *TruncatedType,
1302 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001303 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001304
1305 // Check we actually point to a derived class object.
1306 if (TruncatedElements == D.Entries.size())
1307 return true;
1308 assert(TruncatedElements >= D.MostDerivedPathLength &&
1309 "not casting to a derived class");
1310 if (!Result.checkSubobject(Info, E, CSK_Derived))
1311 return false;
1312
1313 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001314 const RecordDecl *RD = TruncatedType;
1315 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001316 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001317 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1318 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001319 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001320 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001321 else
Richard Smithd62306a2011-11-10 06:34:14 +00001322 Result.Offset -= Layout.getBaseClassOffset(Base);
1323 RD = Base;
1324 }
Richard Smith027bf112011-11-17 22:56:20 +00001325 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001326 return true;
1327}
1328
John McCalld7bca762012-05-01 00:38:49 +00001329static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001330 const CXXRecordDecl *Derived,
1331 const CXXRecordDecl *Base,
1332 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001333 if (!RL) {
1334 if (Derived->isInvalidDecl()) return false;
1335 RL = &Info.Ctx.getASTRecordLayout(Derived);
1336 }
1337
Richard Smithd62306a2011-11-10 06:34:14 +00001338 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001339 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001340 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001341}
1342
Richard Smitha8105bc2012-01-06 16:39:00 +00001343static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001344 const CXXRecordDecl *DerivedDecl,
1345 const CXXBaseSpecifier *Base) {
1346 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1347
John McCalld7bca762012-05-01 00:38:49 +00001348 if (!Base->isVirtual())
1349 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001350
Richard Smitha8105bc2012-01-06 16:39:00 +00001351 SubobjectDesignator &D = Obj.Designator;
1352 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001353 return false;
1354
Richard Smitha8105bc2012-01-06 16:39:00 +00001355 // Extract most-derived object and corresponding type.
1356 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1357 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1358 return false;
1359
1360 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001361 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001362 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1363 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001364 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001365 return true;
1366}
1367
1368/// Update LVal to refer to the given field, which must be a member of the type
1369/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001370static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001371 const FieldDecl *FD,
1372 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001373 if (!RL) {
1374 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001375 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001376 }
Richard Smithd62306a2011-11-10 06:34:14 +00001377
1378 unsigned I = FD->getFieldIndex();
1379 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001380 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001381 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001382}
1383
Richard Smith1b78b3d2012-01-25 22:15:11 +00001384/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001385static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001386 LValue &LVal,
1387 const IndirectFieldDecl *IFD) {
1388 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1389 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001390 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1391 return false;
1392 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001393}
1394
Richard Smithd62306a2011-11-10 06:34:14 +00001395/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001396static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1397 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001398 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1399 // extension.
1400 if (Type->isVoidType() || Type->isFunctionType()) {
1401 Size = CharUnits::One();
1402 return true;
1403 }
1404
1405 if (!Type->isConstantSizeType()) {
1406 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001407 // FIXME: Better diagnostic.
1408 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001409 return false;
1410 }
1411
1412 Size = Info.Ctx.getTypeSizeInChars(Type);
1413 return true;
1414}
1415
1416/// Update a pointer value to model pointer arithmetic.
1417/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001418/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001419/// \param LVal - The pointer value to be updated.
1420/// \param EltTy - The pointee type represented by LVal.
1421/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001422static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1423 LValue &LVal, QualType EltTy,
1424 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001425 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001426 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001427 return false;
1428
1429 // Compute the new offset in the appropriate width.
1430 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001431 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001432 return true;
1433}
1434
Richard Smith66c96992012-02-18 22:04:06 +00001435/// Update an lvalue to refer to a component of a complex number.
1436/// \param Info - Information about the ongoing evaluation.
1437/// \param LVal - The lvalue to be updated.
1438/// \param EltTy - The complex number's component type.
1439/// \param Imag - False for the real component, true for the imaginary.
1440static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1441 LValue &LVal, QualType EltTy,
1442 bool Imag) {
1443 if (Imag) {
1444 CharUnits SizeOfComponent;
1445 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1446 return false;
1447 LVal.Offset += SizeOfComponent;
1448 }
1449 LVal.addComplex(Info, E, EltTy, Imag);
1450 return true;
1451}
1452
Richard Smith27908702011-10-24 17:54:18 +00001453/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001454///
1455/// \param Info Information about the ongoing evaluation.
1456/// \param E An expression to be used when printing diagnostics.
1457/// \param VD The variable whose initializer should be obtained.
1458/// \param Frame The frame in which the variable was created. Must be null
1459/// if this variable is not local to the evaluation.
1460/// \param Result Filled in with a pointer to the value of the variable.
1461static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1462 const VarDecl *VD, CallStackFrame *Frame,
1463 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001464 // If this is a parameter to an active constexpr function call, perform
1465 // argument substitution.
1466 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001467 // Assume arguments of a potential constant expression are unknown
1468 // constant expressions.
1469 if (Info.CheckingPotentialConstantExpression)
1470 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001471 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001472 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001473 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001474 }
Richard Smith3229b742013-05-05 21:17:10 +00001475 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001476 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001477 }
Richard Smith27908702011-10-24 17:54:18 +00001478
Richard Smithd9f663b2013-04-22 15:31:51 +00001479 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001480 if (Frame) {
1481 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001482 // If we've carried on past an unevaluatable local variable initializer,
1483 // we can't go any further. This can happen during potential constant
1484 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001485 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001486 }
1487
Richard Smithd0b4dd62011-12-19 06:19:21 +00001488 // Dig out the initializer, and use the declaration which it's attached to.
1489 const Expr *Init = VD->getAnyInitializer(VD);
1490 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001491 // If we're checking a potential constant expression, the variable could be
1492 // initialized later.
1493 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001494 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001495 return false;
1496 }
1497
Richard Smithd62306a2011-11-10 06:34:14 +00001498 // If we're currently evaluating the initializer of this declaration, use that
1499 // in-flight value.
1500 if (Info.EvaluatingDecl == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001501 Result = Info.EvaluatingDeclValue;
1502 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001503 }
1504
Richard Smithcecf1842011-11-01 21:06:14 +00001505 // Never evaluate the initializer of a weak variable. We can't be sure that
1506 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001507 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001508 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001509 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001510 }
Richard Smithcecf1842011-11-01 21:06:14 +00001511
Richard Smithd0b4dd62011-12-19 06:19:21 +00001512 // Check that we can fold the initializer. In C++, we will have already done
1513 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001514 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001515 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001516 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001517 Notes.size() + 1) << VD;
1518 Info.Note(VD->getLocation(), diag::note_declared_at);
1519 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001520 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001521 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001522 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001523 Notes.size() + 1) << VD;
1524 Info.Note(VD->getLocation(), diag::note_declared_at);
1525 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001526 }
Richard Smith27908702011-10-24 17:54:18 +00001527
Richard Smith3229b742013-05-05 21:17:10 +00001528 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001529 return true;
Richard Smith27908702011-10-24 17:54:18 +00001530}
1531
Richard Smith11562c52011-10-28 17:51:58 +00001532static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001533 Qualifiers Quals = T.getQualifiers();
1534 return Quals.hasConst() && !Quals.hasVolatile();
1535}
1536
Richard Smithe97cbd72011-11-11 04:05:33 +00001537/// Get the base index of the given base class within an APValue representing
1538/// the given derived class.
1539static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1540 const CXXRecordDecl *Base) {
1541 Base = Base->getCanonicalDecl();
1542 unsigned Index = 0;
1543 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1544 E = Derived->bases_end(); I != E; ++I, ++Index) {
1545 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1546 return Index;
1547 }
1548
1549 llvm_unreachable("base class missing from derived class's bases list");
1550}
1551
Richard Smith3da88fa2013-04-26 14:36:30 +00001552/// Extract the value of a character from a string literal.
1553static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1554 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001555 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001556 const StringLiteral *S = cast<StringLiteral>(Lit);
1557 const ConstantArrayType *CAT =
1558 Info.Ctx.getAsConstantArrayType(S->getType());
1559 assert(CAT && "string literal isn't an array");
1560 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001561 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001562
1563 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001564 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001565 if (Index < S->getLength())
1566 Value = S->getCodeUnit(Index);
1567 return Value;
1568}
1569
Richard Smith3da88fa2013-04-26 14:36:30 +00001570// Expand a string literal into an array of characters.
1571static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1572 APValue &Result) {
1573 const StringLiteral *S = cast<StringLiteral>(Lit);
1574 const ConstantArrayType *CAT =
1575 Info.Ctx.getAsConstantArrayType(S->getType());
1576 assert(CAT && "string literal isn't an array");
1577 QualType CharType = CAT->getElementType();
1578 assert(CharType->isIntegerType() && "unexpected character type");
1579
1580 unsigned Elts = CAT->getSize().getZExtValue();
1581 Result = APValue(APValue::UninitArray(),
1582 std::min(S->getLength(), Elts), Elts);
1583 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1584 CharType->isUnsignedIntegerType());
1585 if (Result.hasArrayFiller())
1586 Result.getArrayFiller() = APValue(Value);
1587 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1588 Value = S->getCodeUnit(I);
1589 Result.getArrayInitializedElt(I) = APValue(Value);
1590 }
1591}
1592
1593// Expand an array so that it has more than Index filled elements.
1594static void expandArray(APValue &Array, unsigned Index) {
1595 unsigned Size = Array.getArraySize();
1596 assert(Index < Size);
1597
1598 // Always at least double the number of elements for which we store a value.
1599 unsigned OldElts = Array.getArrayInitializedElts();
1600 unsigned NewElts = std::max(Index+1, OldElts * 2);
1601 NewElts = std::min(Size, std::max(NewElts, 8u));
1602
1603 // Copy the data across.
1604 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1605 for (unsigned I = 0; I != OldElts; ++I)
1606 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1607 for (unsigned I = OldElts; I != NewElts; ++I)
1608 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1609 if (NewValue.hasArrayFiller())
1610 NewValue.getArrayFiller() = Array.getArrayFiller();
1611 Array.swap(NewValue);
1612}
1613
1614/// Kinds of access we can perform on an object.
1615enum AccessKinds {
1616 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001617 AK_Assign,
1618 AK_Increment,
1619 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001620};
1621
Richard Smith3229b742013-05-05 21:17:10 +00001622/// A handle to a complete object (an object that is not a subobject of
1623/// another object).
1624struct CompleteObject {
1625 /// The value of the complete object.
1626 APValue *Value;
1627 /// The type of the complete object.
1628 QualType Type;
1629
1630 CompleteObject() : Value(0) {}
1631 CompleteObject(APValue *Value, QualType Type)
1632 : Value(Value), Type(Type) {
1633 assert(Value && "missing value for complete object");
1634 }
1635
1636 operator bool() const { return Value; }
1637};
1638
Richard Smith3da88fa2013-04-26 14:36:30 +00001639/// Find the designated sub-object of an rvalue.
1640template<typename SubobjectHandler>
1641typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001642findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001643 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001644 if (Sub.Invalid)
1645 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001646 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001647 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001648 if (Info.getLangOpts().CPlusPlus11)
1649 Info.Diag(E, diag::note_constexpr_access_past_end)
1650 << handler.AccessKind;
1651 else
1652 Info.Diag(E);
1653 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001654 }
Richard Smith6804be52011-11-11 08:28:03 +00001655 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001656 return handler.found(*Obj.Value, Obj.Type);
1657 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001658 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001659 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001660
Richard Smith3229b742013-05-05 21:17:10 +00001661 APValue *O = Obj.Value;
1662 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001663 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001664 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001665 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001666 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001667 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001668 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001669 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001670 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001671 // Note, it should not be possible to form a pointer with a valid
1672 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001673 if (Info.getLangOpts().CPlusPlus11)
1674 Info.Diag(E, diag::note_constexpr_access_past_end)
1675 << handler.AccessKind;
1676 else
1677 Info.Diag(E);
1678 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001679 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001680
1681 ObjType = CAT->getElementType();
1682
Richard Smith14a94132012-02-17 03:35:37 +00001683 // An array object is represented as either an Array APValue or as an
1684 // LValue which refers to a string literal.
1685 if (O->isLValue()) {
1686 assert(I == N - 1 && "extracting subobject of character?");
1687 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001688 if (handler.AccessKind != AK_Read)
1689 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1690 *O);
1691 else
1692 return handler.foundString(*O, ObjType, Index);
1693 }
1694
1695 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001696 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001697 else if (handler.AccessKind != AK_Read) {
1698 expandArray(*O, Index);
1699 O = &O->getArrayInitializedElt(Index);
1700 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001701 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001702 } else if (ObjType->isAnyComplexType()) {
1703 // Next subobject is a complex number.
1704 uint64_t Index = Sub.Entries[I].ArrayIndex;
1705 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001706 if (Info.getLangOpts().CPlusPlus11)
1707 Info.Diag(E, diag::note_constexpr_access_past_end)
1708 << handler.AccessKind;
1709 else
1710 Info.Diag(E);
1711 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001712 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001713
1714 bool WasConstQualified = ObjType.isConstQualified();
1715 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1716 if (WasConstQualified)
1717 ObjType.addConst();
1718
Richard Smith66c96992012-02-18 22:04:06 +00001719 assert(I == N - 1 && "extracting subobject of scalar?");
1720 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001721 return handler.found(Index ? O->getComplexIntImag()
1722 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001723 } else {
1724 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001725 return handler.found(Index ? O->getComplexFloatImag()
1726 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001727 }
Richard Smithd62306a2011-11-10 06:34:14 +00001728 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001729 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001730 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001731 << Field;
1732 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001733 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001734 }
1735
Richard Smithd62306a2011-11-10 06:34:14 +00001736 // Next subobject is a class, struct or union field.
1737 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1738 if (RD->isUnion()) {
1739 const FieldDecl *UnionField = O->getUnionField();
1740 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001741 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001742 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1743 << handler.AccessKind << Field << !UnionField << UnionField;
1744 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745 }
Richard Smithd62306a2011-11-10 06:34:14 +00001746 O = &O->getUnionValue();
1747 } else
1748 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001749
1750 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001751 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001752 if (WasConstQualified && !Field->isMutable())
1753 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001754
1755 if (ObjType.isVolatileQualified()) {
1756 if (Info.getLangOpts().CPlusPlus) {
1757 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001758 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1759 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001760 Info.Note(Field->getLocation(), diag::note_declared_at);
1761 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001762 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001763 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001764 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001765 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001766 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001767 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001768 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1769 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1770 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001771
1772 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001773 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001774 if (WasConstQualified)
1775 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001776 }
Richard Smithd62306a2011-11-10 06:34:14 +00001777
Richard Smithf57d8cb2011-12-09 22:58:01 +00001778 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001779 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001780 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1781 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001782 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001783 }
1784
Richard Smith3da88fa2013-04-26 14:36:30 +00001785 return handler.found(*O, ObjType);
1786}
1787
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001788namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001789struct ExtractSubobjectHandler {
1790 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001791 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001792
1793 static const AccessKinds AccessKind = AK_Read;
1794
1795 typedef bool result_type;
1796 bool failed() { return false; }
1797 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001798 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001799 return true;
1800 }
1801 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001802 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001803 return true;
1804 }
1805 bool found(APFloat &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 foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001810 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001811 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1812 return true;
1813 }
1814};
Richard Smith3229b742013-05-05 21:17:10 +00001815} // end anonymous namespace
1816
Richard Smith3da88fa2013-04-26 14:36:30 +00001817const AccessKinds ExtractSubobjectHandler::AccessKind;
1818
1819/// Extract the designated sub-object of an rvalue.
1820static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001821 const CompleteObject &Obj,
1822 const SubobjectDesignator &Sub,
1823 APValue &Result) {
1824 ExtractSubobjectHandler Handler = { Info, Result };
1825 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00001826}
1827
Richard Smith3229b742013-05-05 21:17:10 +00001828namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001829struct ModifySubobjectHandler {
1830 EvalInfo &Info;
1831 APValue &NewVal;
1832 const Expr *E;
1833
1834 typedef bool result_type;
1835 static const AccessKinds AccessKind = AK_Assign;
1836
1837 bool checkConst(QualType QT) {
1838 // Assigning to a const object has undefined behavior.
1839 if (QT.isConstQualified()) {
1840 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
1841 return false;
1842 }
1843 return true;
1844 }
1845
1846 bool failed() { return false; }
1847 bool found(APValue &Subobj, QualType SubobjType) {
1848 if (!checkConst(SubobjType))
1849 return false;
1850 // We've been given ownership of NewVal, so just swap it in.
1851 Subobj.swap(NewVal);
1852 return true;
1853 }
1854 bool found(APSInt &Value, QualType SubobjType) {
1855 if (!checkConst(SubobjType))
1856 return false;
1857 if (!NewVal.isInt()) {
1858 // Maybe trying to write a cast pointer value into a complex?
1859 Info.Diag(E);
1860 return false;
1861 }
1862 Value = NewVal.getInt();
1863 return true;
1864 }
1865 bool found(APFloat &Value, QualType SubobjType) {
1866 if (!checkConst(SubobjType))
1867 return false;
1868 Value = NewVal.getFloat();
1869 return true;
1870 }
1871 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1872 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
1873 }
1874};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001875} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00001876
Richard Smith3229b742013-05-05 21:17:10 +00001877const AccessKinds ModifySubobjectHandler::AccessKind;
1878
Richard Smith3da88fa2013-04-26 14:36:30 +00001879/// Update the designated sub-object of an rvalue to the given value.
1880static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001881 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001882 const SubobjectDesignator &Sub,
1883 APValue &NewVal) {
1884 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00001885 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00001886}
1887
Richard Smith84f6dcf2012-02-02 01:16:57 +00001888/// Find the position where two subobject designators diverge, or equivalently
1889/// the length of the common initial subsequence.
1890static unsigned FindDesignatorMismatch(QualType ObjType,
1891 const SubobjectDesignator &A,
1892 const SubobjectDesignator &B,
1893 bool &WasArrayIndex) {
1894 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1895 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001896 if (!ObjType.isNull() &&
1897 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001898 // Next subobject is an array element.
1899 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1900 WasArrayIndex = true;
1901 return I;
1902 }
Richard Smith66c96992012-02-18 22:04:06 +00001903 if (ObjType->isAnyComplexType())
1904 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1905 else
1906 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001907 } else {
1908 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1909 WasArrayIndex = false;
1910 return I;
1911 }
1912 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1913 // Next subobject is a field.
1914 ObjType = FD->getType();
1915 else
1916 // Next subobject is a base class.
1917 ObjType = QualType();
1918 }
1919 }
1920 WasArrayIndex = false;
1921 return I;
1922}
1923
1924/// Determine whether the given subobject designators refer to elements of the
1925/// same array object.
1926static bool AreElementsOfSameArray(QualType ObjType,
1927 const SubobjectDesignator &A,
1928 const SubobjectDesignator &B) {
1929 if (A.Entries.size() != B.Entries.size())
1930 return false;
1931
1932 bool IsArray = A.MostDerivedArraySize != 0;
1933 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1934 // A is a subobject of the array element.
1935 return false;
1936
1937 // If A (and B) designates an array element, the last entry will be the array
1938 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1939 // of length 1' case, and the entire path must match.
1940 bool WasArrayIndex;
1941 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1942 return CommonLength >= A.Entries.size() - IsArray;
1943}
1944
Richard Smith3229b742013-05-05 21:17:10 +00001945/// Find the complete object to which an LValue refers.
1946CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
1947 const LValue &LVal, QualType LValType) {
1948 if (!LVal.Base) {
1949 Info.Diag(E, diag::note_constexpr_access_null) << AK;
1950 return CompleteObject();
1951 }
1952
1953 CallStackFrame *Frame = 0;
1954 if (LVal.CallIndex) {
1955 Frame = Info.getCallFrame(LVal.CallIndex);
1956 if (!Frame) {
1957 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
1958 << AK << LVal.Base.is<const ValueDecl*>();
1959 NoteLValueLocation(Info, LVal.Base);
1960 return CompleteObject();
1961 }
1962 } else if (AK != AK_Read) {
1963 Info.Diag(E, diag::note_constexpr_modify_global);
1964 return CompleteObject();
1965 }
1966
1967 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1968 // is not a constant expression (even if the object is non-volatile). We also
1969 // apply this rule to C++98, in order to conform to the expected 'volatile'
1970 // semantics.
1971 if (LValType.isVolatileQualified()) {
1972 if (Info.getLangOpts().CPlusPlus)
1973 Info.Diag(E, diag::note_constexpr_access_volatile_type)
1974 << AK << LValType;
1975 else
1976 Info.Diag(E);
1977 return CompleteObject();
1978 }
1979
1980 // Compute value storage location and type of base object.
1981 APValue *BaseVal = 0;
1982 QualType BaseType;
1983
1984 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1985 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1986 // In C++11, constexpr, non-volatile variables initialized with constant
1987 // expressions are constant expressions too. Inside constexpr functions,
1988 // parameters are constant expressions even if they're non-const.
1989 // In C++1y, objects local to a constant expression (those with a Frame) are
1990 // both readable and writable inside constant expressions.
1991 // In C, such things can also be folded, although they are not ICEs.
1992 const VarDecl *VD = dyn_cast<VarDecl>(D);
1993 if (VD) {
1994 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1995 VD = VDef;
1996 }
1997 if (!VD || VD->isInvalidDecl()) {
1998 Info.Diag(E);
1999 return CompleteObject();
2000 }
2001
2002 // Accesses of volatile-qualified objects are not allowed.
2003 BaseType = VD->getType();
2004 if (BaseType.isVolatileQualified()) {
2005 if (Info.getLangOpts().CPlusPlus) {
2006 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2007 << AK << 1 << VD;
2008 Info.Note(VD->getLocation(), diag::note_declared_at);
2009 } else {
2010 Info.Diag(E);
2011 }
2012 return CompleteObject();
2013 }
2014
2015 // Unless we're looking at a local variable or argument in a constexpr call,
2016 // the variable we're reading must be const.
2017 if (!Frame) {
2018 assert(AK == AK_Read && "can't modify non-local");
2019 if (VD->isConstexpr()) {
2020 // OK, we can read this variable.
2021 } else if (BaseType->isIntegralOrEnumerationType()) {
2022 if (!BaseType.isConstQualified()) {
2023 if (Info.getLangOpts().CPlusPlus) {
2024 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2025 Info.Note(VD->getLocation(), diag::note_declared_at);
2026 } else {
2027 Info.Diag(E);
2028 }
2029 return CompleteObject();
2030 }
2031 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2032 // We support folding of const floating-point types, in order to make
2033 // static const data members of such types (supported as an extension)
2034 // more useful.
2035 if (Info.getLangOpts().CPlusPlus11) {
2036 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2037 Info.Note(VD->getLocation(), diag::note_declared_at);
2038 } else {
2039 Info.CCEDiag(E);
2040 }
2041 } else {
2042 // FIXME: Allow folding of values of any literal type in all languages.
2043 if (Info.getLangOpts().CPlusPlus11) {
2044 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2045 Info.Note(VD->getLocation(), diag::note_declared_at);
2046 } else {
2047 Info.Diag(E);
2048 }
2049 return CompleteObject();
2050 }
2051 }
2052
2053 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2054 return CompleteObject();
2055 } else {
2056 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2057
2058 if (!Frame) {
2059 Info.Diag(E);
2060 return CompleteObject();
2061 }
2062
2063 BaseType = Base->getType();
2064 BaseVal = &Frame->Temporaries[Base];
2065
2066 // Volatile temporary objects cannot be accessed in constant expressions.
2067 if (BaseType.isVolatileQualified()) {
2068 if (Info.getLangOpts().CPlusPlus) {
2069 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2070 << AK << 0;
2071 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2072 } else {
2073 Info.Diag(E);
2074 }
2075 return CompleteObject();
2076 }
2077 }
2078
2079 // In C++1y, we can't safely access any mutable state when checking a
2080 // potential constant expression.
2081 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2082 Info.CheckingPotentialConstantExpression)
2083 return CompleteObject();
2084
2085 return CompleteObject(BaseVal, BaseType);
2086}
2087
Richard Smith243ef902013-05-05 23:31:59 +00002088/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2089/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2090/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002091///
2092/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002093/// \param Conv - The expression for which we are performing the conversion.
2094/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002095/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2096/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002097/// \param LVal - The glvalue on which we are attempting to perform this action.
2098/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002099static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002100 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002101 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002102 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002103 return false;
2104
Richard Smith3229b742013-05-05 21:17:10 +00002105 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002106 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002107 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2108 !Type.isVolatileQualified()) {
2109 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2110 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2111 // initializer until now for such expressions. Such an expression can't be
2112 // an ICE in C, so this only matters for fold.
2113 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2114 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002115 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002116 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002117 }
Richard Smith3229b742013-05-05 21:17:10 +00002118 APValue Lit;
2119 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2120 return false;
2121 CompleteObject LitObj(&Lit, Base->getType());
2122 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2123 } else if (isa<StringLiteral>(Base)) {
2124 // We represent a string literal array as an lvalue pointing at the
2125 // corresponding expression, rather than building an array of chars.
2126 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2127 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2128 CompleteObject StrObj(&Str, Base->getType());
2129 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002130 }
Richard Smith11562c52011-10-28 17:51:58 +00002131 }
2132
Richard Smith3229b742013-05-05 21:17:10 +00002133 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2134 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002135}
2136
2137/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002138static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002139 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002140 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002141 return false;
2142
Richard Smith3229b742013-05-05 21:17:10 +00002143 if (!Info.getLangOpts().CPlusPlus1y) {
2144 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002145 return false;
2146 }
2147
Richard Smith3229b742013-05-05 21:17:10 +00002148 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2149 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002150}
2151
Richard Smith243ef902013-05-05 23:31:59 +00002152static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2153 return T->isSignedIntegerType() &&
2154 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2155}
2156
2157namespace {
2158struct IncDecSubobjectHandler {
2159 EvalInfo &Info;
2160 const Expr *E;
2161 AccessKinds AccessKind;
2162 APValue *Old;
2163
2164 typedef bool result_type;
2165
2166 bool checkConst(QualType QT) {
2167 // Assigning to a const object has undefined behavior.
2168 if (QT.isConstQualified()) {
2169 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2170 return false;
2171 }
2172 return true;
2173 }
2174
2175 bool failed() { return false; }
2176 bool found(APValue &Subobj, QualType SubobjType) {
2177 // Stash the old value. Also clear Old, so we don't clobber it later
2178 // if we're post-incrementing a complex.
2179 if (Old) {
2180 *Old = Subobj;
2181 Old = 0;
2182 }
2183
2184 switch (Subobj.getKind()) {
2185 case APValue::Int:
2186 return found(Subobj.getInt(), SubobjType);
2187 case APValue::Float:
2188 return found(Subobj.getFloat(), SubobjType);
2189 case APValue::ComplexInt:
2190 return found(Subobj.getComplexIntReal(),
2191 SubobjType->castAs<ComplexType>()->getElementType()
2192 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2193 case APValue::ComplexFloat:
2194 return found(Subobj.getComplexFloatReal(),
2195 SubobjType->castAs<ComplexType>()->getElementType()
2196 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2197 case APValue::LValue:
2198 return foundPointer(Subobj, SubobjType);
2199 default:
2200 // FIXME: can this happen?
2201 Info.Diag(E);
2202 return false;
2203 }
2204 }
2205 bool found(APSInt &Value, QualType SubobjType) {
2206 if (!checkConst(SubobjType))
2207 return false;
2208
2209 if (!SubobjType->isIntegerType()) {
2210 // We don't support increment / decrement on integer-cast-to-pointer
2211 // values.
2212 Info.Diag(E);
2213 return false;
2214 }
2215
2216 if (Old) *Old = APValue(Value);
2217
2218 // bool arithmetic promotes to int, and the conversion back to bool
2219 // doesn't reduce mod 2^n, so special-case it.
2220 if (SubobjType->isBooleanType()) {
2221 if (AccessKind == AK_Increment)
2222 Value = 1;
2223 else
2224 Value = !Value;
2225 return true;
2226 }
2227
2228 bool WasNegative = Value.isNegative();
2229 if (AccessKind == AK_Increment) {
2230 ++Value;
2231
2232 if (!WasNegative && Value.isNegative() &&
2233 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2234 APSInt ActualValue(Value, /*IsUnsigned*/true);
2235 HandleOverflow(Info, E, ActualValue, SubobjType);
2236 }
2237 } else {
2238 --Value;
2239
2240 if (WasNegative && !Value.isNegative() &&
2241 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2242 unsigned BitWidth = Value.getBitWidth();
2243 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2244 ActualValue.setBit(BitWidth);
2245 HandleOverflow(Info, E, ActualValue, SubobjType);
2246 }
2247 }
2248 return true;
2249 }
2250 bool found(APFloat &Value, QualType SubobjType) {
2251 if (!checkConst(SubobjType))
2252 return false;
2253
2254 if (Old) *Old = APValue(Value);
2255
2256 APFloat One(Value.getSemantics(), 1);
2257 if (AccessKind == AK_Increment)
2258 Value.add(One, APFloat::rmNearestTiesToEven);
2259 else
2260 Value.subtract(One, APFloat::rmNearestTiesToEven);
2261 return true;
2262 }
2263 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2264 if (!checkConst(SubobjType))
2265 return false;
2266
2267 QualType PointeeType;
2268 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2269 PointeeType = PT->getPointeeType();
2270 else {
2271 Info.Diag(E);
2272 return false;
2273 }
2274
2275 LValue LVal;
2276 LVal.setFrom(Info.Ctx, Subobj);
2277 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2278 AccessKind == AK_Increment ? 1 : -1))
2279 return false;
2280 LVal.moveInto(Subobj);
2281 return true;
2282 }
2283 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2284 llvm_unreachable("shouldn't encounter string elements here");
2285 }
2286};
2287} // end anonymous namespace
2288
2289/// Perform an increment or decrement on LVal.
2290static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2291 QualType LValType, bool IsIncrement, APValue *Old) {
2292 if (LVal.Designator.Invalid)
2293 return false;
2294
2295 if (!Info.getLangOpts().CPlusPlus1y) {
2296 Info.Diag(E);
2297 return false;
2298 }
2299
2300 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2301 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2302 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2303 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2304}
2305
Richard Smithe97cbd72011-11-11 04:05:33 +00002306/// Build an lvalue for the object argument of a member function call.
2307static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2308 LValue &This) {
2309 if (Object->getType()->isPointerType())
2310 return EvaluatePointer(Object, This, Info);
2311
2312 if (Object->isGLValue())
2313 return EvaluateLValue(Object, This, Info);
2314
Richard Smithd9f663b2013-04-22 15:31:51 +00002315 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002316 return EvaluateTemporary(Object, This, Info);
2317
2318 return false;
2319}
2320
2321/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2322/// lvalue referring to the result.
2323///
2324/// \param Info - Information about the ongoing evaluation.
2325/// \param BO - The member pointer access operation.
2326/// \param LV - Filled in with a reference to the resulting object.
2327/// \param IncludeMember - Specifies whether the member itself is included in
2328/// the resulting LValue subobject designator. This is not possible when
2329/// creating a bound member function.
2330/// \return The field or method declaration to which the member pointer refers,
2331/// or 0 if evaluation fails.
2332static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2333 const BinaryOperator *BO,
2334 LValue &LV,
2335 bool IncludeMember = true) {
2336 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2337
Richard Smith253c2a32012-01-27 01:14:48 +00002338 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2339 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002340 return 0;
2341
2342 MemberPtr MemPtr;
2343 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2344 return 0;
2345
2346 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2347 // member value, the behavior is undefined.
2348 if (!MemPtr.getDecl())
2349 return 0;
2350
Richard Smith253c2a32012-01-27 01:14:48 +00002351 if (!EvalObjOK)
2352 return 0;
2353
Richard Smith027bf112011-11-17 22:56:20 +00002354 if (MemPtr.isDerivedMember()) {
2355 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002356 // The end of the derived-to-base path for the base object must match the
2357 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002358 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002359 LV.Designator.Entries.size())
2360 return 0;
2361 unsigned PathLengthToMember =
2362 LV.Designator.Entries.size() - MemPtr.Path.size();
2363 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2364 const CXXRecordDecl *LVDecl = getAsBaseClass(
2365 LV.Designator.Entries[PathLengthToMember + I]);
2366 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2367 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2368 return 0;
2369 }
2370
2371 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002372 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2373 PathLengthToMember))
2374 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002375 } else if (!MemPtr.Path.empty()) {
2376 // Extend the LValue path with the member pointer's path.
2377 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2378 MemPtr.Path.size() + IncludeMember);
2379
2380 // Walk down to the appropriate base class.
2381 QualType LVType = BO->getLHS()->getType();
2382 if (const PointerType *PT = LVType->getAs<PointerType>())
2383 LVType = PT->getPointeeType();
2384 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2385 assert(RD && "member pointer access on non-class-type expression");
2386 // The first class in the path is that of the lvalue.
2387 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2388 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002389 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2390 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002391 RD = Base;
2392 }
2393 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002394 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2395 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002396 }
2397
2398 // Add the member. Note that we cannot build bound member functions here.
2399 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002400 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2401 if (!HandleLValueMember(Info, BO, LV, FD))
2402 return 0;
2403 } else if (const IndirectFieldDecl *IFD =
2404 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2405 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2406 return 0;
2407 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002408 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002409 }
Richard Smith027bf112011-11-17 22:56:20 +00002410 }
2411
2412 return MemPtr.getDecl();
2413}
2414
2415/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2416/// the provided lvalue, which currently refers to the base object.
2417static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2418 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002419 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002420 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002421 return false;
2422
Richard Smitha8105bc2012-01-06 16:39:00 +00002423 QualType TargetQT = E->getType();
2424 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2425 TargetQT = PT->getPointeeType();
2426
2427 // Check this cast lands within the final derived-to-base subobject path.
2428 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002429 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002430 << D.MostDerivedType << TargetQT;
2431 return false;
2432 }
2433
Richard Smith027bf112011-11-17 22:56:20 +00002434 // Check the type of the final cast. We don't need to check the path,
2435 // since a cast can only be formed if the path is unique.
2436 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002437 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2438 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002439 if (NewEntriesSize == D.MostDerivedPathLength)
2440 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2441 else
Richard Smith027bf112011-11-17 22:56:20 +00002442 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002443 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002444 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002445 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002446 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002447 }
Richard Smith027bf112011-11-17 22:56:20 +00002448
2449 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002450 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002451}
2452
Mike Stump876387b2009-10-27 22:09:17 +00002453namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002454enum EvalStmtResult {
2455 /// Evaluation failed.
2456 ESR_Failed,
2457 /// Hit a 'return' statement.
2458 ESR_Returned,
2459 /// Evaluation succeeded.
2460 ESR_Succeeded
2461};
2462}
2463
Richard Smithd9f663b2013-04-22 15:31:51 +00002464static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2465 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2466 // We don't need to evaluate the initializer for a static local.
2467 if (!VD->hasLocalStorage())
2468 return true;
2469
2470 LValue Result;
2471 Result.set(VD, Info.CurrentCall->Index);
2472 APValue &Val = Info.CurrentCall->Temporaries[VD];
2473
2474 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2475 // Wipe out any partially-computed value, to allow tracking that this
2476 // evaluation failed.
2477 Val = APValue();
2478 return false;
2479 }
2480 }
2481
2482 return true;
2483}
2484
Richard Smith254a73d2011-10-28 22:34:42 +00002485// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002486static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002487 const Stmt *S) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002488 // FIXME: Mark all temporaries in the current frame as destroyed at
2489 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002490 switch (S->getStmtClass()) {
2491 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002492 if (const Expr *E = dyn_cast<Expr>(S)) {
2493 EvaluateIgnoredValue(Info, E);
2494 // Don't bother evaluating beyond an expression-statement which couldn't
2495 // be evaluated.
2496 if (Info.EvalStatus.HasSideEffects && !Info.keepEvaluatingAfterFailure())
2497 return ESR_Failed;
2498 return ESR_Succeeded;
2499 }
2500
2501 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002502 return ESR_Failed;
2503
2504 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002505 return ESR_Succeeded;
2506
Richard Smithd9f663b2013-04-22 15:31:51 +00002507 case Stmt::DeclStmtClass: {
2508 const DeclStmt *DS = cast<DeclStmt>(S);
2509 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2510 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2511 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2512 return ESR_Failed;
2513 return ESR_Succeeded;
2514 }
2515
Richard Smith357362d2011-12-13 06:39:58 +00002516 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002517 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002518 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002519 return ESR_Failed;
2520 return ESR_Returned;
2521 }
Richard Smith254a73d2011-10-28 22:34:42 +00002522
2523 case Stmt::CompoundStmtClass: {
2524 const CompoundStmt *CS = cast<CompoundStmt>(S);
2525 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2526 BE = CS->body_end(); BI != BE; ++BI) {
2527 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2528 if (ESR != ESR_Succeeded)
2529 return ESR;
2530 }
2531 return ESR_Succeeded;
2532 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002533
2534 case Stmt::IfStmtClass: {
2535 const IfStmt *IS = cast<IfStmt>(S);
2536
2537 // Evaluate the condition, as either a var decl or as an expression.
2538 bool Cond;
2539 if (VarDecl *CondDecl = IS->getConditionVariable()) {
2540 if (!EvaluateDecl(Info, CondDecl))
2541 return ESR_Failed;
2542 if (!HandleConversionToBool(Info.CurrentCall->Temporaries[CondDecl],
2543 Cond))
2544 return ESR_Failed;
2545 } else if (!EvaluateAsBooleanCondition(IS->getCond(), Cond, Info))
2546 return ESR_Failed;
2547
2548 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2549 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2550 if (ESR != ESR_Succeeded)
2551 return ESR;
2552 }
2553 return ESR_Succeeded;
2554 }
Richard Smith254a73d2011-10-28 22:34:42 +00002555 }
2556}
2557
Richard Smithcc36f692011-12-22 02:22:31 +00002558/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2559/// default constructor. If so, we'll fold it whether or not it's marked as
2560/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2561/// so we need special handling.
2562static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002563 const CXXConstructorDecl *CD,
2564 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002565 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2566 return false;
2567
Richard Smith66e05fe2012-01-18 05:21:49 +00002568 // Value-initialization does not call a trivial default constructor, so such a
2569 // call is a core constant expression whether or not the constructor is
2570 // constexpr.
2571 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002572 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002573 // FIXME: If DiagDecl is an implicitly-declared special member function,
2574 // we should be much more explicit about why it's not constexpr.
2575 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2576 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2577 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002578 } else {
2579 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2580 }
2581 }
2582 return true;
2583}
2584
Richard Smith357362d2011-12-13 06:39:58 +00002585/// CheckConstexprFunction - Check that a function can be called in a constant
2586/// expression.
2587static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2588 const FunctionDecl *Declaration,
2589 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002590 // Potential constant expressions can contain calls to declared, but not yet
2591 // defined, constexpr functions.
2592 if (Info.CheckingPotentialConstantExpression && !Definition &&
2593 Declaration->isConstexpr())
2594 return false;
2595
Richard Smith357362d2011-12-13 06:39:58 +00002596 // Can we evaluate this function call?
2597 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2598 return true;
2599
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002600 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002601 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002602 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2603 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002604 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2605 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2606 << DiagDecl;
2607 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2608 } else {
2609 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2610 }
2611 return false;
2612}
2613
Richard Smithd62306a2011-11-10 06:34:14 +00002614namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002615typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002616}
2617
2618/// EvaluateArgs - Evaluate the arguments to a function call.
2619static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2620 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002621 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002622 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002623 I != E; ++I) {
2624 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2625 // If we're checking for a potential constant expression, evaluate all
2626 // initializers even if some of them fail.
2627 if (!Info.keepEvaluatingAfterFailure())
2628 return false;
2629 Success = false;
2630 }
2631 }
2632 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002633}
2634
Richard Smith254a73d2011-10-28 22:34:42 +00002635/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002636static bool HandleFunctionCall(SourceLocation CallLoc,
2637 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002638 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002639 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002640 ArgVector ArgValues(Args.size());
2641 if (!EvaluateArgs(Args, ArgValues, Info))
2642 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002643
Richard Smith253c2a32012-01-27 01:14:48 +00002644 if (!Info.CheckCallLimit(CallLoc))
2645 return false;
2646
2647 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd9f663b2013-04-22 15:31:51 +00002648 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00002649 if (ESR == ESR_Succeeded) {
2650 if (Callee->getResultType()->isVoidType())
2651 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002652 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00002653 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002654 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00002655}
2656
Richard Smithd62306a2011-11-10 06:34:14 +00002657/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002658static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002659 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002660 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002661 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002662 ArgVector ArgValues(Args.size());
2663 if (!EvaluateArgs(Args, ArgValues, Info))
2664 return false;
2665
Richard Smith253c2a32012-01-27 01:14:48 +00002666 if (!Info.CheckCallLimit(CallLoc))
2667 return false;
2668
Richard Smith3607ffe2012-02-13 03:54:03 +00002669 const CXXRecordDecl *RD = Definition->getParent();
2670 if (RD->getNumVBases()) {
2671 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2672 return false;
2673 }
2674
Richard Smith253c2a32012-01-27 01:14:48 +00002675 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002676
2677 // If it's a delegating constructor, just delegate.
2678 if (Definition->isDelegatingConstructor()) {
2679 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00002680 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
2681 return false;
2682 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002683 }
2684
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002685 // For a trivial copy or move constructor, perform an APValue copy. This is
2686 // essential for unions, where the operations performed by the constructor
2687 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002688 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002689 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2690 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002691 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002692 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00002693 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00002694 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002695 }
2696
2697 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002698 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002699 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2700 std::distance(RD->field_begin(), RD->field_end()));
2701
John McCalld7bca762012-05-01 00:38:49 +00002702 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002703 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2704
Richard Smith253c2a32012-01-27 01:14:48 +00002705 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002706 unsigned BasesSeen = 0;
2707#ifndef NDEBUG
2708 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2709#endif
2710 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2711 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002712 LValue Subobject = This;
2713 APValue *Value = &Result;
2714
2715 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002716 if ((*I)->isBaseInitializer()) {
2717 QualType BaseType((*I)->getBaseClass(), 0);
2718#ifndef NDEBUG
2719 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002720 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002721 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2722 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2723 "base class initializers not in expected order");
2724 ++BaseIt;
2725#endif
John McCalld7bca762012-05-01 00:38:49 +00002726 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2727 BaseType->getAsCXXRecordDecl(), &Layout))
2728 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002729 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002730 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002731 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2732 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002733 if (RD->isUnion()) {
2734 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002735 Value = &Result.getUnionValue();
2736 } else {
2737 Value = &Result.getStructField(FD->getFieldIndex());
2738 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002739 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002740 // Walk the indirect field decl's chain to find the object to initialize,
2741 // and make sure we've initialized every step along it.
2742 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2743 CE = IFD->chain_end();
2744 C != CE; ++C) {
2745 FieldDecl *FD = cast<FieldDecl>(*C);
2746 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2747 // Switch the union field if it differs. This happens if we had
2748 // preceding zero-initialization, and we're now initializing a union
2749 // subobject other than the first.
2750 // FIXME: In this case, the values of the other subobjects are
2751 // specified, since zero-initialization sets all padding bits to zero.
2752 if (Value->isUninit() ||
2753 (Value->isUnion() && Value->getUnionField() != FD)) {
2754 if (CD->isUnion())
2755 *Value = APValue(FD);
2756 else
2757 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2758 std::distance(CD->field_begin(), CD->field_end()));
2759 }
John McCalld7bca762012-05-01 00:38:49 +00002760 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2761 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002762 if (CD->isUnion())
2763 Value = &Value->getUnionValue();
2764 else
2765 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002766 }
Richard Smithd62306a2011-11-10 06:34:14 +00002767 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002768 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002769 }
Richard Smith253c2a32012-01-27 01:14:48 +00002770
Richard Smithb228a862012-02-15 02:18:13 +00002771 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2772 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002773 ? CCEK_Constant : CCEK_MemberInit)) {
2774 // If we're checking for a potential constant expression, evaluate all
2775 // initializers even if some of them fail.
2776 if (!Info.keepEvaluatingAfterFailure())
2777 return false;
2778 Success = false;
2779 }
Richard Smithd62306a2011-11-10 06:34:14 +00002780 }
2781
Richard Smithd9f663b2013-04-22 15:31:51 +00002782 return Success &&
2783 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002784}
2785
Eli Friedman9a156e52008-11-12 09:44:48 +00002786//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002787// Generic Evaluation
2788//===----------------------------------------------------------------------===//
2789namespace {
2790
Richard Smithf57d8cb2011-12-09 22:58:01 +00002791// FIXME: RetTy is always bool. Remove it.
2792template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002793class ExprEvaluatorBase
2794 : public ConstStmtVisitor<Derived, RetTy> {
2795private:
Richard Smith2e312c82012-03-03 22:46:17 +00002796 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002797 return static_cast<Derived*>(this)->Success(V, E);
2798 }
Richard Smithfddd3842011-12-30 21:15:51 +00002799 RetTy DerivedZeroInitialization(const Expr *E) {
2800 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002801 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002802
Richard Smith17100ba2012-02-16 02:46:34 +00002803 // Check whether a conditional operator with a non-constant condition is a
2804 // potential constant expression. If neither arm is a potential constant
2805 // expression, then the conditional operator is not either.
2806 template<typename ConditionalOperator>
2807 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2808 assert(Info.CheckingPotentialConstantExpression);
2809
2810 // Speculatively evaluate both arms.
2811 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002812 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002813 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2814
2815 StmtVisitorTy::Visit(E->getFalseExpr());
2816 if (Diag.empty())
2817 return;
2818
2819 Diag.clear();
2820 StmtVisitorTy::Visit(E->getTrueExpr());
2821 if (Diag.empty())
2822 return;
2823 }
2824
2825 Error(E, diag::note_constexpr_conditional_never_const);
2826 }
2827
2828
2829 template<typename ConditionalOperator>
2830 bool HandleConditionalOperator(const ConditionalOperator *E) {
2831 bool BoolResult;
2832 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2833 if (Info.CheckingPotentialConstantExpression)
2834 CheckPotentialConstantConditional(E);
2835 return false;
2836 }
2837
2838 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2839 return StmtVisitorTy::Visit(EvalExpr);
2840 }
2841
Peter Collingbournee9200682011-05-13 03:29:01 +00002842protected:
2843 EvalInfo &Info;
2844 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2845 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2846
Richard Smith92b1ce02011-12-12 09:28:41 +00002847 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002848 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002849 }
2850
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002851 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2852
2853public:
2854 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2855
2856 EvalInfo &getEvalInfo() { return Info; }
2857
Richard Smithf57d8cb2011-12-09 22:58:01 +00002858 /// Report an evaluation error. This should only be called when an error is
2859 /// first discovered. When propagating an error, just return false.
2860 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002861 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002862 return false;
2863 }
2864 bool Error(const Expr *E) {
2865 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2866 }
2867
Peter Collingbournee9200682011-05-13 03:29:01 +00002868 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002869 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002870 }
2871 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002872 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002873 }
2874
2875 RetTy VisitParenExpr(const ParenExpr *E)
2876 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2877 RetTy VisitUnaryExtension(const UnaryOperator *E)
2878 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2879 RetTy VisitUnaryPlus(const UnaryOperator *E)
2880 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2881 RetTy VisitChooseExpr(const ChooseExpr *E)
2882 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2883 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2884 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002885 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2886 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002887 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2888 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00002889 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
2890 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002891 // We cannot create any objects for which cleanups are required, so there is
2892 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2893 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2894 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002895
Richard Smith6d6ecc32011-12-12 12:46:16 +00002896 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2897 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2898 return static_cast<Derived*>(this)->VisitCastExpr(E);
2899 }
2900 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2901 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2902 return static_cast<Derived*>(this)->VisitCastExpr(E);
2903 }
2904
Richard Smith027bf112011-11-17 22:56:20 +00002905 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2906 switch (E->getOpcode()) {
2907 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002908 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002909
2910 case BO_Comma:
2911 VisitIgnoredValue(E->getLHS());
2912 return StmtVisitorTy::Visit(E->getRHS());
2913
2914 case BO_PtrMemD:
2915 case BO_PtrMemI: {
2916 LValue Obj;
2917 if (!HandleMemberPointerAccess(Info, E, Obj))
2918 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002919 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00002920 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002921 return false;
2922 return DerivedSuccess(Result, E);
2923 }
2924 }
2925 }
2926
Peter Collingbournee9200682011-05-13 03:29:01 +00002927 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002928 // Evaluate and cache the common expression. We treat it as a temporary,
2929 // even though it's not quite the same thing.
2930 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2931 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002932 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002933
Richard Smith17100ba2012-02-16 02:46:34 +00002934 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002935 }
2936
2937 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002938 bool IsBcpCall = false;
2939 // If the condition (ignoring parens) is a __builtin_constant_p call,
2940 // the result is a constant expression if it can be folded without
2941 // side-effects. This is an important GNU extension. See GCC PR38377
2942 // for discussion.
2943 if (const CallExpr *CallCE =
2944 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2945 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2946 IsBcpCall = true;
2947
2948 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2949 // constant expression; we can't check whether it's potentially foldable.
2950 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2951 return false;
2952
2953 FoldConstant Fold(Info);
2954
Richard Smith17100ba2012-02-16 02:46:34 +00002955 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00002956 return false;
2957
2958 if (IsBcpCall)
2959 Fold.Fold(Info);
2960
2961 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00002962 }
2963
2964 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002965 APValue &Value = Info.CurrentCall->Temporaries[E];
2966 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002967 const Expr *Source = E->getSourceExpr();
2968 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002969 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002970 if (Source == E) { // sanity checking.
2971 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002972 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002973 }
2974 return StmtVisitorTy::Visit(Source);
2975 }
Richard Smith26d4cc12012-06-26 08:12:11 +00002976 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002977 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002978
Richard Smith254a73d2011-10-28 22:34:42 +00002979 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002980 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002981 QualType CalleeType = Callee->getType();
2982
Richard Smith254a73d2011-10-28 22:34:42 +00002983 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002984 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002985 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00002986 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00002987
Richard Smithe97cbd72011-11-11 04:05:33 +00002988 // Extract function decl and 'this' pointer from the callee.
2989 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002990 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002991 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2992 // Explicit bound member calls, such as x.f() or p->g();
2993 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002994 return false;
2995 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002996 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00002997 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00002998 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2999 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003000 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3001 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003002 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003003 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003004 return Error(Callee);
3005
3006 FD = dyn_cast<FunctionDecl>(Member);
3007 if (!FD)
3008 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003009 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003010 LValue Call;
3011 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003012 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003013
Richard Smitha8105bc2012-01-06 16:39:00 +00003014 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003015 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003016 FD = dyn_cast_or_null<FunctionDecl>(
3017 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003018 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003019 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003020
3021 // Overloaded operator calls to member functions are represented as normal
3022 // calls with '*this' as the first argument.
3023 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3024 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003025 // FIXME: When selecting an implicit conversion for an overloaded
3026 // operator delete, we sometimes try to evaluate calls to conversion
3027 // operators without a 'this' parameter!
3028 if (Args.empty())
3029 return Error(E);
3030
Richard Smithe97cbd72011-11-11 04:05:33 +00003031 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3032 return false;
3033 This = &ThisVal;
3034 Args = Args.slice(1);
3035 }
3036
3037 // Don't call function pointers which have been cast to some other type.
3038 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003039 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003040 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003041 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003042
Richard Smith47b34932012-02-01 02:39:43 +00003043 if (This && !This->checkSubobject(Info, E, CSK_This))
3044 return false;
3045
Richard Smith3607ffe2012-02-13 03:54:03 +00003046 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3047 // calls to such functions in constant expressions.
3048 if (This && !HasQualifier &&
3049 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3050 return Error(E, diag::note_constexpr_virtual_call);
3051
Richard Smith357362d2011-12-13 06:39:58 +00003052 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003053 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003054 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003055
Richard Smith357362d2011-12-13 06:39:58 +00003056 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003057 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3058 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003059 return false;
3060
Richard Smithb228a862012-02-15 02:18:13 +00003061 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003062 }
3063
Richard Smith11562c52011-10-28 17:51:58 +00003064 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3065 return StmtVisitorTy::Visit(E->getInitializer());
3066 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003067 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003068 if (E->getNumInits() == 0)
3069 return DerivedZeroInitialization(E);
3070 if (E->getNumInits() == 1)
3071 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003072 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003073 }
3074 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003075 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003076 }
3077 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003078 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003079 }
Richard Smith027bf112011-11-17 22:56:20 +00003080 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003081 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003082 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003083
Richard Smithd62306a2011-11-10 06:34:14 +00003084 /// A member expression where the object is a prvalue is itself a prvalue.
3085 RetTy VisitMemberExpr(const MemberExpr *E) {
3086 assert(!E->isArrow() && "missing call to bound member function?");
3087
Richard Smith2e312c82012-03-03 22:46:17 +00003088 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003089 if (!Evaluate(Val, Info, E->getBase()))
3090 return false;
3091
3092 QualType BaseTy = E->getBase()->getType();
3093
3094 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003095 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003096 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003097 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003098 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3099
Richard Smith3229b742013-05-05 21:17:10 +00003100 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003101 SubobjectDesignator Designator(BaseTy);
3102 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003103
Richard Smith3229b742013-05-05 21:17:10 +00003104 APValue Result;
3105 return extractSubobject(Info, E, Obj, Designator, Result) &&
3106 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003107 }
3108
Richard Smith11562c52011-10-28 17:51:58 +00003109 RetTy VisitCastExpr(const CastExpr *E) {
3110 switch (E->getCastKind()) {
3111 default:
3112 break;
3113
David Chisnallfa35df62012-01-16 17:27:18 +00003114 case CK_AtomicToNonAtomic:
3115 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003116 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003117 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003118 return StmtVisitorTy::Visit(E->getSubExpr());
3119
3120 case CK_LValueToRValue: {
3121 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003122 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3123 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003124 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003125 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003126 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003127 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003128 return false;
3129 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003130 }
3131 }
3132
Richard Smithf57d8cb2011-12-09 22:58:01 +00003133 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003134 }
3135
Richard Smith243ef902013-05-05 23:31:59 +00003136 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3137 return VisitUnaryPostIncDec(UO);
3138 }
3139 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3140 return VisitUnaryPostIncDec(UO);
3141 }
3142 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3143 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3144 return Error(UO);
3145
3146 LValue LVal;
3147 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3148 return false;
3149 APValue RVal;
3150 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3151 UO->isIncrementOp(), &RVal))
3152 return false;
3153 return DerivedSuccess(RVal, UO);
3154 }
3155
Richard Smith4a678122011-10-24 18:44:57 +00003156 /// Visit a value which is evaluated, but whose value is ignored.
3157 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003158 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003159 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003160};
3161
3162}
3163
3164//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003165// Common base class for lvalue and temporary evaluation.
3166//===----------------------------------------------------------------------===//
3167namespace {
3168template<class Derived>
3169class LValueExprEvaluatorBase
3170 : public ExprEvaluatorBase<Derived, bool> {
3171protected:
3172 LValue &Result;
3173 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3174 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3175
3176 bool Success(APValue::LValueBase B) {
3177 Result.set(B);
3178 return true;
3179 }
3180
3181public:
3182 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3183 ExprEvaluatorBaseTy(Info), Result(Result) {}
3184
Richard Smith2e312c82012-03-03 22:46:17 +00003185 bool Success(const APValue &V, const Expr *E) {
3186 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003187 return true;
3188 }
Richard Smith027bf112011-11-17 22:56:20 +00003189
Richard Smith027bf112011-11-17 22:56:20 +00003190 bool VisitMemberExpr(const MemberExpr *E) {
3191 // Handle non-static data members.
3192 QualType BaseTy;
3193 if (E->isArrow()) {
3194 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3195 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003196 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003197 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003198 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003199 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3200 return false;
3201 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003202 } else {
3203 if (!this->Visit(E->getBase()))
3204 return false;
3205 BaseTy = E->getBase()->getType();
3206 }
Richard Smith027bf112011-11-17 22:56:20 +00003207
Richard Smith1b78b3d2012-01-25 22:15:11 +00003208 const ValueDecl *MD = E->getMemberDecl();
3209 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3210 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3211 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3212 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003213 if (!HandleLValueMember(this->Info, E, Result, FD))
3214 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003215 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003216 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3217 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003218 } else
3219 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003220
Richard Smith1b78b3d2012-01-25 22:15:11 +00003221 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003222 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003223 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003224 RefValue))
3225 return false;
3226 return Success(RefValue, E);
3227 }
3228 return true;
3229 }
3230
3231 bool VisitBinaryOperator(const BinaryOperator *E) {
3232 switch (E->getOpcode()) {
3233 default:
3234 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3235
3236 case BO_PtrMemD:
3237 case BO_PtrMemI:
3238 return HandleMemberPointerAccess(this->Info, E, Result);
3239 }
3240 }
3241
3242 bool VisitCastExpr(const CastExpr *E) {
3243 switch (E->getCastKind()) {
3244 default:
3245 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3246
3247 case CK_DerivedToBase:
3248 case CK_UncheckedDerivedToBase: {
3249 if (!this->Visit(E->getSubExpr()))
3250 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003251
3252 // Now figure out the necessary offset to add to the base LV to get from
3253 // the derived class to the base class.
3254 QualType Type = E->getSubExpr()->getType();
3255
3256 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3257 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003258 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003259 *PathI))
3260 return false;
3261 Type = (*PathI)->getType();
3262 }
3263
3264 return true;
3265 }
3266 }
3267 }
3268};
3269}
3270
3271//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003272// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003273//
3274// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3275// function designators (in C), decl references to void objects (in C), and
3276// temporaries (if building with -Wno-address-of-temporary).
3277//
3278// LValue evaluation produces values comprising a base expression of one of the
3279// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003280// - Declarations
3281// * VarDecl
3282// * FunctionDecl
3283// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003284// * CompoundLiteralExpr in C
3285// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003286// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003287// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003288// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003289// * ObjCEncodeExpr
3290// * AddrLabelExpr
3291// * BlockExpr
3292// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003293// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003294// * Any Expr, with a CallIndex indicating the function in which the temporary
3295// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003296// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003297//===----------------------------------------------------------------------===//
3298namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003299class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003300 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003301public:
Richard Smith027bf112011-11-17 22:56:20 +00003302 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3303 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003304
Richard Smith11562c52011-10-28 17:51:58 +00003305 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003306 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003307
Peter Collingbournee9200682011-05-13 03:29:01 +00003308 bool VisitDeclRefExpr(const DeclRefExpr *E);
3309 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003310 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003311 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3312 bool VisitMemberExpr(const MemberExpr *E);
3313 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3314 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003315 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003316 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003317 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3318 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003319 bool VisitUnaryReal(const UnaryOperator *E);
3320 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003321 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3322 return VisitUnaryPreIncDec(UO);
3323 }
3324 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3325 return VisitUnaryPreIncDec(UO);
3326 }
Richard Smith3229b742013-05-05 21:17:10 +00003327 bool VisitBinAssign(const BinaryOperator *BO);
3328 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003329
Peter Collingbournee9200682011-05-13 03:29:01 +00003330 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003331 switch (E->getCastKind()) {
3332 default:
Richard Smith027bf112011-11-17 22:56:20 +00003333 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003334
Eli Friedmance3e02a2011-10-11 00:13:24 +00003335 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003336 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003337 if (!Visit(E->getSubExpr()))
3338 return false;
3339 Result.Designator.setInvalid();
3340 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003341
Richard Smith027bf112011-11-17 22:56:20 +00003342 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003343 if (!Visit(E->getSubExpr()))
3344 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003345 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003346 }
3347 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003348};
3349} // end anonymous namespace
3350
Richard Smith11562c52011-10-28 17:51:58 +00003351/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003352/// expressions which are not glvalues, in two cases:
3353/// * function designators in C, and
3354/// * "extern void" objects
3355static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3356 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3357 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003358 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003359}
3360
Peter Collingbournee9200682011-05-13 03:29:01 +00003361bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003362 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3363 return Success(FD);
3364 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003365 return VisitVarDecl(E, VD);
3366 return Error(E);
3367}
Richard Smith733237d2011-10-24 23:14:33 +00003368
Richard Smith11562c52011-10-28 17:51:58 +00003369bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003370 CallStackFrame *Frame = 0;
3371 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3372 Frame = Info.CurrentCall;
3373
Richard Smithfec09922011-11-01 16:57:24 +00003374 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003375 if (Frame) {
3376 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003377 return true;
3378 }
Richard Smithce40ad62011-11-12 22:28:03 +00003379 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003380 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003381
Richard Smith3229b742013-05-05 21:17:10 +00003382 APValue *V;
3383 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003384 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003385 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003386}
3387
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003388bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3389 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003390 if (E->getType()->isRecordType())
3391 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003392
Richard Smithb228a862012-02-15 02:18:13 +00003393 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003394 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3395 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003396}
3397
Peter Collingbournee9200682011-05-13 03:29:01 +00003398bool
3399LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003400 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3401 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3402 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003403 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003404}
3405
Richard Smith6e525142011-12-27 12:18:28 +00003406bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003407 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003408 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003409
3410 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3411 << E->getExprOperand()->getType()
3412 << E->getExprOperand()->getSourceRange();
3413 return false;
Richard Smith6e525142011-12-27 12:18:28 +00003414}
3415
Francois Pichet0066db92012-04-16 04:08:35 +00003416bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3417 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00003418}
Francois Pichet0066db92012-04-16 04:08:35 +00003419
Peter Collingbournee9200682011-05-13 03:29:01 +00003420bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003421 // Handle static data members.
3422 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3423 VisitIgnoredValue(E->getBase());
3424 return VisitVarDecl(E, VD);
3425 }
3426
Richard Smith254a73d2011-10-28 22:34:42 +00003427 // Handle static member functions.
3428 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3429 if (MD->isStatic()) {
3430 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003431 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003432 }
3433 }
3434
Richard Smithd62306a2011-11-10 06:34:14 +00003435 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003436 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003437}
3438
Peter Collingbournee9200682011-05-13 03:29:01 +00003439bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003440 // FIXME: Deal with vectors as array subscript bases.
3441 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003442 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003443
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003444 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003445 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003446
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003447 APSInt Index;
3448 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003449 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003450 int64_t IndexValue
3451 = Index.isSigned() ? Index.getSExtValue()
3452 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003453
Richard Smitha8105bc2012-01-06 16:39:00 +00003454 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003455}
Eli Friedman9a156e52008-11-12 09:44:48 +00003456
Peter Collingbournee9200682011-05-13 03:29:01 +00003457bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003458 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003459}
3460
Richard Smith66c96992012-02-18 22:04:06 +00003461bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3462 if (!Visit(E->getSubExpr()))
3463 return false;
3464 // __real is a no-op on scalar lvalues.
3465 if (E->getSubExpr()->getType()->isAnyComplexType())
3466 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3467 return true;
3468}
3469
3470bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3471 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3472 "lvalue __imag__ on scalar?");
3473 if (!Visit(E->getSubExpr()))
3474 return false;
3475 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3476 return true;
3477}
3478
Richard Smith243ef902013-05-05 23:31:59 +00003479bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
3480 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003481 return Error(UO);
3482
3483 if (!this->Visit(UO->getSubExpr()))
3484 return false;
3485
Richard Smith243ef902013-05-05 23:31:59 +00003486 return handleIncDec(
3487 this->Info, UO, Result, UO->getSubExpr()->getType(),
3488 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00003489}
3490
3491bool LValueExprEvaluator::VisitCompoundAssignOperator(
3492 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00003493 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003494 return Error(CAO);
3495
Richard Smith3229b742013-05-05 21:17:10 +00003496 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00003497
3498 // The overall lvalue result is the result of evaluating the LHS.
3499 if (!this->Visit(CAO->getLHS())) {
3500 if (Info.keepEvaluatingAfterFailure())
3501 Evaluate(RHS, this->Info, CAO->getRHS());
3502 return false;
3503 }
3504
Richard Smith3229b742013-05-05 21:17:10 +00003505 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
3506 return false;
3507
3508 // FIXME:
3509 //return handleCompoundAssignment(
3510 // this->Info, CAO,
3511 // Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
3512 // RHS, CAO->getRHS()->getType(),
3513 // CAO->getOpForCompoundAssignment(CAO->getOpcode()),
3514 // CAO->getComputationResultType());
3515 return Error(CAO);
3516}
3517
3518bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00003519 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3520 return Error(E);
3521
Richard Smith3229b742013-05-05 21:17:10 +00003522 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00003523
3524 if (!this->Visit(E->getLHS())) {
3525 if (Info.keepEvaluatingAfterFailure())
3526 Evaluate(NewVal, this->Info, E->getRHS());
3527 return false;
3528 }
3529
Richard Smith3229b742013-05-05 21:17:10 +00003530 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3531 return false;
Richard Smith243ef902013-05-05 23:31:59 +00003532
3533 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00003534 NewVal);
3535}
3536
Eli Friedman9a156e52008-11-12 09:44:48 +00003537//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003538// Pointer Evaluation
3539//===----------------------------------------------------------------------===//
3540
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003541namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003542class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003543 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003544 LValue &Result;
3545
Peter Collingbournee9200682011-05-13 03:29:01 +00003546 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003547 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003548 return true;
3549 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003550public:
Mike Stump11289f42009-09-09 15:08:12 +00003551
John McCall45d55e42010-05-07 21:00:08 +00003552 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003553 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003554
Richard Smith2e312c82012-03-03 22:46:17 +00003555 bool Success(const APValue &V, const Expr *E) {
3556 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00003557 return true;
3558 }
Richard Smithfddd3842011-12-30 21:15:51 +00003559 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003560 return Success((Expr*)0);
3561 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003562
John McCall45d55e42010-05-07 21:00:08 +00003563 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003564 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003565 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003566 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003567 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003568 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003569 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003570 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003571 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003572 bool VisitCallExpr(const CallExpr *E);
3573 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003574 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003575 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003576 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003577 }
Richard Smithd62306a2011-11-10 06:34:14 +00003578 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3579 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003580 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003581 Result = *Info.CurrentCall->This;
3582 return true;
3583 }
John McCallc07a0c72011-02-17 10:25:35 +00003584
Eli Friedman449fe542009-03-23 04:56:01 +00003585 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003586};
Chris Lattner05706e882008-07-11 18:11:29 +00003587} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003588
John McCall45d55e42010-05-07 21:00:08 +00003589static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003590 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003591 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003592}
3593
John McCall45d55e42010-05-07 21:00:08 +00003594bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003595 if (E->getOpcode() != BO_Add &&
3596 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003597 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003598
Chris Lattner05706e882008-07-11 18:11:29 +00003599 const Expr *PExp = E->getLHS();
3600 const Expr *IExp = E->getRHS();
3601 if (IExp->getType()->isPointerType())
3602 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003603
Richard Smith253c2a32012-01-27 01:14:48 +00003604 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3605 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003606 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003607
John McCall45d55e42010-05-07 21:00:08 +00003608 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003609 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003610 return false;
3611 int64_t AdditionalOffset
3612 = Offset.isSigned() ? Offset.getSExtValue()
3613 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003614 if (E->getOpcode() == BO_Sub)
3615 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003616
Ted Kremenek28831752012-08-23 20:46:57 +00003617 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003618 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3619 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003620}
Eli Friedman9a156e52008-11-12 09:44:48 +00003621
John McCall45d55e42010-05-07 21:00:08 +00003622bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3623 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003624}
Mike Stump11289f42009-09-09 15:08:12 +00003625
Peter Collingbournee9200682011-05-13 03:29:01 +00003626bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3627 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003628
Eli Friedman847a2bc2009-12-27 05:43:15 +00003629 switch (E->getCastKind()) {
3630 default:
3631 break;
3632
John McCalle3027922010-08-25 11:45:40 +00003633 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003634 case CK_CPointerToObjCPointerCast:
3635 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003636 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003637 if (!Visit(SubExpr))
3638 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003639 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3640 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3641 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003642 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003643 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003644 if (SubExpr->getType()->isVoidPointerType())
3645 CCEDiag(E, diag::note_constexpr_invalid_cast)
3646 << 3 << SubExpr->getType();
3647 else
3648 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3649 }
Richard Smith96e0c102011-11-04 02:25:55 +00003650 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003651
Anders Carlsson18275092010-10-31 20:41:46 +00003652 case CK_DerivedToBase:
3653 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003654 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003655 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003656 if (!Result.Base && Result.Offset.isZero())
3657 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003658
Richard Smithd62306a2011-11-10 06:34:14 +00003659 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003660 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003661 QualType Type =
3662 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003663
Richard Smithd62306a2011-11-10 06:34:14 +00003664 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003665 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003666 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3667 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003668 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003669 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003670 }
3671
Anders Carlsson18275092010-10-31 20:41:46 +00003672 return true;
3673 }
3674
Richard Smith027bf112011-11-17 22:56:20 +00003675 case CK_BaseToDerived:
3676 if (!Visit(E->getSubExpr()))
3677 return false;
3678 if (!Result.Base && Result.Offset.isZero())
3679 return true;
3680 return HandleBaseToDerivedCast(Info, E, Result);
3681
Richard Smith0b0a0b62011-10-29 20:57:55 +00003682 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003683 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003684 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003685
John McCalle3027922010-08-25 11:45:40 +00003686 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003687 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3688
Richard Smith2e312c82012-03-03 22:46:17 +00003689 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003690 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003691 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003692
John McCall45d55e42010-05-07 21:00:08 +00003693 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003694 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3695 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003696 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003697 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003698 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003699 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003700 return true;
3701 } else {
3702 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003703 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003704 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003705 }
3706 }
John McCalle3027922010-08-25 11:45:40 +00003707 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003708 if (SubExpr->isGLValue()) {
3709 if (!EvaluateLValue(SubExpr, Result, Info))
3710 return false;
3711 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003712 Result.set(SubExpr, Info.CurrentCall->Index);
3713 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3714 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003715 return false;
3716 }
Richard Smith96e0c102011-11-04 02:25:55 +00003717 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003718 if (const ConstantArrayType *CAT
3719 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3720 Result.addArray(Info, E, CAT);
3721 else
3722 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003723 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003724
John McCalle3027922010-08-25 11:45:40 +00003725 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003726 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003727 }
3728
Richard Smith11562c52011-10-28 17:51:58 +00003729 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003730}
Chris Lattner05706e882008-07-11 18:11:29 +00003731
Peter Collingbournee9200682011-05-13 03:29:01 +00003732bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003733 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003734 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003735
Peter Collingbournee9200682011-05-13 03:29:01 +00003736 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003737}
Chris Lattner05706e882008-07-11 18:11:29 +00003738
3739//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003740// Member Pointer Evaluation
3741//===----------------------------------------------------------------------===//
3742
3743namespace {
3744class MemberPointerExprEvaluator
3745 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3746 MemberPtr &Result;
3747
3748 bool Success(const ValueDecl *D) {
3749 Result = MemberPtr(D);
3750 return true;
3751 }
3752public:
3753
3754 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3755 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3756
Richard Smith2e312c82012-03-03 22:46:17 +00003757 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003758 Result.setFrom(V);
3759 return true;
3760 }
Richard Smithfddd3842011-12-30 21:15:51 +00003761 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003762 return Success((const ValueDecl*)0);
3763 }
3764
3765 bool VisitCastExpr(const CastExpr *E);
3766 bool VisitUnaryAddrOf(const UnaryOperator *E);
3767};
3768} // end anonymous namespace
3769
3770static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3771 EvalInfo &Info) {
3772 assert(E->isRValue() && E->getType()->isMemberPointerType());
3773 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3774}
3775
3776bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3777 switch (E->getCastKind()) {
3778 default:
3779 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3780
3781 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003782 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003783 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003784
3785 case CK_BaseToDerivedMemberPointer: {
3786 if (!Visit(E->getSubExpr()))
3787 return false;
3788 if (E->path_empty())
3789 return true;
3790 // Base-to-derived member pointer casts store the path in derived-to-base
3791 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3792 // the wrong end of the derived->base arc, so stagger the path by one class.
3793 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3794 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3795 PathI != PathE; ++PathI) {
3796 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3797 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3798 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003799 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003800 }
3801 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3802 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003803 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003804 return true;
3805 }
3806
3807 case CK_DerivedToBaseMemberPointer:
3808 if (!Visit(E->getSubExpr()))
3809 return false;
3810 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3811 PathE = E->path_end(); PathI != PathE; ++PathI) {
3812 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3813 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3814 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003815 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003816 }
3817 return true;
3818 }
3819}
3820
3821bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3822 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3823 // member can be formed.
3824 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3825}
3826
3827//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003828// Record Evaluation
3829//===----------------------------------------------------------------------===//
3830
3831namespace {
3832 class RecordExprEvaluator
3833 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3834 const LValue &This;
3835 APValue &Result;
3836 public:
3837
3838 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3839 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3840
Richard Smith2e312c82012-03-03 22:46:17 +00003841 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003842 Result = V;
3843 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003844 }
Richard Smithfddd3842011-12-30 21:15:51 +00003845 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003846
Richard Smithe97cbd72011-11-11 04:05:33 +00003847 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003848 bool VisitInitListExpr(const InitListExpr *E);
3849 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3850 };
3851}
3852
Richard Smithfddd3842011-12-30 21:15:51 +00003853/// Perform zero-initialization on an object of non-union class type.
3854/// C++11 [dcl.init]p5:
3855/// To zero-initialize an object or reference of type T means:
3856/// [...]
3857/// -- if T is a (possibly cv-qualified) non-union class type,
3858/// each non-static data member and each base-class subobject is
3859/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003860static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3861 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003862 const LValue &This, APValue &Result) {
3863 assert(!RD->isUnion() && "Expected non-union class type");
3864 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3865 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3866 std::distance(RD->field_begin(), RD->field_end()));
3867
John McCalld7bca762012-05-01 00:38:49 +00003868 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003869 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3870
3871 if (CD) {
3872 unsigned Index = 0;
3873 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003874 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00003875 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3876 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003877 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3878 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003879 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00003880 Result.getStructBase(Index)))
3881 return false;
3882 }
3883 }
3884
Richard Smitha8105bc2012-01-06 16:39:00 +00003885 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3886 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00003887 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00003888 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00003889 continue;
3890
3891 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003892 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003893 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003894
David Blaikie2d7c57e2012-04-30 02:36:29 +00003895 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003896 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00003897 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003898 return false;
3899 }
3900
3901 return true;
3902}
3903
3904bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3905 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003906 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003907 if (RD->isUnion()) {
3908 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3909 // object's first non-static named data member is zero-initialized
3910 RecordDecl::field_iterator I = RD->field_begin();
3911 if (I == RD->field_end()) {
3912 Result = APValue((const FieldDecl*)0);
3913 return true;
3914 }
3915
3916 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003917 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00003918 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00003919 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003920 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003921 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003922 }
3923
Richard Smith5d108602012-02-17 00:44:16 +00003924 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003925 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00003926 return false;
3927 }
3928
Richard Smitha8105bc2012-01-06 16:39:00 +00003929 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00003930}
3931
Richard Smithe97cbd72011-11-11 04:05:33 +00003932bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3933 switch (E->getCastKind()) {
3934 default:
3935 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3936
3937 case CK_ConstructorConversion:
3938 return Visit(E->getSubExpr());
3939
3940 case CK_DerivedToBase:
3941 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00003942 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003943 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00003944 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003945 if (!DerivedObject.isStruct())
3946 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00003947
3948 // Derived-to-base rvalue conversion: just slice off the derived part.
3949 APValue *Value = &DerivedObject;
3950 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3951 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3952 PathE = E->path_end(); PathI != PathE; ++PathI) {
3953 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3954 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3955 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3956 RD = Base;
3957 }
3958 Result = *Value;
3959 return true;
3960 }
3961 }
3962}
3963
Richard Smithd62306a2011-11-10 06:34:14 +00003964bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00003965 // Cannot constant-evaluate std::initializer_list inits.
3966 if (E->initializesStdInitializerList())
3967 return false;
3968
Richard Smithd62306a2011-11-10 06:34:14 +00003969 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003970 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003971 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3972
3973 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00003974 const FieldDecl *Field = E->getInitializedFieldInUnion();
3975 Result = APValue(Field);
3976 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00003977 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00003978
3979 // If the initializer list for a union does not contain any elements, the
3980 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00003981 // FIXME: The element should be initialized from an initializer list.
3982 // Is this difference ever observable for initializer lists which
3983 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00003984 ImplicitValueInitExpr VIE(Field->getType());
3985 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3986
Richard Smithd62306a2011-11-10 06:34:14 +00003987 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003988 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3989 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00003990
3991 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3992 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3993 isa<CXXDefaultInitExpr>(InitExpr));
3994
Richard Smithb228a862012-02-15 02:18:13 +00003995 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00003996 }
3997
3998 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3999 "initializer list for class with base classes");
4000 Result = APValue(APValue::UninitStruct(), 0,
4001 std::distance(RD->field_begin(), RD->field_end()));
4002 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004003 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004004 for (RecordDecl::field_iterator Field = RD->field_begin(),
4005 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4006 // Anonymous bit-fields are not considered members of the class for
4007 // purposes of aggregate initialization.
4008 if (Field->isUnnamedBitfield())
4009 continue;
4010
4011 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004012
Richard Smith253c2a32012-01-27 01:14:48 +00004013 bool HaveInit = ElementNo < E->getNumInits();
4014
4015 // FIXME: Diagnostics here should point to the end of the initializer
4016 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004017 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004018 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004019 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004020
4021 // Perform an implicit value-initialization for members beyond the end of
4022 // the initializer list.
4023 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004024 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004025
Richard Smith852c9db2013-04-20 22:23:05 +00004026 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4027 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4028 isa<CXXDefaultInitExpr>(Init));
4029
4030 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4031 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004032 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004033 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004034 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004035 }
4036 }
4037
Richard Smith253c2a32012-01-27 01:14:48 +00004038 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004039}
4040
4041bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4042 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004043 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4044
Richard Smithfddd3842011-12-30 21:15:51 +00004045 bool ZeroInit = E->requiresZeroInitialization();
4046 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004047 // If we've already performed zero-initialization, we're already done.
4048 if (!Result.isUninit())
4049 return true;
4050
Richard Smithfddd3842011-12-30 21:15:51 +00004051 if (ZeroInit)
4052 return ZeroInitialization(E);
4053
Richard Smithcc36f692011-12-22 02:22:31 +00004054 const CXXRecordDecl *RD = FD->getParent();
4055 if (RD->isUnion())
4056 Result = APValue((FieldDecl*)0);
4057 else
4058 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4059 std::distance(RD->field_begin(), RD->field_end()));
4060 return true;
4061 }
4062
Richard Smithd62306a2011-11-10 06:34:14 +00004063 const FunctionDecl *Definition = 0;
4064 FD->getBody(Definition);
4065
Richard Smith357362d2011-12-13 06:39:58 +00004066 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4067 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004068
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004069 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004070 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004071 if (const MaterializeTemporaryExpr *ME
4072 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4073 return Visit(ME->GetTemporaryExpr());
4074
Richard Smithfddd3842011-12-30 21:15:51 +00004075 if (ZeroInit && !ZeroInitialization(E))
4076 return false;
4077
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004078 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004079 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004080 cast<CXXConstructorDecl>(Definition), Info,
4081 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004082}
4083
4084static bool EvaluateRecord(const Expr *E, const LValue &This,
4085 APValue &Result, EvalInfo &Info) {
4086 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004087 "can't evaluate expression as a record rvalue");
4088 return RecordExprEvaluator(Info, This, Result).Visit(E);
4089}
4090
4091//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004092// Temporary Evaluation
4093//
4094// Temporaries are represented in the AST as rvalues, but generally behave like
4095// lvalues. The full-object of which the temporary is a subobject is implicitly
4096// materialized so that a reference can bind to it.
4097//===----------------------------------------------------------------------===//
4098namespace {
4099class TemporaryExprEvaluator
4100 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4101public:
4102 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4103 LValueExprEvaluatorBaseTy(Info, Result) {}
4104
4105 /// Visit an expression which constructs the value of this temporary.
4106 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004107 Result.set(E, Info.CurrentCall->Index);
4108 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004109 }
4110
4111 bool VisitCastExpr(const CastExpr *E) {
4112 switch (E->getCastKind()) {
4113 default:
4114 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4115
4116 case CK_ConstructorConversion:
4117 return VisitConstructExpr(E->getSubExpr());
4118 }
4119 }
4120 bool VisitInitListExpr(const InitListExpr *E) {
4121 return VisitConstructExpr(E);
4122 }
4123 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4124 return VisitConstructExpr(E);
4125 }
4126 bool VisitCallExpr(const CallExpr *E) {
4127 return VisitConstructExpr(E);
4128 }
4129};
4130} // end anonymous namespace
4131
4132/// Evaluate an expression of record type as a temporary.
4133static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004134 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004135 return TemporaryExprEvaluator(Info, Result).Visit(E);
4136}
4137
4138//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004139// Vector Evaluation
4140//===----------------------------------------------------------------------===//
4141
4142namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004143 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004144 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4145 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004146 public:
Mike Stump11289f42009-09-09 15:08:12 +00004147
Richard Smith2d406342011-10-22 21:10:00 +00004148 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4149 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004150
Richard Smith2d406342011-10-22 21:10:00 +00004151 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4152 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4153 // FIXME: remove this APValue copy.
4154 Result = APValue(V.data(), V.size());
4155 return true;
4156 }
Richard Smith2e312c82012-03-03 22:46:17 +00004157 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004158 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004159 Result = V;
4160 return true;
4161 }
Richard Smithfddd3842011-12-30 21:15:51 +00004162 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004163
Richard Smith2d406342011-10-22 21:10:00 +00004164 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004165 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004166 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004167 bool VisitInitListExpr(const InitListExpr *E);
4168 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004169 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004170 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004171 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004172 };
4173} // end anonymous namespace
4174
4175static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004176 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004177 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004178}
4179
Richard Smith2d406342011-10-22 21:10:00 +00004180bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4181 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004182 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004183
Richard Smith161f09a2011-12-06 22:44:34 +00004184 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004185 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004186
Eli Friedmanc757de22011-03-25 00:43:55 +00004187 switch (E->getCastKind()) {
4188 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004189 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004190 if (SETy->isIntegerType()) {
4191 APSInt IntResult;
4192 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004193 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004194 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004195 } else if (SETy->isRealFloatingType()) {
4196 APFloat F(0.0);
4197 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004198 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004199 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004200 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004201 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004202 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004203
4204 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004205 SmallVector<APValue, 4> Elts(NElts, Val);
4206 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004207 }
Eli Friedman803acb32011-12-22 03:51:45 +00004208 case CK_BitCast: {
4209 // Evaluate the operand into an APInt we can extract from.
4210 llvm::APInt SValInt;
4211 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4212 return false;
4213 // Extract the elements
4214 QualType EltTy = VTy->getElementType();
4215 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4216 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4217 SmallVector<APValue, 4> Elts;
4218 if (EltTy->isRealFloatingType()) {
4219 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004220 unsigned FloatEltSize = EltSize;
4221 if (&Sem == &APFloat::x87DoubleExtended)
4222 FloatEltSize = 80;
4223 for (unsigned i = 0; i < NElts; i++) {
4224 llvm::APInt Elt;
4225 if (BigEndian)
4226 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4227 else
4228 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004229 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004230 }
4231 } else if (EltTy->isIntegerType()) {
4232 for (unsigned i = 0; i < NElts; i++) {
4233 llvm::APInt Elt;
4234 if (BigEndian)
4235 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4236 else
4237 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4238 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4239 }
4240 } else {
4241 return Error(E);
4242 }
4243 return Success(Elts, E);
4244 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004245 default:
Richard Smith11562c52011-10-28 17:51:58 +00004246 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004247 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004248}
4249
Richard Smith2d406342011-10-22 21:10:00 +00004250bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004251VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004252 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004253 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004254 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004255
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004256 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004257 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004258
Eli Friedmanb9c71292012-01-03 23:24:20 +00004259 // The number of initializers can be less than the number of
4260 // vector elements. For OpenCL, this can be due to nested vector
4261 // initialization. For GCC compatibility, missing trailing elements
4262 // should be initialized with zeroes.
4263 unsigned CountInits = 0, CountElts = 0;
4264 while (CountElts < NumElements) {
4265 // Handle nested vector initialization.
4266 if (CountInits < NumInits
4267 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4268 APValue v;
4269 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4270 return Error(E);
4271 unsigned vlen = v.getVectorLength();
4272 for (unsigned j = 0; j < vlen; j++)
4273 Elements.push_back(v.getVectorElt(j));
4274 CountElts += vlen;
4275 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004276 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004277 if (CountInits < NumInits) {
4278 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004279 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004280 } else // trailing integer zero.
4281 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4282 Elements.push_back(APValue(sInt));
4283 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004284 } else {
4285 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004286 if (CountInits < NumInits) {
4287 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004288 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004289 } else // trailing float zero.
4290 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4291 Elements.push_back(APValue(f));
4292 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004293 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004294 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004295 }
Richard Smith2d406342011-10-22 21:10:00 +00004296 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004297}
4298
Richard Smith2d406342011-10-22 21:10:00 +00004299bool
Richard Smithfddd3842011-12-30 21:15:51 +00004300VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004301 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004302 QualType EltTy = VT->getElementType();
4303 APValue ZeroElement;
4304 if (EltTy->isIntegerType())
4305 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4306 else
4307 ZeroElement =
4308 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4309
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004310 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004311 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004312}
4313
Richard Smith2d406342011-10-22 21:10:00 +00004314bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004315 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004316 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004317}
4318
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004319//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004320// Array Evaluation
4321//===----------------------------------------------------------------------===//
4322
4323namespace {
4324 class ArrayExprEvaluator
4325 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004326 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004327 APValue &Result;
4328 public:
4329
Richard Smithd62306a2011-11-10 06:34:14 +00004330 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4331 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004332
4333 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004334 assert((V.isArray() || V.isLValue()) &&
4335 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004336 Result = V;
4337 return true;
4338 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004339
Richard Smithfddd3842011-12-30 21:15:51 +00004340 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004341 const ConstantArrayType *CAT =
4342 Info.Ctx.getAsConstantArrayType(E->getType());
4343 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004344 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004345
4346 Result = APValue(APValue::UninitArray(), 0,
4347 CAT->getSize().getZExtValue());
4348 if (!Result.hasArrayFiller()) return true;
4349
Richard Smithfddd3842011-12-30 21:15:51 +00004350 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004351 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004352 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004353 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004354 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004355 }
4356
Richard Smithf3e9e432011-11-07 09:22:26 +00004357 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004358 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004359 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4360 const LValue &Subobject,
4361 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004362 };
4363} // end anonymous namespace
4364
Richard Smithd62306a2011-11-10 06:34:14 +00004365static bool EvaluateArray(const Expr *E, const LValue &This,
4366 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004367 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004368 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004369}
4370
4371bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4372 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4373 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004374 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004375
Richard Smithca2cfbf2011-12-22 01:07:19 +00004376 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4377 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004378 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004379 LValue LV;
4380 if (!EvaluateLValue(E->getInit(0), LV, Info))
4381 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004382 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004383 LV.moveInto(Val);
4384 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004385 }
4386
Richard Smith253c2a32012-01-27 01:14:48 +00004387 bool Success = true;
4388
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004389 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4390 "zero-initialized array shouldn't have any initialized elts");
4391 APValue Filler;
4392 if (Result.isArray() && Result.hasArrayFiller())
4393 Filler = Result.getArrayFiller();
4394
Richard Smith9543c5e2013-04-22 14:44:29 +00004395 unsigned NumEltsToInit = E->getNumInits();
4396 unsigned NumElts = CAT->getSize().getZExtValue();
4397 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4398
4399 // If the initializer might depend on the array index, run it for each
4400 // array element. For now, just whitelist non-class value-initialization.
4401 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4402 NumEltsToInit = NumElts;
4403
4404 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004405
4406 // If the array was previously zero-initialized, preserve the
4407 // zero-initialized values.
4408 if (!Filler.isUninit()) {
4409 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4410 Result.getArrayInitializedElt(I) = Filler;
4411 if (Result.hasArrayFiller())
4412 Result.getArrayFiller() = Filler;
4413 }
4414
Richard Smithd62306a2011-11-10 06:34:14 +00004415 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004416 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004417 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4418 const Expr *Init =
4419 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00004420 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00004421 Info, Subobject, Init) ||
4422 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00004423 CAT->getElementType(), 1)) {
4424 if (!Info.keepEvaluatingAfterFailure())
4425 return false;
4426 Success = false;
4427 }
Richard Smithd62306a2011-11-10 06:34:14 +00004428 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004429
Richard Smith9543c5e2013-04-22 14:44:29 +00004430 if (!Result.hasArrayFiller())
4431 return Success;
4432
4433 // If we get here, we have a trivial filler, which we can just evaluate
4434 // once and splat over the rest of the array elements.
4435 assert(FillerExpr && "no array filler for incomplete init list");
4436 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4437 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00004438}
4439
Richard Smith027bf112011-11-17 22:56:20 +00004440bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004441 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4442}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004443
Richard Smith9543c5e2013-04-22 14:44:29 +00004444bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4445 const LValue &Subobject,
4446 APValue *Value,
4447 QualType Type) {
4448 bool HadZeroInit = !Value->isUninit();
4449
4450 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4451 unsigned N = CAT->getSize().getZExtValue();
4452
4453 // Preserve the array filler if we had prior zero-initialization.
4454 APValue Filler =
4455 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4456 : APValue();
4457
4458 *Value = APValue(APValue::UninitArray(), N, N);
4459
4460 if (HadZeroInit)
4461 for (unsigned I = 0; I != N; ++I)
4462 Value->getArrayInitializedElt(I) = Filler;
4463
4464 // Initialize the elements.
4465 LValue ArrayElt = Subobject;
4466 ArrayElt.addArray(Info, E, CAT);
4467 for (unsigned I = 0; I != N; ++I)
4468 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4469 CAT->getElementType()) ||
4470 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4471 CAT->getElementType(), 1))
4472 return false;
4473
4474 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004475 }
Richard Smith027bf112011-11-17 22:56:20 +00004476
Richard Smith9543c5e2013-04-22 14:44:29 +00004477 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004478 return Error(E);
4479
Richard Smith027bf112011-11-17 22:56:20 +00004480 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004481
Richard Smithfddd3842011-12-30 21:15:51 +00004482 bool ZeroInit = E->requiresZeroInitialization();
4483 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004484 if (HadZeroInit)
4485 return true;
4486
Richard Smithfddd3842011-12-30 21:15:51 +00004487 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004488 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004489 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004490 }
4491
Richard Smithcc36f692011-12-22 02:22:31 +00004492 const CXXRecordDecl *RD = FD->getParent();
4493 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004494 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004495 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004496 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004497 APValue(APValue::UninitStruct(), RD->getNumBases(),
4498 std::distance(RD->field_begin(), RD->field_end()));
4499 return true;
4500 }
4501
Richard Smith027bf112011-11-17 22:56:20 +00004502 const FunctionDecl *Definition = 0;
4503 FD->getBody(Definition);
4504
Richard Smith357362d2011-12-13 06:39:58 +00004505 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4506 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004507
Richard Smith9eae7232012-01-12 18:54:33 +00004508 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004509 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004510 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004511 return false;
4512 }
4513
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004514 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004515 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004516 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004517 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004518}
4519
Richard Smithf3e9e432011-11-07 09:22:26 +00004520//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004521// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004522//
4523// As a GNU extension, we support casting pointers to sufficiently-wide integer
4524// types and back in constant folding. Integer values are thus represented
4525// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004526//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004527
4528namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004529class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004530 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004531 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004532public:
Richard Smith2e312c82012-03-03 22:46:17 +00004533 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004534 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004535
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004536 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004537 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004538 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004539 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004540 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004541 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004542 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004543 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004544 return true;
4545 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004546 bool Success(const llvm::APSInt &SI, const Expr *E) {
4547 return Success(SI, E, Result);
4548 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004549
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004550 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004551 assert(E->getType()->isIntegralOrEnumerationType() &&
4552 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004553 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004554 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004555 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004556 Result.getInt().setIsUnsigned(
4557 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004558 return true;
4559 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004560 bool Success(const llvm::APInt &I, const Expr *E) {
4561 return Success(I, E, Result);
4562 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004563
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004564 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004565 assert(E->getType()->isIntegralOrEnumerationType() &&
4566 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004567 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004568 return true;
4569 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004570 bool Success(uint64_t Value, const Expr *E) {
4571 return Success(Value, E, Result);
4572 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004573
Ken Dyckdbc01912011-03-11 02:13:43 +00004574 bool Success(CharUnits Size, const Expr *E) {
4575 return Success(Size.getQuantity(), E);
4576 }
4577
Richard Smith2e312c82012-03-03 22:46:17 +00004578 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004579 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00004580 Result = V;
4581 return true;
4582 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004583 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004584 }
Mike Stump11289f42009-09-09 15:08:12 +00004585
Richard Smithfddd3842011-12-30 21:15:51 +00004586 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00004587
Peter Collingbournee9200682011-05-13 03:29:01 +00004588 //===--------------------------------------------------------------------===//
4589 // Visitor Methods
4590 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004591
Chris Lattner7174bf32008-07-12 00:38:25 +00004592 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004593 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004594 }
4595 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004596 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004597 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004598
4599 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4600 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004601 if (CheckReferencedDecl(E, E->getDecl()))
4602 return true;
4603
4604 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004605 }
4606 bool VisitMemberExpr(const MemberExpr *E) {
4607 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004608 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004609 return true;
4610 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004611
4612 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004613 }
4614
Peter Collingbournee9200682011-05-13 03:29:01 +00004615 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004616 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004617 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004618 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004619
Peter Collingbournee9200682011-05-13 03:29:01 +00004620 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004621 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004622
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004623 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004624 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004625 }
Mike Stump11289f42009-09-09 15:08:12 +00004626
Ted Kremeneke65b0862012-03-06 20:05:56 +00004627 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4628 return Success(E->getValue(), E);
4629 }
4630
Richard Smith4ce706a2011-10-11 21:43:33 +00004631 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004632 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004633 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004634 }
4635
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004636 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004637 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004638 }
4639
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004640 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4641 return Success(E->getValue(), E);
4642 }
4643
Douglas Gregor29c42f22012-02-24 07:38:34 +00004644 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4645 return Success(E->getValue(), E);
4646 }
4647
John Wiegley6242b6a2011-04-28 00:16:57 +00004648 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4649 return Success(E->getValue(), E);
4650 }
4651
John Wiegleyf9f65842011-04-25 06:54:41 +00004652 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4653 return Success(E->getValue(), E);
4654 }
4655
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004656 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004657 bool VisitUnaryImag(const UnaryOperator *E);
4658
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004659 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004660 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004661
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004662private:
Ken Dyck160146e2010-01-27 17:10:57 +00004663 CharUnits GetAlignOfExpr(const Expr *E);
4664 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004665 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004666 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004667 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004668};
Chris Lattner05706e882008-07-11 18:11:29 +00004669} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004670
Richard Smith11562c52011-10-28 17:51:58 +00004671/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4672/// produce either the integer value or a pointer.
4673///
4674/// GCC has a heinous extension which folds casts between pointer types and
4675/// pointer-sized integral types. We support this by allowing the evaluation of
4676/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4677/// Some simple arithmetic on such values is supported (they are treated much
4678/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004679static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004680 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004681 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004682 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004683}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004684
Richard Smithf57d8cb2011-12-09 22:58:01 +00004685static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004686 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004687 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004688 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004689 if (!Val.isInt()) {
4690 // FIXME: It would be better to produce the diagnostic for casting
4691 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004692 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004693 return false;
4694 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004695 Result = Val.getInt();
4696 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004697}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004698
Richard Smithf57d8cb2011-12-09 22:58:01 +00004699/// Check whether the given declaration can be directly converted to an integral
4700/// rvalue. If not, no diagnostic is produced; there are other things we can
4701/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004702bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004703 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004704 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004705 // Check for signedness/width mismatches between E type and ECD value.
4706 bool SameSign = (ECD->getInitVal().isSigned()
4707 == E->getType()->isSignedIntegerOrEnumerationType());
4708 bool SameWidth = (ECD->getInitVal().getBitWidth()
4709 == Info.Ctx.getIntWidth(E->getType()));
4710 if (SameSign && SameWidth)
4711 return Success(ECD->getInitVal(), E);
4712 else {
4713 // Get rid of mismatch (otherwise Success assertions will fail)
4714 // by computing a new value matching the type of E.
4715 llvm::APSInt Val = ECD->getInitVal();
4716 if (!SameSign)
4717 Val.setIsSigned(!ECD->getInitVal().isSigned());
4718 if (!SameWidth)
4719 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4720 return Success(Val, E);
4721 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004722 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004723 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004724}
4725
Chris Lattner86ee2862008-10-06 06:40:35 +00004726/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4727/// as GCC.
4728static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4729 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004730 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004731 enum gcc_type_class {
4732 no_type_class = -1,
4733 void_type_class, integer_type_class, char_type_class,
4734 enumeral_type_class, boolean_type_class,
4735 pointer_type_class, reference_type_class, offset_type_class,
4736 real_type_class, complex_type_class,
4737 function_type_class, method_type_class,
4738 record_type_class, union_type_class,
4739 array_type_class, string_type_class,
4740 lang_type_class
4741 };
Mike Stump11289f42009-09-09 15:08:12 +00004742
4743 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004744 // ideal, however it is what gcc does.
4745 if (E->getNumArgs() == 0)
4746 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004747
Chris Lattner86ee2862008-10-06 06:40:35 +00004748 QualType ArgTy = E->getArg(0)->getType();
4749 if (ArgTy->isVoidType())
4750 return void_type_class;
4751 else if (ArgTy->isEnumeralType())
4752 return enumeral_type_class;
4753 else if (ArgTy->isBooleanType())
4754 return boolean_type_class;
4755 else if (ArgTy->isCharType())
4756 return string_type_class; // gcc doesn't appear to use char_type_class
4757 else if (ArgTy->isIntegerType())
4758 return integer_type_class;
4759 else if (ArgTy->isPointerType())
4760 return pointer_type_class;
4761 else if (ArgTy->isReferenceType())
4762 return reference_type_class;
4763 else if (ArgTy->isRealType())
4764 return real_type_class;
4765 else if (ArgTy->isComplexType())
4766 return complex_type_class;
4767 else if (ArgTy->isFunctionType())
4768 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004769 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004770 return record_type_class;
4771 else if (ArgTy->isUnionType())
4772 return union_type_class;
4773 else if (ArgTy->isArrayType())
4774 return array_type_class;
4775 else if (ArgTy->isUnionType())
4776 return union_type_class;
4777 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004778 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004779}
4780
Richard Smith5fab0c92011-12-28 19:48:30 +00004781/// EvaluateBuiltinConstantPForLValue - Determine the result of
4782/// __builtin_constant_p when applied to the given lvalue.
4783///
4784/// An lvalue is only "constant" if it is a pointer or reference to the first
4785/// character of a string literal.
4786template<typename LValue>
4787static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004788 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004789 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4790}
4791
4792/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4793/// GCC as we can manage.
4794static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4795 QualType ArgType = Arg->getType();
4796
4797 // __builtin_constant_p always has one operand. The rules which gcc follows
4798 // are not precisely documented, but are as follows:
4799 //
4800 // - If the operand is of integral, floating, complex or enumeration type,
4801 // and can be folded to a known value of that type, it returns 1.
4802 // - If the operand and can be folded to a pointer to the first character
4803 // of a string literal (or such a pointer cast to an integral type), it
4804 // returns 1.
4805 //
4806 // Otherwise, it returns 0.
4807 //
4808 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4809 // its support for this does not currently work.
4810 if (ArgType->isIntegralOrEnumerationType()) {
4811 Expr::EvalResult Result;
4812 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4813 return false;
4814
4815 APValue &V = Result.Val;
4816 if (V.getKind() == APValue::Int)
4817 return true;
4818
4819 return EvaluateBuiltinConstantPForLValue(V);
4820 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4821 return Arg->isEvaluatable(Ctx);
4822 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4823 LValue LV;
4824 Expr::EvalStatus Status;
4825 EvalInfo Info(Ctx, Status);
4826 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4827 : EvaluatePointer(Arg, LV, Info)) &&
4828 !Status.HasSideEffects)
4829 return EvaluateBuiltinConstantPForLValue(LV);
4830 }
4831
4832 // Anything else isn't considered to be sufficiently constant.
4833 return false;
4834}
4835
John McCall95007602010-05-10 23:27:23 +00004836/// Retrieves the "underlying object type" of the given expression,
4837/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004838QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4839 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4840 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004841 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004842 } else if (const Expr *E = B.get<const Expr*>()) {
4843 if (isa<CompoundLiteralExpr>(E))
4844 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004845 }
4846
4847 return QualType();
4848}
4849
Peter Collingbournee9200682011-05-13 03:29:01 +00004850bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004851 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004852
4853 {
4854 // The operand of __builtin_object_size is never evaluated for side-effects.
4855 // If there are any, but we can determine the pointed-to object anyway, then
4856 // ignore the side-effects.
4857 SpeculativeEvaluationRAII SpeculativeEval(Info);
4858 if (!EvaluatePointer(E->getArg(0), Base, Info))
4859 return false;
4860 }
John McCall95007602010-05-10 23:27:23 +00004861
4862 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004863 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004864
Richard Smithce40ad62011-11-12 22:28:03 +00004865 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004866 if (T.isNull() ||
4867 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004868 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004869 T->isVariablyModifiedType() ||
4870 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004871 return Error(E);
John McCall95007602010-05-10 23:27:23 +00004872
4873 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4874 CharUnits Offset = Base.getLValueOffset();
4875
4876 if (!Offset.isNegative() && Offset <= Size)
4877 Size -= Offset;
4878 else
4879 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00004880 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00004881}
4882
Peter Collingbournee9200682011-05-13 03:29:01 +00004883bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00004884 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004885 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00004886 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004887
4888 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00004889 if (TryEvaluateBuiltinObjectSize(E))
4890 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00004891
Richard Smith0421ce72012-08-07 04:16:51 +00004892 // If evaluating the argument has side-effects, we can't determine the size
4893 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4894 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004895 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00004896 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00004897 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00004898 return Success(0, E);
4899 }
Mike Stump876387b2009-10-27 22:09:17 +00004900
Richard Smith01ade172012-05-23 04:13:20 +00004901 // Expression had no side effects, but we couldn't statically determine the
4902 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004903 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004904 }
4905
Benjamin Kramera801f4a2012-10-06 14:42:22 +00004906 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00004907 case Builtin::BI__builtin_bswap32:
4908 case Builtin::BI__builtin_bswap64: {
4909 APSInt Val;
4910 if (!EvaluateInteger(E->getArg(0), Val, Info))
4911 return false;
4912
4913 return Success(Val.byteSwap(), E);
4914 }
4915
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004916 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004917 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00004918
Richard Smith5fab0c92011-12-28 19:48:30 +00004919 case Builtin::BI__builtin_constant_p:
4920 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00004921
Chris Lattnerd545ad12009-09-23 06:06:36 +00004922 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00004923 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00004924 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00004925 return Success(Operand, E);
4926 }
Eli Friedmand5c93992010-02-13 00:10:10 +00004927
4928 case Builtin::BI__builtin_expect:
4929 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00004930
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004931 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00004932 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004933 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00004934 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00004935 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4936 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00004937 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00004938 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004939 case Builtin::BI__builtin_strlen:
4940 // As an extension, we support strlen() and __builtin_strlen() as constant
4941 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00004942 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004943 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4944 // The string literal may have embedded null characters. Find the first
4945 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004946 StringRef Str = S->getString();
4947 StringRef::size_type Pos = Str.find(0);
4948 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004949 Str = Str.substr(0, Pos);
4950
4951 return Success(Str.size(), E);
4952 }
4953
Richard Smithf57d8cb2011-12-09 22:58:01 +00004954 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004955
Richard Smith01ba47d2012-04-13 00:45:38 +00004956 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00004957 case Builtin::BI__atomic_is_lock_free:
4958 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00004959 APSInt SizeVal;
4960 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4961 return false;
4962
4963 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4964 // of two less than the maximum inline atomic width, we know it is
4965 // lock-free. If the size isn't a power of two, or greater than the
4966 // maximum alignment where we promote atomics, we know it is not lock-free
4967 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4968 // the answer can only be determined at runtime; for example, 16-byte
4969 // atomics have lock-free implementations on some, but not all,
4970 // x86-64 processors.
4971
4972 // Check power-of-two.
4973 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00004974 if (Size.isPowerOfTwo()) {
4975 // Check against inlining width.
4976 unsigned InlineWidthBits =
4977 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4978 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4979 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4980 Size == CharUnits::One() ||
4981 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4982 Expr::NPC_NeverValueDependent))
4983 // OK, we will inline appropriately-aligned operations of this size,
4984 // and _Atomic(T) is appropriately-aligned.
4985 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004986
Richard Smith01ba47d2012-04-13 00:45:38 +00004987 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4988 castAs<PointerType>()->getPointeeType();
4989 if (!PointeeType->isIncompleteType() &&
4990 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4991 // OK, we will inline operations on this object.
4992 return Success(1, E);
4993 }
4994 }
4995 }
Eli Friedmana4c26022011-10-17 21:44:23 +00004996
Richard Smith01ba47d2012-04-13 00:45:38 +00004997 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4998 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004999 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005000 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005001}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005002
Richard Smith8b3497e2011-10-31 01:37:14 +00005003static bool HasSameBase(const LValue &A, const LValue &B) {
5004 if (!A.getLValueBase())
5005 return !B.getLValueBase();
5006 if (!B.getLValueBase())
5007 return false;
5008
Richard Smithce40ad62011-11-12 22:28:03 +00005009 if (A.getLValueBase().getOpaqueValue() !=
5010 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005011 const Decl *ADecl = GetLValueBaseDecl(A);
5012 if (!ADecl)
5013 return false;
5014 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005015 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005016 return false;
5017 }
5018
5019 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005020 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005021}
5022
Richard Smithc8042322012-02-01 05:53:12 +00005023/// Perform the given integer operation, which is known to need at most BitWidth
5024/// bits, and check for overflow in the original type (if that type was not an
5025/// unsigned type).
5026template<typename Operation>
5027static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
5028 const APSInt &LHS, const APSInt &RHS,
5029 unsigned BitWidth, Operation Op) {
5030 if (LHS.isUnsigned())
5031 return Op(LHS, RHS);
5032
5033 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
5034 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005035 if (Result.extend(BitWidth) != Value) {
5036 if (Info.getIntOverflowCheckMode())
5037 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
5038 diag::warn_integer_constant_overflow)
5039 << Result.toString(10) << E->getType();
5040 else
5041 HandleOverflow(Info, E, Value, E->getType());
5042 }
Richard Smithc8042322012-02-01 05:53:12 +00005043 return Result;
5044}
5045
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005046namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005047
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005048/// \brief Data recursive integer evaluator of certain binary operators.
5049///
5050/// We use a data recursive algorithm for binary operators so that we are able
5051/// to handle extreme cases of chained binary operators without causing stack
5052/// overflow.
5053class DataRecursiveIntBinOpEvaluator {
5054 struct EvalResult {
5055 APValue Val;
5056 bool Failed;
5057
5058 EvalResult() : Failed(false) { }
5059
5060 void swap(EvalResult &RHS) {
5061 Val.swap(RHS.Val);
5062 Failed = RHS.Failed;
5063 RHS.Failed = false;
5064 }
5065 };
5066
5067 struct Job {
5068 const Expr *E;
5069 EvalResult LHSResult; // meaningful only for binary operator expression.
5070 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5071
5072 Job() : StoredInfo(0) { }
5073 void startSpeculativeEval(EvalInfo &Info) {
5074 OldEvalStatus = Info.EvalStatus;
5075 Info.EvalStatus.Diag = 0;
5076 StoredInfo = &Info;
5077 }
5078 ~Job() {
5079 if (StoredInfo) {
5080 StoredInfo->EvalStatus = OldEvalStatus;
5081 }
5082 }
5083 private:
5084 EvalInfo *StoredInfo; // non-null if status changed.
5085 Expr::EvalStatus OldEvalStatus;
5086 };
5087
5088 SmallVector<Job, 16> Queue;
5089
5090 IntExprEvaluator &IntEval;
5091 EvalInfo &Info;
5092 APValue &FinalResult;
5093
5094public:
5095 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5096 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5097
5098 /// \brief True if \param E is a binary operator that we are going to handle
5099 /// data recursively.
5100 /// We handle binary operators that are comma, logical, or that have operands
5101 /// with integral or enumeration type.
5102 static bool shouldEnqueue(const BinaryOperator *E) {
5103 return E->getOpcode() == BO_Comma ||
5104 E->isLogicalOp() ||
5105 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5106 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005107 }
5108
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005109 bool Traverse(const BinaryOperator *E) {
5110 enqueue(E);
5111 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005112 while (!Queue.empty())
5113 process(PrevResult);
5114
5115 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005116
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005117 FinalResult.swap(PrevResult.Val);
5118 return true;
5119 }
5120
5121private:
5122 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5123 return IntEval.Success(Value, E, Result);
5124 }
5125 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5126 return IntEval.Success(Value, E, Result);
5127 }
5128 bool Error(const Expr *E) {
5129 return IntEval.Error(E);
5130 }
5131 bool Error(const Expr *E, diag::kind D) {
5132 return IntEval.Error(E, D);
5133 }
5134
5135 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5136 return Info.CCEDiag(E, D);
5137 }
5138
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005139 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5140 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005141 bool &SuppressRHSDiags);
5142
5143 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5144 const BinaryOperator *E, APValue &Result);
5145
5146 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5147 Result.Failed = !Evaluate(Result.Val, Info, E);
5148 if (Result.Failed)
5149 Result.Val = APValue();
5150 }
5151
Richard Trieuba4d0872012-03-21 23:30:30 +00005152 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005153
5154 void enqueue(const Expr *E) {
5155 E = E->IgnoreParens();
5156 Queue.resize(Queue.size()+1);
5157 Queue.back().E = E;
5158 Queue.back().Kind = Job::AnyExprKind;
5159 }
5160};
5161
5162}
5163
5164bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005165 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005166 bool &SuppressRHSDiags) {
5167 if (E->getOpcode() == BO_Comma) {
5168 // Ignore LHS but note if we could not evaluate it.
5169 if (LHSResult.Failed)
5170 Info.EvalStatus.HasSideEffects = true;
5171 return true;
5172 }
5173
5174 if (E->isLogicalOp()) {
5175 bool lhsResult;
5176 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005177 // We were able to evaluate the LHS, see if we can get away with not
5178 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005179 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005180 Success(lhsResult, E, LHSResult.Val);
5181 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005182 }
5183 } else {
5184 // Since we weren't able to evaluate the left hand side, it
5185 // must have had side effects.
5186 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005187
5188 // We can't evaluate the LHS; however, sometimes the result
5189 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5190 // Don't ignore RHS and suppress diagnostics from this arm.
5191 SuppressRHSDiags = true;
5192 }
5193
5194 return true;
5195 }
5196
5197 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5198 E->getRHS()->getType()->isIntegralOrEnumerationType());
5199
5200 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005201 return false; // Ignore RHS;
5202
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005203 return true;
5204}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005205
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005206bool DataRecursiveIntBinOpEvaluator::
5207 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5208 const BinaryOperator *E, APValue &Result) {
5209 if (E->getOpcode() == BO_Comma) {
5210 if (RHSResult.Failed)
5211 return false;
5212 Result = RHSResult.Val;
5213 return true;
5214 }
5215
5216 if (E->isLogicalOp()) {
5217 bool lhsResult, rhsResult;
5218 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5219 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5220
5221 if (LHSIsOK) {
5222 if (RHSIsOK) {
5223 if (E->getOpcode() == BO_LOr)
5224 return Success(lhsResult || rhsResult, E, Result);
5225 else
5226 return Success(lhsResult && rhsResult, E, Result);
5227 }
5228 } else {
5229 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005230 // We can't evaluate the LHS; however, sometimes the result
5231 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5232 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005233 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005234 }
5235 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005236
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005237 return false;
5238 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005239
5240 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5241 E->getRHS()->getType()->isIntegralOrEnumerationType());
5242
5243 if (LHSResult.Failed || RHSResult.Failed)
5244 return false;
5245
5246 const APValue &LHSVal = LHSResult.Val;
5247 const APValue &RHSVal = RHSResult.Val;
5248
5249 // Handle cases like (unsigned long)&a + 4.
5250 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5251 Result = LHSVal;
5252 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5253 RHSVal.getInt().getZExtValue());
5254 if (E->getOpcode() == BO_Add)
5255 Result.getLValueOffset() += AdditionalOffset;
5256 else
5257 Result.getLValueOffset() -= AdditionalOffset;
5258 return true;
5259 }
5260
5261 // Handle cases like 4 + (unsigned long)&a
5262 if (E->getOpcode() == BO_Add &&
5263 RHSVal.isLValue() && LHSVal.isInt()) {
5264 Result = RHSVal;
5265 Result.getLValueOffset() += CharUnits::fromQuantity(
5266 LHSVal.getInt().getZExtValue());
5267 return true;
5268 }
5269
5270 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5271 // Handle (intptr_t)&&A - (intptr_t)&&B.
5272 if (!LHSVal.getLValueOffset().isZero() ||
5273 !RHSVal.getLValueOffset().isZero())
5274 return false;
5275 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5276 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5277 if (!LHSExpr || !RHSExpr)
5278 return false;
5279 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5280 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5281 if (!LHSAddrExpr || !RHSAddrExpr)
5282 return false;
5283 // Make sure both labels come from the same function.
5284 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5285 RHSAddrExpr->getLabel()->getDeclContext())
5286 return false;
5287 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5288 return true;
5289 }
5290
5291 // All the following cases expect both operands to be an integer
5292 if (!LHSVal.isInt() || !RHSVal.isInt())
5293 return Error(E);
5294
5295 const APSInt &LHS = LHSVal.getInt();
5296 APSInt RHS = RHSVal.getInt();
5297
5298 switch (E->getOpcode()) {
5299 default:
5300 return Error(E);
5301 case BO_Mul:
5302 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5303 LHS.getBitWidth() * 2,
5304 std::multiplies<APSInt>()), E,
5305 Result);
5306 case BO_Add:
5307 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5308 LHS.getBitWidth() + 1,
5309 std::plus<APSInt>()), E, Result);
5310 case BO_Sub:
5311 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5312 LHS.getBitWidth() + 1,
5313 std::minus<APSInt>()), E, Result);
5314 case BO_And: return Success(LHS & RHS, E, Result);
5315 case BO_Xor: return Success(LHS ^ RHS, E, Result);
5316 case BO_Or: return Success(LHS | RHS, E, Result);
5317 case BO_Div:
5318 case BO_Rem:
5319 if (RHS == 0)
5320 return Error(E, diag::note_expr_divide_by_zero);
5321 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
5322 // not actually undefined behavior in C++11 due to a language defect.
5323 if (RHS.isNegative() && RHS.isAllOnesValue() &&
5324 LHS.isSigned() && LHS.isMinSignedValue())
5325 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
5326 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
5327 Result);
5328 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00005329 if (Info.getLangOpts().OpenCL)
5330 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005331 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005332 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5333 RHS.isUnsigned());
5334 else if (RHS.isSigned() && RHS.isNegative()) {
5335 // During constant-folding, a negative shift is an opposite shift. Such
5336 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005337 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5338 RHS = -RHS;
5339 goto shift_right;
5340 }
5341
5342 shift_left:
5343 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
5344 // the shifted type.
5345 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5346 if (SA != RHS) {
5347 CCEDiag(E, diag::note_constexpr_large_shift)
5348 << RHS << E->getType() << LHS.getBitWidth();
5349 } else if (LHS.isSigned()) {
5350 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
5351 // operand, and must not overflow the corresponding unsigned type.
5352 if (LHS.isNegative())
5353 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
5354 else if (LHS.countLeadingZeros() < SA)
5355 CCEDiag(E, diag::note_constexpr_lshift_discards);
5356 }
5357
5358 return Success(LHS << SA, E, Result);
5359 }
5360 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00005361 if (Info.getLangOpts().OpenCL)
5362 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005363 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005364 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5365 RHS.isUnsigned());
5366 else if (RHS.isSigned() && RHS.isNegative()) {
5367 // During constant-folding, a negative shift is an opposite shift. Such a
5368 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005369 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5370 RHS = -RHS;
5371 goto shift_left;
5372 }
5373
5374 shift_right:
5375 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
5376 // shifted type.
5377 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5378 if (SA != RHS)
5379 CCEDiag(E, diag::note_constexpr_large_shift)
5380 << RHS << E->getType() << LHS.getBitWidth();
5381
5382 return Success(LHS >> SA, E, Result);
5383 }
5384
5385 case BO_LT: return Success(LHS < RHS, E, Result);
5386 case BO_GT: return Success(LHS > RHS, E, Result);
5387 case BO_LE: return Success(LHS <= RHS, E, Result);
5388 case BO_GE: return Success(LHS >= RHS, E, Result);
5389 case BO_EQ: return Success(LHS == RHS, E, Result);
5390 case BO_NE: return Success(LHS != RHS, E, Result);
5391 }
5392}
5393
Richard Trieuba4d0872012-03-21 23:30:30 +00005394void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005395 Job &job = Queue.back();
5396
5397 switch (job.Kind) {
5398 case Job::AnyExprKind: {
5399 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5400 if (shouldEnqueue(Bop)) {
5401 job.Kind = Job::BinOpKind;
5402 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005403 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005404 }
5405 }
5406
5407 EvaluateExpr(job.E, Result);
5408 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005409 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005410 }
5411
5412 case Job::BinOpKind: {
5413 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005414 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005415 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005416 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005417 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005418 }
5419 if (SuppressRHSDiags)
5420 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005421 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005422 job.Kind = Job::BinOpVisitedLHSKind;
5423 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005424 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005425 }
5426
5427 case Job::BinOpVisitedLHSKind: {
5428 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5429 EvalResult RHS;
5430 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005431 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005432 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005433 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005434 }
5435 }
5436
5437 llvm_unreachable("Invalid Job::Kind!");
5438}
5439
5440bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5441 if (E->isAssignmentOp())
5442 return Error(E);
5443
5444 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5445 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005446
Anders Carlssonacc79812008-11-16 07:17:21 +00005447 QualType LHSTy = E->getLHS()->getType();
5448 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005449
5450 if (LHSTy->isAnyComplexType()) {
5451 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005452 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005453
Richard Smith253c2a32012-01-27 01:14:48 +00005454 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5455 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005456 return false;
5457
Richard Smith253c2a32012-01-27 01:14:48 +00005458 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005459 return false;
5460
5461 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005462 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005463 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005464 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005465 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5466
John McCalle3027922010-08-25 11:45:40 +00005467 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005468 return Success((CR_r == APFloat::cmpEqual &&
5469 CR_i == APFloat::cmpEqual), E);
5470 else {
John McCalle3027922010-08-25 11:45:40 +00005471 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005472 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005473 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005474 CR_r == APFloat::cmpLessThan ||
5475 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005476 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005477 CR_i == APFloat::cmpLessThan ||
5478 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005479 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005480 } else {
John McCalle3027922010-08-25 11:45:40 +00005481 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005482 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5483 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5484 else {
John McCalle3027922010-08-25 11:45:40 +00005485 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005486 "Invalid compex comparison.");
5487 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5488 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5489 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005490 }
5491 }
Mike Stump11289f42009-09-09 15:08:12 +00005492
Anders Carlssonacc79812008-11-16 07:17:21 +00005493 if (LHSTy->isRealFloatingType() &&
5494 RHSTy->isRealFloatingType()) {
5495 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005496
Richard Smith253c2a32012-01-27 01:14:48 +00005497 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5498 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005499 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005500
Richard Smith253c2a32012-01-27 01:14:48 +00005501 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005502 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005503
Anders Carlssonacc79812008-11-16 07:17:21 +00005504 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005505
Anders Carlssonacc79812008-11-16 07:17:21 +00005506 switch (E->getOpcode()) {
5507 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005508 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005509 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005510 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005511 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005512 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005513 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005514 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005515 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005516 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005517 E);
John McCalle3027922010-08-25 11:45:40 +00005518 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005519 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005520 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005521 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005522 || CR == APFloat::cmpLessThan
5523 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005524 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005525 }
Mike Stump11289f42009-09-09 15:08:12 +00005526
Eli Friedmana38da572009-04-28 19:17:36 +00005527 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005528 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005529 LValue LHSValue, RHSValue;
5530
5531 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5532 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005533 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005534
Richard Smith253c2a32012-01-27 01:14:48 +00005535 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005536 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005537
Richard Smith8b3497e2011-10-31 01:37:14 +00005538 // Reject differing bases from the normal codepath; we special-case
5539 // comparisons to null.
5540 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005541 if (E->getOpcode() == BO_Sub) {
5542 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005543 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5544 return false;
5545 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005546 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005547 if (!LHSExpr || !RHSExpr)
5548 return false;
5549 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5550 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5551 if (!LHSAddrExpr || !RHSAddrExpr)
5552 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005553 // Make sure both labels come from the same function.
5554 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5555 RHSAddrExpr->getLabel()->getDeclContext())
5556 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005557 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005558 return true;
5559 }
Richard Smith83c68212011-10-31 05:11:32 +00005560 // Inequalities and subtractions between unrelated pointers have
5561 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005562 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005563 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005564 // A constant address may compare equal to the address of a symbol.
5565 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005566 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005567 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5568 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005569 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005570 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005571 // distinct addresses. In clang, the result of such a comparison is
5572 // unspecified, so it is not a constant expression. However, we do know
5573 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005574 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5575 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005576 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005577 // We can't tell whether weak symbols will end up pointing to the same
5578 // object.
5579 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005580 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005581 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005582 // (Note that clang defaults to -fmerge-all-constants, which can
5583 // lead to inconsistent results for comparisons involving the address
5584 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005585 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005586 }
Eli Friedman64004332009-03-23 04:38:34 +00005587
Richard Smith1b470412012-02-01 08:10:20 +00005588 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5589 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5590
Richard Smith84f6dcf2012-02-02 01:16:57 +00005591 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5592 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5593
John McCalle3027922010-08-25 11:45:40 +00005594 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005595 // C++11 [expr.add]p6:
5596 // Unless both pointers point to elements of the same array object, or
5597 // one past the last element of the array object, the behavior is
5598 // undefined.
5599 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5600 !AreElementsOfSameArray(getType(LHSValue.Base),
5601 LHSDesignator, RHSDesignator))
5602 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5603
Chris Lattner882bdf22010-04-20 17:13:14 +00005604 QualType Type = E->getLHS()->getType();
5605 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005606
Richard Smithd62306a2011-11-10 06:34:14 +00005607 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005608 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005609 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005610
Richard Smith1b470412012-02-01 08:10:20 +00005611 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5612 // and produce incorrect results when it overflows. Such behavior
5613 // appears to be non-conforming, but is common, so perhaps we should
5614 // assume the standard intended for such cases to be undefined behavior
5615 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005616
Richard Smith1b470412012-02-01 08:10:20 +00005617 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5618 // overflow in the final conversion to ptrdiff_t.
5619 APSInt LHS(
5620 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5621 APSInt RHS(
5622 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5623 APSInt ElemSize(
5624 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5625 APSInt TrueResult = (LHS - RHS) / ElemSize;
5626 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5627
5628 if (Result.extend(65) != TrueResult)
5629 HandleOverflow(Info, E, TrueResult, E->getType());
5630 return Success(Result, E);
5631 }
Richard Smithde21b242012-01-31 06:41:30 +00005632
5633 // C++11 [expr.rel]p3:
5634 // Pointers to void (after pointer conversions) can be compared, with a
5635 // result defined as follows: If both pointers represent the same
5636 // address or are both the null pointer value, the result is true if the
5637 // operator is <= or >= and false otherwise; otherwise the result is
5638 // unspecified.
5639 // We interpret this as applying to pointers to *cv* void.
5640 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005641 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005642 CCEDiag(E, diag::note_constexpr_void_comparison);
5643
Richard Smith84f6dcf2012-02-02 01:16:57 +00005644 // C++11 [expr.rel]p2:
5645 // - If two pointers point to non-static data members of the same object,
5646 // or to subobjects or array elements fo such members, recursively, the
5647 // pointer to the later declared member compares greater provided the
5648 // two members have the same access control and provided their class is
5649 // not a union.
5650 // [...]
5651 // - Otherwise pointer comparisons are unspecified.
5652 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5653 E->isRelationalOp()) {
5654 bool WasArrayIndex;
5655 unsigned Mismatch =
5656 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5657 RHSDesignator, WasArrayIndex);
5658 // At the point where the designators diverge, the comparison has a
5659 // specified value if:
5660 // - we are comparing array indices
5661 // - we are comparing fields of a union, or fields with the same access
5662 // Otherwise, the result is unspecified and thus the comparison is not a
5663 // constant expression.
5664 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5665 Mismatch < RHSDesignator.Entries.size()) {
5666 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5667 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5668 if (!LF && !RF)
5669 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5670 else if (!LF)
5671 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5672 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5673 << RF->getParent() << RF;
5674 else if (!RF)
5675 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5676 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5677 << LF->getParent() << LF;
5678 else if (!LF->getParent()->isUnion() &&
5679 LF->getAccess() != RF->getAccess())
5680 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5681 << LF << LF->getAccess() << RF << RF->getAccess()
5682 << LF->getParent();
5683 }
5684 }
5685
Eli Friedman6c31cb42012-04-16 04:30:08 +00005686 // The comparison here must be unsigned, and performed with the same
5687 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005688 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5689 uint64_t CompareLHS = LHSOffset.getQuantity();
5690 uint64_t CompareRHS = RHSOffset.getQuantity();
5691 assert(PtrSize <= 64 && "Unexpected pointer width");
5692 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5693 CompareLHS &= Mask;
5694 CompareRHS &= Mask;
5695
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005696 // If there is a base and this is a relational operator, we can only
5697 // compare pointers within the object in question; otherwise, the result
5698 // depends on where the object is located in memory.
5699 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5700 QualType BaseTy = getType(LHSValue.Base);
5701 if (BaseTy->isIncompleteType())
5702 return Error(E);
5703 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5704 uint64_t OffsetLimit = Size.getQuantity();
5705 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5706 return Error(E);
5707 }
5708
Richard Smith8b3497e2011-10-31 01:37:14 +00005709 switch (E->getOpcode()) {
5710 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005711 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5712 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5713 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5714 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5715 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5716 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005717 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005718 }
5719 }
Richard Smith7bb00672012-02-01 01:42:44 +00005720
5721 if (LHSTy->isMemberPointerType()) {
5722 assert(E->isEqualityOp() && "unexpected member pointer operation");
5723 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5724
5725 MemberPtr LHSValue, RHSValue;
5726
5727 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5728 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5729 return false;
5730
5731 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5732 return false;
5733
5734 // C++11 [expr.eq]p2:
5735 // If both operands are null, they compare equal. Otherwise if only one is
5736 // null, they compare unequal.
5737 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5738 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5739 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5740 }
5741
5742 // Otherwise if either is a pointer to a virtual member function, the
5743 // result is unspecified.
5744 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5745 if (MD->isVirtual())
5746 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5747 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5748 if (MD->isVirtual())
5749 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5750
5751 // Otherwise they compare equal if and only if they would refer to the
5752 // same member of the same most derived object or the same subobject if
5753 // they were dereferenced with a hypothetical object of the associated
5754 // class type.
5755 bool Equal = LHSValue == RHSValue;
5756 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5757 }
5758
Richard Smithab44d9b2012-02-14 22:35:28 +00005759 if (LHSTy->isNullPtrType()) {
5760 assert(E->isComparisonOp() && "unexpected nullptr operation");
5761 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5762 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5763 // are compared, the result is true of the operator is <=, >= or ==, and
5764 // false otherwise.
5765 BinaryOperator::Opcode Opcode = E->getOpcode();
5766 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5767 }
5768
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005769 assert((!LHSTy->isIntegralOrEnumerationType() ||
5770 !RHSTy->isIntegralOrEnumerationType()) &&
5771 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5772 // We can't continue from here for non-integral types.
5773 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005774}
5775
Ken Dyck160146e2010-01-27 17:10:57 +00005776CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005777 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5778 // result shall be the alignment of the referenced type."
5779 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5780 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005781
5782 // __alignof is defined to return the preferred alignment.
5783 return Info.Ctx.toCharUnitsFromBits(
5784 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005785}
5786
Ken Dyck160146e2010-01-27 17:10:57 +00005787CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005788 E = E->IgnoreParens();
5789
5790 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005791 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005792 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005793 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5794 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005795
Chris Lattner68061312009-01-24 21:53:27 +00005796 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005797 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5798 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005799
Chris Lattner24aeeab2009-01-24 21:09:06 +00005800 return GetAlignOfType(E->getType());
5801}
5802
5803
Peter Collingbournee190dee2011-03-11 19:24:49 +00005804/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5805/// a result as the expression's type.
5806bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5807 const UnaryExprOrTypeTraitExpr *E) {
5808 switch(E->getKind()) {
5809 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005810 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005811 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005812 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005813 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005814 }
Eli Friedman64004332009-03-23 04:38:34 +00005815
Peter Collingbournee190dee2011-03-11 19:24:49 +00005816 case UETT_VecStep: {
5817 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005818
Peter Collingbournee190dee2011-03-11 19:24:49 +00005819 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005820 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005821
Peter Collingbournee190dee2011-03-11 19:24:49 +00005822 // The vec_step built-in functions that take a 3-component
5823 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5824 if (n == 3)
5825 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005826
Peter Collingbournee190dee2011-03-11 19:24:49 +00005827 return Success(n, E);
5828 } else
5829 return Success(1, E);
5830 }
5831
5832 case UETT_SizeOf: {
5833 QualType SrcTy = E->getTypeOfArgument();
5834 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5835 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005836 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5837 SrcTy = Ref->getPointeeType();
5838
Richard Smithd62306a2011-11-10 06:34:14 +00005839 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005840 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005841 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005842 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005843 }
5844 }
5845
5846 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005847}
5848
Peter Collingbournee9200682011-05-13 03:29:01 +00005849bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005850 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005851 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005852 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005853 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005854 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005855 for (unsigned i = 0; i != n; ++i) {
5856 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5857 switch (ON.getKind()) {
5858 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005859 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005860 APSInt IdxResult;
5861 if (!EvaluateInteger(Idx, IdxResult, Info))
5862 return false;
5863 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5864 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005865 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005866 CurrentType = AT->getElementType();
5867 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5868 Result += IdxResult.getSExtValue() * ElementSize;
5869 break;
5870 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005871
Douglas Gregor882211c2010-04-28 22:16:22 +00005872 case OffsetOfExpr::OffsetOfNode::Field: {
5873 FieldDecl *MemberDecl = ON.getField();
5874 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005875 if (!RT)
5876 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005877 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005878 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00005879 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00005880 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00005881 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00005882 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00005883 CurrentType = MemberDecl->getType().getNonReferenceType();
5884 break;
5885 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005886
Douglas Gregor882211c2010-04-28 22:16:22 +00005887 case OffsetOfExpr::OffsetOfNode::Identifier:
5888 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005889
Douglas Gregord1702062010-04-29 00:18:15 +00005890 case OffsetOfExpr::OffsetOfNode::Base: {
5891 CXXBaseSpecifier *BaseSpec = ON.getBase();
5892 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005893 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005894
5895 // Find the layout of the class whose base we are looking into.
5896 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005897 if (!RT)
5898 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005899 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005900 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00005901 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5902
5903 // Find the base class itself.
5904 CurrentType = BaseSpec->getType();
5905 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5906 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005907 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005908
5909 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00005910 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00005911 break;
5912 }
Douglas Gregor882211c2010-04-28 22:16:22 +00005913 }
5914 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005915 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005916}
5917
Chris Lattnere13042c2008-07-11 19:10:17 +00005918bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005919 switch (E->getOpcode()) {
5920 default:
5921 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5922 // See C99 6.6p3.
5923 return Error(E);
5924 case UO_Extension:
5925 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5926 // If so, we could clear the diagnostic ID.
5927 return Visit(E->getSubExpr());
5928 case UO_Plus:
5929 // The result is just the value.
5930 return Visit(E->getSubExpr());
5931 case UO_Minus: {
5932 if (!Visit(E->getSubExpr()))
5933 return false;
5934 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00005935 const APSInt &Value = Result.getInt();
5936 if (Value.isSigned() && Value.isMinSignedValue())
5937 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5938 E->getType());
5939 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005940 }
5941 case UO_Not: {
5942 if (!Visit(E->getSubExpr()))
5943 return false;
5944 if (!Result.isInt()) return Error(E);
5945 return Success(~Result.getInt(), E);
5946 }
5947 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00005948 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00005949 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00005950 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005951 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005952 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005953 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005954}
Mike Stump11289f42009-09-09 15:08:12 +00005955
Chris Lattner477c4be2008-07-12 01:15:53 +00005956/// HandleCast - This is used to evaluate implicit or explicit casts where the
5957/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00005958bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5959 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005960 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00005961 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005962
Eli Friedmanc757de22011-03-25 00:43:55 +00005963 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00005964 case CK_BaseToDerived:
5965 case CK_DerivedToBase:
5966 case CK_UncheckedDerivedToBase:
5967 case CK_Dynamic:
5968 case CK_ToUnion:
5969 case CK_ArrayToPointerDecay:
5970 case CK_FunctionToPointerDecay:
5971 case CK_NullToPointer:
5972 case CK_NullToMemberPointer:
5973 case CK_BaseToDerivedMemberPointer:
5974 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00005975 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00005976 case CK_ConstructorConversion:
5977 case CK_IntegralToPointer:
5978 case CK_ToVoid:
5979 case CK_VectorSplat:
5980 case CK_IntegralToFloating:
5981 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005982 case CK_CPointerToObjCPointerCast:
5983 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005984 case CK_AnyPointerToBlockPointerCast:
5985 case CK_ObjCObjectLValueCast:
5986 case CK_FloatingRealToComplex:
5987 case CK_FloatingComplexToReal:
5988 case CK_FloatingComplexCast:
5989 case CK_FloatingComplexToIntegralComplex:
5990 case CK_IntegralRealToComplex:
5991 case CK_IntegralComplexCast:
5992 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00005993 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005994 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005995 llvm_unreachable("invalid cast kind for integral value");
5996
Eli Friedman9faf2f92011-03-25 19:07:11 +00005997 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005998 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005999 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006000 case CK_ARCProduceObject:
6001 case CK_ARCConsumeObject:
6002 case CK_ARCReclaimReturnedObject:
6003 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006004 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006005 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006006
Richard Smith4ef685b2012-01-17 21:17:26 +00006007 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006008 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006009 case CK_AtomicToNonAtomic:
6010 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006011 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006012 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006013
6014 case CK_MemberPointerToBoolean:
6015 case CK_PointerToBoolean:
6016 case CK_IntegralToBoolean:
6017 case CK_FloatingToBoolean:
6018 case CK_FloatingComplexToBoolean:
6019 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006020 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006021 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006022 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006023 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006024 }
6025
Eli Friedmanc757de22011-03-25 00:43:55 +00006026 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006027 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006028 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006029
Eli Friedman742421e2009-02-20 01:15:07 +00006030 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006031 // Allow casts of address-of-label differences if they are no-ops
6032 // or narrowing. (The narrowing case isn't actually guaranteed to
6033 // be constant-evaluatable except in some narrow cases which are hard
6034 // to detect here. We let it through on the assumption the user knows
6035 // what they are doing.)
6036 if (Result.isAddrLabelDiff())
6037 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006038 // Only allow casts of lvalues if they are lossless.
6039 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6040 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006041
Richard Smith911e1422012-01-30 22:27:01 +00006042 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6043 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006044 }
Mike Stump11289f42009-09-09 15:08:12 +00006045
Eli Friedmanc757de22011-03-25 00:43:55 +00006046 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006047 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6048
John McCall45d55e42010-05-07 21:00:08 +00006049 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006050 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006051 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006052
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006053 if (LV.getLValueBase()) {
6054 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006055 // FIXME: Allow a larger integer size than the pointer size, and allow
6056 // narrowing back down to pointer width in subsequent integral casts.
6057 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006058 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006059 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006060
Richard Smithcf74da72011-11-16 07:18:12 +00006061 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006062 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006063 return true;
6064 }
6065
Ken Dyck02990832010-01-15 12:37:54 +00006066 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6067 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006068 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006069 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006070
Eli Friedmanc757de22011-03-25 00:43:55 +00006071 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006072 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006073 if (!EvaluateComplex(SubExpr, C, Info))
6074 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006075 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006076 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006077
Eli Friedmanc757de22011-03-25 00:43:55 +00006078 case CK_FloatingToIntegral: {
6079 APFloat F(0.0);
6080 if (!EvaluateFloat(SubExpr, F, Info))
6081 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006082
Richard Smith357362d2011-12-13 06:39:58 +00006083 APSInt Value;
6084 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6085 return false;
6086 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006087 }
6088 }
Mike Stump11289f42009-09-09 15:08:12 +00006089
Eli Friedmanc757de22011-03-25 00:43:55 +00006090 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006091}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006092
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006093bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6094 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006095 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006096 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6097 return false;
6098 if (!LV.isComplexInt())
6099 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006100 return Success(LV.getComplexIntReal(), E);
6101 }
6102
6103 return Visit(E->getSubExpr());
6104}
6105
Eli Friedman4e7a2412009-02-27 04:45:43 +00006106bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006107 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006108 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006109 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6110 return false;
6111 if (!LV.isComplexInt())
6112 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006113 return Success(LV.getComplexIntImag(), E);
6114 }
6115
Richard Smith4a678122011-10-24 18:44:57 +00006116 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006117 return Success(0, E);
6118}
6119
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006120bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6121 return Success(E->getPackLength(), E);
6122}
6123
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006124bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6125 return Success(E->getValue(), E);
6126}
6127
Chris Lattner05706e882008-07-11 18:11:29 +00006128//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006129// Float Evaluation
6130//===----------------------------------------------------------------------===//
6131
6132namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006133class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006134 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006135 APFloat &Result;
6136public:
6137 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006138 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006139
Richard Smith2e312c82012-03-03 22:46:17 +00006140 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006141 Result = V.getFloat();
6142 return true;
6143 }
Eli Friedman24c01542008-08-22 00:06:13 +00006144
Richard Smithfddd3842011-12-30 21:15:51 +00006145 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006146 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6147 return true;
6148 }
6149
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006150 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006151
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006152 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006153 bool VisitBinaryOperator(const BinaryOperator *E);
6154 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006155 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006156
John McCallb1fb0d32010-05-07 22:08:54 +00006157 bool VisitUnaryReal(const UnaryOperator *E);
6158 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006159
Richard Smithfddd3842011-12-30 21:15:51 +00006160 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006161};
6162} // end anonymous namespace
6163
6164static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006165 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006166 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006167}
6168
Jay Foad39c79802011-01-12 09:06:06 +00006169static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006170 QualType ResultTy,
6171 const Expr *Arg,
6172 bool SNaN,
6173 llvm::APFloat &Result) {
6174 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6175 if (!S) return false;
6176
6177 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6178
6179 llvm::APInt fill;
6180
6181 // Treat empty strings as if they were zero.
6182 if (S->getString().empty())
6183 fill = llvm::APInt(32, 0);
6184 else if (S->getString().getAsInteger(0, fill))
6185 return false;
6186
6187 if (SNaN)
6188 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6189 else
6190 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6191 return true;
6192}
6193
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006194bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006195 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006196 default:
6197 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6198
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006199 case Builtin::BI__builtin_huge_val:
6200 case Builtin::BI__builtin_huge_valf:
6201 case Builtin::BI__builtin_huge_vall:
6202 case Builtin::BI__builtin_inf:
6203 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006204 case Builtin::BI__builtin_infl: {
6205 const llvm::fltSemantics &Sem =
6206 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006207 Result = llvm::APFloat::getInf(Sem);
6208 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006209 }
Mike Stump11289f42009-09-09 15:08:12 +00006210
John McCall16291492010-02-28 13:00:19 +00006211 case Builtin::BI__builtin_nans:
6212 case Builtin::BI__builtin_nansf:
6213 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006214 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6215 true, Result))
6216 return Error(E);
6217 return true;
John McCall16291492010-02-28 13:00:19 +00006218
Chris Lattner0b7282e2008-10-06 06:31:58 +00006219 case Builtin::BI__builtin_nan:
6220 case Builtin::BI__builtin_nanf:
6221 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006222 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006223 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006224 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6225 false, Result))
6226 return Error(E);
6227 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006228
6229 case Builtin::BI__builtin_fabs:
6230 case Builtin::BI__builtin_fabsf:
6231 case Builtin::BI__builtin_fabsl:
6232 if (!EvaluateFloat(E->getArg(0), Result, Info))
6233 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006234
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006235 if (Result.isNegative())
6236 Result.changeSign();
6237 return true;
6238
Mike Stump11289f42009-09-09 15:08:12 +00006239 case Builtin::BI__builtin_copysign:
6240 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006241 case Builtin::BI__builtin_copysignl: {
6242 APFloat RHS(0.);
6243 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6244 !EvaluateFloat(E->getArg(1), RHS, Info))
6245 return false;
6246 Result.copySign(RHS);
6247 return true;
6248 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006249 }
6250}
6251
John McCallb1fb0d32010-05-07 22:08:54 +00006252bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006253 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6254 ComplexValue CV;
6255 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6256 return false;
6257 Result = CV.FloatReal;
6258 return true;
6259 }
6260
6261 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006262}
6263
6264bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006265 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6266 ComplexValue CV;
6267 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6268 return false;
6269 Result = CV.FloatImag;
6270 return true;
6271 }
6272
Richard Smith4a678122011-10-24 18:44:57 +00006273 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006274 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6275 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006276 return true;
6277}
6278
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006279bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006280 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006281 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006282 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006283 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006284 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006285 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6286 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006287 Result.changeSign();
6288 return true;
6289 }
6290}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006291
Eli Friedman24c01542008-08-22 00:06:13 +00006292bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006293 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6294 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006295
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006296 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006297 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6298 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006299 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006300 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00006301 return false;
6302
6303 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006304 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006305 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00006306 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006307 break;
John McCalle3027922010-08-25 11:45:40 +00006308 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00006309 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006310 break;
John McCalle3027922010-08-25 11:45:40 +00006311 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00006312 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006313 break;
John McCalle3027922010-08-25 11:45:40 +00006314 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00006315 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006316 break;
Eli Friedman24c01542008-08-22 00:06:13 +00006317 }
Richard Smithc8042322012-02-01 05:53:12 +00006318
6319 if (Result.isInfinity() || Result.isNaN())
6320 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
6321 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00006322}
6323
6324bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6325 Result = E->getValue();
6326 return true;
6327}
6328
Peter Collingbournee9200682011-05-13 03:29:01 +00006329bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6330 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006331
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006332 switch (E->getCastKind()) {
6333 default:
Richard Smith11562c52011-10-28 17:51:58 +00006334 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006335
6336 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006337 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006338 return EvaluateInteger(SubExpr, IntResult, Info) &&
6339 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6340 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006341 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006342
6343 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006344 if (!Visit(SubExpr))
6345 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006346 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6347 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006348 }
John McCalld7646252010-11-14 08:17:51 +00006349
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006350 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006351 ComplexValue V;
6352 if (!EvaluateComplex(SubExpr, V, Info))
6353 return false;
6354 Result = V.getComplexFloatReal();
6355 return true;
6356 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006357 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006358}
6359
Eli Friedman24c01542008-08-22 00:06:13 +00006360//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006361// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006362//===----------------------------------------------------------------------===//
6363
6364namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006365class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006366 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006367 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006368
Anders Carlsson537969c2008-11-16 20:27:53 +00006369public:
John McCall93d91dc2010-05-07 17:22:02 +00006370 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006371 : ExprEvaluatorBaseTy(info), Result(Result) {}
6372
Richard Smith2e312c82012-03-03 22:46:17 +00006373 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006374 Result.setFrom(V);
6375 return true;
6376 }
Mike Stump11289f42009-09-09 15:08:12 +00006377
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006378 bool ZeroInitialization(const Expr *E);
6379
Anders Carlsson537969c2008-11-16 20:27:53 +00006380 //===--------------------------------------------------------------------===//
6381 // Visitor Methods
6382 //===--------------------------------------------------------------------===//
6383
Peter Collingbournee9200682011-05-13 03:29:01 +00006384 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006385 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006386 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006387 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006388 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006389};
6390} // end anonymous namespace
6391
John McCall93d91dc2010-05-07 17:22:02 +00006392static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6393 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006394 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006395 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006396}
6397
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006398bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006399 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006400 if (ElemTy->isRealFloatingType()) {
6401 Result.makeComplexFloat();
6402 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6403 Result.FloatReal = Zero;
6404 Result.FloatImag = Zero;
6405 } else {
6406 Result.makeComplexInt();
6407 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6408 Result.IntReal = Zero;
6409 Result.IntImag = Zero;
6410 }
6411 return true;
6412}
6413
Peter Collingbournee9200682011-05-13 03:29:01 +00006414bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6415 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006416
6417 if (SubExpr->getType()->isRealFloatingType()) {
6418 Result.makeComplexFloat();
6419 APFloat &Imag = Result.FloatImag;
6420 if (!EvaluateFloat(SubExpr, Imag, Info))
6421 return false;
6422
6423 Result.FloatReal = APFloat(Imag.getSemantics());
6424 return true;
6425 } else {
6426 assert(SubExpr->getType()->isIntegerType() &&
6427 "Unexpected imaginary literal.");
6428
6429 Result.makeComplexInt();
6430 APSInt &Imag = Result.IntImag;
6431 if (!EvaluateInteger(SubExpr, Imag, Info))
6432 return false;
6433
6434 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6435 return true;
6436 }
6437}
6438
Peter Collingbournee9200682011-05-13 03:29:01 +00006439bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006440
John McCallfcef3cf2010-12-14 17:51:41 +00006441 switch (E->getCastKind()) {
6442 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006443 case CK_BaseToDerived:
6444 case CK_DerivedToBase:
6445 case CK_UncheckedDerivedToBase:
6446 case CK_Dynamic:
6447 case CK_ToUnion:
6448 case CK_ArrayToPointerDecay:
6449 case CK_FunctionToPointerDecay:
6450 case CK_NullToPointer:
6451 case CK_NullToMemberPointer:
6452 case CK_BaseToDerivedMemberPointer:
6453 case CK_DerivedToBaseMemberPointer:
6454 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006455 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006456 case CK_ConstructorConversion:
6457 case CK_IntegralToPointer:
6458 case CK_PointerToIntegral:
6459 case CK_PointerToBoolean:
6460 case CK_ToVoid:
6461 case CK_VectorSplat:
6462 case CK_IntegralCast:
6463 case CK_IntegralToBoolean:
6464 case CK_IntegralToFloating:
6465 case CK_FloatingToIntegral:
6466 case CK_FloatingToBoolean:
6467 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006468 case CK_CPointerToObjCPointerCast:
6469 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006470 case CK_AnyPointerToBlockPointerCast:
6471 case CK_ObjCObjectLValueCast:
6472 case CK_FloatingComplexToReal:
6473 case CK_FloatingComplexToBoolean:
6474 case CK_IntegralComplexToReal:
6475 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006476 case CK_ARCProduceObject:
6477 case CK_ARCConsumeObject:
6478 case CK_ARCReclaimReturnedObject:
6479 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006480 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006481 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006482 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006483 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006484
John McCallfcef3cf2010-12-14 17:51:41 +00006485 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006486 case CK_AtomicToNonAtomic:
6487 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006488 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006489 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006490
6491 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006492 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006493 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006494 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006495
6496 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006497 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006498 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006499 return false;
6500
John McCallfcef3cf2010-12-14 17:51:41 +00006501 Result.makeComplexFloat();
6502 Result.FloatImag = APFloat(Real.getSemantics());
6503 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006504 }
6505
John McCallfcef3cf2010-12-14 17:51:41 +00006506 case CK_FloatingComplexCast: {
6507 if (!Visit(E->getSubExpr()))
6508 return false;
6509
6510 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6511 QualType From
6512 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6513
Richard Smith357362d2011-12-13 06:39:58 +00006514 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6515 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006516 }
6517
6518 case CK_FloatingComplexToIntegralComplex: {
6519 if (!Visit(E->getSubExpr()))
6520 return false;
6521
6522 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6523 QualType From
6524 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6525 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006526 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6527 To, Result.IntReal) &&
6528 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6529 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006530 }
6531
6532 case CK_IntegralRealToComplex: {
6533 APSInt &Real = Result.IntReal;
6534 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6535 return false;
6536
6537 Result.makeComplexInt();
6538 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6539 return true;
6540 }
6541
6542 case CK_IntegralComplexCast: {
6543 if (!Visit(E->getSubExpr()))
6544 return false;
6545
6546 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6547 QualType From
6548 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6549
Richard Smith911e1422012-01-30 22:27:01 +00006550 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6551 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006552 return true;
6553 }
6554
6555 case CK_IntegralComplexToFloatingComplex: {
6556 if (!Visit(E->getSubExpr()))
6557 return false;
6558
Ted Kremenek28831752012-08-23 20:46:57 +00006559 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006560 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006561 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006562 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006563 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6564 To, Result.FloatReal) &&
6565 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6566 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006567 }
6568 }
6569
6570 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006571}
6572
John McCall93d91dc2010-05-07 17:22:02 +00006573bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006574 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006575 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6576
Richard Smith253c2a32012-01-27 01:14:48 +00006577 bool LHSOK = Visit(E->getLHS());
6578 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006579 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006580
John McCall93d91dc2010-05-07 17:22:02 +00006581 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006582 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006583 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006584
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006585 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6586 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006587 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006588 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006589 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006590 if (Result.isComplexFloat()) {
6591 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6592 APFloat::rmNearestTiesToEven);
6593 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6594 APFloat::rmNearestTiesToEven);
6595 } else {
6596 Result.getComplexIntReal() += RHS.getComplexIntReal();
6597 Result.getComplexIntImag() += RHS.getComplexIntImag();
6598 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006599 break;
John McCalle3027922010-08-25 11:45:40 +00006600 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006601 if (Result.isComplexFloat()) {
6602 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6603 APFloat::rmNearestTiesToEven);
6604 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6605 APFloat::rmNearestTiesToEven);
6606 } else {
6607 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6608 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6609 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006610 break;
John McCalle3027922010-08-25 11:45:40 +00006611 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006612 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006613 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006614 APFloat &LHS_r = LHS.getComplexFloatReal();
6615 APFloat &LHS_i = LHS.getComplexFloatImag();
6616 APFloat &RHS_r = RHS.getComplexFloatReal();
6617 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006618
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006619 APFloat Tmp = LHS_r;
6620 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6621 Result.getComplexFloatReal() = Tmp;
6622 Tmp = LHS_i;
6623 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6624 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6625
6626 Tmp = LHS_r;
6627 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6628 Result.getComplexFloatImag() = Tmp;
6629 Tmp = LHS_i;
6630 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6631 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6632 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006633 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006634 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006635 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6636 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006637 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006638 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6639 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6640 }
6641 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006642 case BO_Div:
6643 if (Result.isComplexFloat()) {
6644 ComplexValue LHS = Result;
6645 APFloat &LHS_r = LHS.getComplexFloatReal();
6646 APFloat &LHS_i = LHS.getComplexFloatImag();
6647 APFloat &RHS_r = RHS.getComplexFloatReal();
6648 APFloat &RHS_i = RHS.getComplexFloatImag();
6649 APFloat &Res_r = Result.getComplexFloatReal();
6650 APFloat &Res_i = Result.getComplexFloatImag();
6651
6652 APFloat Den = RHS_r;
6653 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6654 APFloat Tmp = RHS_i;
6655 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6656 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6657
6658 Res_r = LHS_r;
6659 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6660 Tmp = LHS_i;
6661 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6662 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6663 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6664
6665 Res_i = LHS_i;
6666 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6667 Tmp = LHS_r;
6668 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6669 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6670 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6671 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006672 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6673 return Error(E, diag::note_expr_divide_by_zero);
6674
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006675 ComplexValue LHS = Result;
6676 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6677 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6678 Result.getComplexIntReal() =
6679 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6680 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6681 Result.getComplexIntImag() =
6682 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6683 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6684 }
6685 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006686 }
6687
John McCall93d91dc2010-05-07 17:22:02 +00006688 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006689}
6690
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006691bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6692 // Get the operand value into 'Result'.
6693 if (!Visit(E->getSubExpr()))
6694 return false;
6695
6696 switch (E->getOpcode()) {
6697 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006698 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006699 case UO_Extension:
6700 return true;
6701 case UO_Plus:
6702 // The result is always just the subexpr.
6703 return true;
6704 case UO_Minus:
6705 if (Result.isComplexFloat()) {
6706 Result.getComplexFloatReal().changeSign();
6707 Result.getComplexFloatImag().changeSign();
6708 }
6709 else {
6710 Result.getComplexIntReal() = -Result.getComplexIntReal();
6711 Result.getComplexIntImag() = -Result.getComplexIntImag();
6712 }
6713 return true;
6714 case UO_Not:
6715 if (Result.isComplexFloat())
6716 Result.getComplexFloatImag().changeSign();
6717 else
6718 Result.getComplexIntImag() = -Result.getComplexIntImag();
6719 return true;
6720 }
6721}
6722
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006723bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6724 if (E->getNumInits() == 2) {
6725 if (E->getType()->isComplexType()) {
6726 Result.makeComplexFloat();
6727 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6728 return false;
6729 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6730 return false;
6731 } else {
6732 Result.makeComplexInt();
6733 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6734 return false;
6735 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6736 return false;
6737 }
6738 return true;
6739 }
6740 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6741}
6742
Anders Carlsson537969c2008-11-16 20:27:53 +00006743//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006744// Void expression evaluation, primarily for a cast to void on the LHS of a
6745// comma operator
6746//===----------------------------------------------------------------------===//
6747
6748namespace {
6749class VoidExprEvaluator
6750 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6751public:
6752 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6753
Richard Smith2e312c82012-03-03 22:46:17 +00006754 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006755
6756 bool VisitCastExpr(const CastExpr *E) {
6757 switch (E->getCastKind()) {
6758 default:
6759 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6760 case CK_ToVoid:
6761 VisitIgnoredValue(E->getSubExpr());
6762 return true;
6763 }
6764 }
6765};
6766} // end anonymous namespace
6767
6768static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6769 assert(E->isRValue() && E->getType()->isVoidType());
6770 return VoidExprEvaluator(Info).Visit(E);
6771}
6772
6773//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006774// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006775//===----------------------------------------------------------------------===//
6776
Richard Smith2e312c82012-03-03 22:46:17 +00006777static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006778 // In C, function designators are not lvalues, but we evaluate them as if they
6779 // are.
6780 if (E->isGLValue() || E->getType()->isFunctionType()) {
6781 LValue LV;
6782 if (!EvaluateLValue(E, LV, Info))
6783 return false;
6784 LV.moveInto(Result);
6785 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006786 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006787 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006788 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006789 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006790 return false;
John McCall45d55e42010-05-07 21:00:08 +00006791 } else if (E->getType()->hasPointerRepresentation()) {
6792 LValue LV;
6793 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006794 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006795 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006796 } else if (E->getType()->isRealFloatingType()) {
6797 llvm::APFloat F(0.0);
6798 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006799 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006800 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006801 } else if (E->getType()->isAnyComplexType()) {
6802 ComplexValue C;
6803 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006804 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006805 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006806 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006807 MemberPtr P;
6808 if (!EvaluateMemberPointer(E, P, Info))
6809 return false;
6810 P.moveInto(Result);
6811 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006812 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006813 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006814 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006815 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006816 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006817 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006818 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006819 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006820 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006821 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6822 return false;
6823 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006824 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006825 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006826 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006827 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006828 if (!EvaluateVoid(E, Info))
6829 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006830 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006831 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006832 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006833 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006834 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006835 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006836 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006837
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006838 return true;
6839}
6840
Richard Smithb228a862012-02-15 02:18:13 +00006841/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6842/// cases, the in-place evaluation is essential, since later initializers for
6843/// an object can indirectly refer to subobjects which were initialized earlier.
6844static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6845 const Expr *E, CheckConstantExpressionKind CCEK,
6846 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006847 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006848 return false;
6849
6850 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006851 // Evaluate arrays and record types in-place, so that later initializers can
6852 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006853 if (E->getType()->isArrayType())
6854 return EvaluateArray(E, This, Result, Info);
6855 else if (E->getType()->isRecordType())
6856 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006857 }
6858
6859 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006860 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006861}
6862
Richard Smithf57d8cb2011-12-09 22:58:01 +00006863/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6864/// lvalue-to-rvalue cast if it is an lvalue.
6865static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006866 if (!CheckLiteralType(Info, E))
6867 return false;
6868
Richard Smith2e312c82012-03-03 22:46:17 +00006869 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006870 return false;
6871
6872 if (E->isGLValue()) {
6873 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00006874 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00006875 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006876 return false;
6877 }
6878
Richard Smith2e312c82012-03-03 22:46:17 +00006879 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00006880 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006881}
Richard Smith11562c52011-10-28 17:51:58 +00006882
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006883static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6884 const ASTContext &Ctx, bool &IsConst) {
6885 // Fast-path evaluations of integer literals, since we sometimes see files
6886 // containing vast quantities of these.
6887 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6888 Result.Val = APValue(APSInt(L->getValue(),
6889 L->getType()->isUnsignedIntegerType()));
6890 IsConst = true;
6891 return true;
6892 }
6893
6894 // FIXME: Evaluating values of large array and record types can cause
6895 // performance problems. Only do so in C++11 for now.
6896 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6897 Exp->getType()->isRecordType()) &&
6898 !Ctx.getLangOpts().CPlusPlus11) {
6899 IsConst = false;
6900 return true;
6901 }
6902 return false;
6903}
6904
6905
Richard Smith7b553f12011-10-29 00:50:52 +00006906/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00006907/// any crazy technique (that has nothing to do with language standards) that
6908/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00006909/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6910/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00006911bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006912 bool IsConst;
6913 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
6914 return IsConst;
6915
Richard Smithf57d8cb2011-12-09 22:58:01 +00006916 EvalInfo Info(Ctx, Result);
6917 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00006918}
6919
Jay Foad39c79802011-01-12 09:06:06 +00006920bool Expr::EvaluateAsBooleanCondition(bool &Result,
6921 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00006922 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00006923 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00006924 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00006925}
6926
Richard Smith5fab0c92011-12-28 19:48:30 +00006927bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6928 SideEffectsKind AllowSideEffects) const {
6929 if (!getType()->isIntegralOrEnumerationType())
6930 return false;
6931
Richard Smith11562c52011-10-28 17:51:58 +00006932 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00006933 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6934 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00006935 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006936
Richard Smith11562c52011-10-28 17:51:58 +00006937 Result = ExprResult.Val.getInt();
6938 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00006939}
6940
Jay Foad39c79802011-01-12 09:06:06 +00006941bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00006942 EvalInfo Info(Ctx, Result);
6943
John McCall45d55e42010-05-07 21:00:08 +00006944 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006945 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6946 !CheckLValueConstantExpression(Info, getExprLoc(),
6947 Ctx.getLValueReferenceType(getType()), LV))
6948 return false;
6949
Richard Smith2e312c82012-03-03 22:46:17 +00006950 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00006951 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00006952}
6953
Richard Smithd0b4dd62011-12-19 06:19:21 +00006954bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6955 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006956 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00006957 // FIXME: Evaluating initializers for large array and record types can cause
6958 // performance problems. Only do so in C++11 for now.
6959 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006960 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00006961 return false;
6962
Richard Smithd0b4dd62011-12-19 06:19:21 +00006963 Expr::EvalStatus EStatus;
6964 EStatus.Diag = &Notes;
6965
6966 EvalInfo InitInfo(Ctx, EStatus);
6967 InitInfo.setEvaluatingDecl(VD, Value);
6968
6969 LValue LVal;
6970 LVal.set(VD);
6971
Richard Smithfddd3842011-12-30 21:15:51 +00006972 // C++11 [basic.start.init]p2:
6973 // Variables with static storage duration or thread storage duration shall be
6974 // zero-initialized before any other initialization takes place.
6975 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006976 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00006977 !VD->getType()->isReferenceType()) {
6978 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006979 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6980 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00006981 return false;
6982 }
6983
Richard Smithb228a862012-02-15 02:18:13 +00006984 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6985 /*AllowNonLiteralTypes=*/true) ||
6986 EStatus.HasSideEffects)
6987 return false;
6988
6989 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6990 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00006991}
6992
Richard Smith7b553f12011-10-29 00:50:52 +00006993/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6994/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00006995bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00006996 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00006997 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00006998}
Anders Carlsson59689ed2008-11-22 21:04:56 +00006999
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007000APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007001 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007002 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007003 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007004 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007005 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007006 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007007 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007008
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007009 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007010}
John McCall864e3962010-05-07 05:32:02 +00007011
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007012void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7013 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7014 bool IsConst;
7015 EvalResult EvalResult;
7016 EvalResult.Diag = Diags;
7017 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7018 EvalInfo Info(Ctx, EvalResult, true);
7019 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7020 }
7021}
7022
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007023 bool Expr::EvalResult::isGlobalLValue() const {
7024 assert(Val.isLValue());
7025 return IsGlobalLValue(Val.getLValueBase());
7026 }
7027
7028
John McCall864e3962010-05-07 05:32:02 +00007029/// isIntegerConstantExpr - this recursive routine will test if an expression is
7030/// an integer constant expression.
7031
7032/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7033/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007034
7035// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007036// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7037// and a (possibly null) SourceLocation indicating the location of the problem.
7038//
John McCall864e3962010-05-07 05:32:02 +00007039// Note that to reduce code duplication, this helper does no evaluation
7040// itself; the caller checks whether the expression is evaluatable, and
7041// in the rare cases where CheckICE actually cares about the evaluated
7042// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007043
Dan Gohman28ade552010-07-26 21:25:24 +00007044namespace {
7045
Richard Smith9e575da2012-12-28 13:25:52 +00007046enum ICEKind {
7047 /// This expression is an ICE.
7048 IK_ICE,
7049 /// This expression is not an ICE, but if it isn't evaluated, it's
7050 /// a legal subexpression for an ICE. This return value is used to handle
7051 /// the comma operator in C99 mode, and non-constant subexpressions.
7052 IK_ICEIfUnevaluated,
7053 /// This expression is not an ICE, and is not a legal subexpression for one.
7054 IK_NotICE
7055};
7056
John McCall864e3962010-05-07 05:32:02 +00007057struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007058 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007059 SourceLocation Loc;
7060
Richard Smith9e575da2012-12-28 13:25:52 +00007061 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007062};
7063
Dan Gohman28ade552010-07-26 21:25:24 +00007064}
7065
Richard Smith9e575da2012-12-28 13:25:52 +00007066static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7067
7068static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007069
7070static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7071 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007072 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007073 !EVResult.Val.isInt())
7074 return ICEDiag(IK_NotICE, E->getLocStart());
7075
John McCall864e3962010-05-07 05:32:02 +00007076 return NoDiag();
7077}
7078
7079static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7080 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007081 if (!E->getType()->isIntegralOrEnumerationType())
7082 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007083
7084 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007085#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007086#define STMT(Node, Base) case Expr::Node##Class:
7087#define EXPR(Node, Base)
7088#include "clang/AST/StmtNodes.inc"
7089 case Expr::PredefinedExprClass:
7090 case Expr::FloatingLiteralClass:
7091 case Expr::ImaginaryLiteralClass:
7092 case Expr::StringLiteralClass:
7093 case Expr::ArraySubscriptExprClass:
7094 case Expr::MemberExprClass:
7095 case Expr::CompoundAssignOperatorClass:
7096 case Expr::CompoundLiteralExprClass:
7097 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007098 case Expr::DesignatedInitExprClass:
7099 case Expr::ImplicitValueInitExprClass:
7100 case Expr::ParenListExprClass:
7101 case Expr::VAArgExprClass:
7102 case Expr::AddrLabelExprClass:
7103 case Expr::StmtExprClass:
7104 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007105 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007106 case Expr::CXXDynamicCastExprClass:
7107 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007108 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007109 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007110 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007111 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007112 case Expr::CXXThisExprClass:
7113 case Expr::CXXThrowExprClass:
7114 case Expr::CXXNewExprClass:
7115 case Expr::CXXDeleteExprClass:
7116 case Expr::CXXPseudoDestructorExprClass:
7117 case Expr::UnresolvedLookupExprClass:
7118 case Expr::DependentScopeDeclRefExprClass:
7119 case Expr::CXXConstructExprClass:
7120 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007121 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007122 case Expr::CXXTemporaryObjectExprClass:
7123 case Expr::CXXUnresolvedConstructExprClass:
7124 case Expr::CXXDependentScopeMemberExprClass:
7125 case Expr::UnresolvedMemberExprClass:
7126 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007127 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007128 case Expr::ObjCArrayLiteralClass:
7129 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007130 case Expr::ObjCEncodeExprClass:
7131 case Expr::ObjCMessageExprClass:
7132 case Expr::ObjCSelectorExprClass:
7133 case Expr::ObjCProtocolExprClass:
7134 case Expr::ObjCIvarRefExprClass:
7135 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007136 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007137 case Expr::ObjCIsaExprClass:
7138 case Expr::ShuffleVectorExprClass:
7139 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007140 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007141 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007142 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007143 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007144 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007145 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007146 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007147 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007148 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007149 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007150 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007151 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007152 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007153
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007154 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007155 case Expr::GNUNullExprClass:
7156 // GCC considers the GNU __null value to be an integral constant expression.
7157 return NoDiag();
7158
John McCall7c454bb2011-07-15 05:09:51 +00007159 case Expr::SubstNonTypeTemplateParmExprClass:
7160 return
7161 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7162
John McCall864e3962010-05-07 05:32:02 +00007163 case Expr::ParenExprClass:
7164 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007165 case Expr::GenericSelectionExprClass:
7166 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007167 case Expr::IntegerLiteralClass:
7168 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007169 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007170 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007171 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007172 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007173 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007174 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007175 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007176 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007177 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007178 return NoDiag();
7179 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007180 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007181 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7182 // constant expressions, but they can never be ICEs because an ICE cannot
7183 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007184 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007185 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007186 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007187 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007188 }
Richard Smith6365c912012-02-24 22:12:32 +00007189 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007190 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7191 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007192 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007193 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007194 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007195 // Parameter variables are never constants. Without this check,
7196 // getAnyInitializer() can find a default argument, which leads
7197 // to chaos.
7198 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007199 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007200
7201 // C++ 7.1.5.1p2
7202 // A variable of non-volatile const-qualified integral or enumeration
7203 // type initialized by an ICE can be used in ICEs.
7204 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007205 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007206 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007207
Richard Smithd0b4dd62011-12-19 06:19:21 +00007208 const VarDecl *VD;
7209 // Look for a declaration of this variable that has an initializer, and
7210 // check whether it is an ICE.
7211 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7212 return NoDiag();
7213 else
Richard Smith9e575da2012-12-28 13:25:52 +00007214 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007215 }
7216 }
Richard Smith9e575da2012-12-28 13:25:52 +00007217 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007218 }
John McCall864e3962010-05-07 05:32:02 +00007219 case Expr::UnaryOperatorClass: {
7220 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7221 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007222 case UO_PostInc:
7223 case UO_PostDec:
7224 case UO_PreInc:
7225 case UO_PreDec:
7226 case UO_AddrOf:
7227 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007228 // C99 6.6/3 allows increment and decrement within unevaluated
7229 // subexpressions of constant expressions, but they can never be ICEs
7230 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007231 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007232 case UO_Extension:
7233 case UO_LNot:
7234 case UO_Plus:
7235 case UO_Minus:
7236 case UO_Not:
7237 case UO_Real:
7238 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007239 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007240 }
Richard Smith9e575da2012-12-28 13:25:52 +00007241
John McCall864e3962010-05-07 05:32:02 +00007242 // OffsetOf falls through here.
7243 }
7244 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007245 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7246 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7247 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7248 // compliance: we should warn earlier for offsetof expressions with
7249 // array subscripts that aren't ICEs, and if the array subscripts
7250 // are ICEs, the value of the offsetof must be an integer constant.
7251 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007252 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007253 case Expr::UnaryExprOrTypeTraitExprClass: {
7254 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7255 if ((Exp->getKind() == UETT_SizeOf) &&
7256 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007257 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007258 return NoDiag();
7259 }
7260 case Expr::BinaryOperatorClass: {
7261 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7262 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007263 case BO_PtrMemD:
7264 case BO_PtrMemI:
7265 case BO_Assign:
7266 case BO_MulAssign:
7267 case BO_DivAssign:
7268 case BO_RemAssign:
7269 case BO_AddAssign:
7270 case BO_SubAssign:
7271 case BO_ShlAssign:
7272 case BO_ShrAssign:
7273 case BO_AndAssign:
7274 case BO_XorAssign:
7275 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007276 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7277 // constant expressions, but they can never be ICEs because an ICE cannot
7278 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007279 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007280
John McCalle3027922010-08-25 11:45:40 +00007281 case BO_Mul:
7282 case BO_Div:
7283 case BO_Rem:
7284 case BO_Add:
7285 case BO_Sub:
7286 case BO_Shl:
7287 case BO_Shr:
7288 case BO_LT:
7289 case BO_GT:
7290 case BO_LE:
7291 case BO_GE:
7292 case BO_EQ:
7293 case BO_NE:
7294 case BO_And:
7295 case BO_Xor:
7296 case BO_Or:
7297 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007298 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7299 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007300 if (Exp->getOpcode() == BO_Div ||
7301 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007302 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007303 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007304 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007305 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007306 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007307 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007308 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007309 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007310 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007311 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007312 }
7313 }
7314 }
John McCalle3027922010-08-25 11:45:40 +00007315 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007316 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007317 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7318 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007319 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7320 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007321 } else {
7322 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007323 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007324 }
7325 }
Richard Smith9e575da2012-12-28 13:25:52 +00007326 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007327 }
John McCalle3027922010-08-25 11:45:40 +00007328 case BO_LAnd:
7329 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007330 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7331 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007332 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007333 // Rare case where the RHS has a comma "side-effect"; we need
7334 // to actually check the condition to see whether the side
7335 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007336 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007337 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007338 return RHSResult;
7339 return NoDiag();
7340 }
7341
Richard Smith9e575da2012-12-28 13:25:52 +00007342 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007343 }
7344 }
7345 }
7346 case Expr::ImplicitCastExprClass:
7347 case Expr::CStyleCastExprClass:
7348 case Expr::CXXFunctionalCastExprClass:
7349 case Expr::CXXStaticCastExprClass:
7350 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007351 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007352 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007353 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007354 if (isa<ExplicitCastExpr>(E)) {
7355 if (const FloatingLiteral *FL
7356 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7357 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7358 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7359 APSInt IgnoredVal(DestWidth, !DestSigned);
7360 bool Ignored;
7361 // If the value does not fit in the destination type, the behavior is
7362 // undefined, so we are not required to treat it as a constant
7363 // expression.
7364 if (FL->getValue().convertToInteger(IgnoredVal,
7365 llvm::APFloat::rmTowardZero,
7366 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007367 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007368 return NoDiag();
7369 }
7370 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007371 switch (cast<CastExpr>(E)->getCastKind()) {
7372 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007373 case CK_AtomicToNonAtomic:
7374 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007375 case CK_NoOp:
7376 case CK_IntegralToBoolean:
7377 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007378 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007379 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007380 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007381 }
John McCall864e3962010-05-07 05:32:02 +00007382 }
John McCallc07a0c72011-02-17 10:25:35 +00007383 case Expr::BinaryConditionalOperatorClass: {
7384 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7385 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007386 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007387 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007388 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7389 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7390 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007391 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007392 return FalseResult;
7393 }
John McCall864e3962010-05-07 05:32:02 +00007394 case Expr::ConditionalOperatorClass: {
7395 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7396 // If the condition (ignoring parens) is a __builtin_constant_p call,
7397 // then only the true side is actually considered in an integer constant
7398 // expression, and it is fully evaluated. This is an important GNU
7399 // extension. See GCC PR38377 for discussion.
7400 if (const CallExpr *CallCE
7401 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007402 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7403 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007404 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007405 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007406 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007407
Richard Smithf57d8cb2011-12-09 22:58:01 +00007408 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7409 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007410
Richard Smith9e575da2012-12-28 13:25:52 +00007411 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007412 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007413 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007414 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007415 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007416 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007417 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007418 return NoDiag();
7419 // Rare case where the diagnostics depend on which side is evaluated
7420 // Note that if we get here, CondResult is 0, and at least one of
7421 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007422 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007423 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007424 return TrueResult;
7425 }
7426 case Expr::CXXDefaultArgExprClass:
7427 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007428 case Expr::CXXDefaultInitExprClass:
7429 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007430 case Expr::ChooseExprClass: {
7431 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7432 }
7433 }
7434
David Blaikiee4d798f2012-01-20 21:50:17 +00007435 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007436}
7437
Richard Smithf57d8cb2011-12-09 22:58:01 +00007438/// Evaluate an expression as a C++11 integral constant expression.
7439static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7440 const Expr *E,
7441 llvm::APSInt *Value,
7442 SourceLocation *Loc) {
7443 if (!E->getType()->isIntegralOrEnumerationType()) {
7444 if (Loc) *Loc = E->getExprLoc();
7445 return false;
7446 }
7447
Richard Smith66e05fe2012-01-18 05:21:49 +00007448 APValue Result;
7449 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007450 return false;
7451
Richard Smith66e05fe2012-01-18 05:21:49 +00007452 assert(Result.isInt() && "pointer cast to int is not an ICE");
7453 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007454 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007455}
7456
Richard Smith92b1ce02011-12-12 09:28:41 +00007457bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007458 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007459 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7460
Richard Smith9e575da2012-12-28 13:25:52 +00007461 ICEDiag D = CheckICE(this, Ctx);
7462 if (D.Kind != IK_ICE) {
7463 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007464 return false;
7465 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007466 return true;
7467}
7468
7469bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7470 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007471 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007472 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7473
7474 if (!isIntegerConstantExpr(Ctx, Loc))
7475 return false;
7476 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007477 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007478 return true;
7479}
Richard Smith66e05fe2012-01-18 05:21:49 +00007480
Richard Smith98a0a492012-02-14 21:38:30 +00007481bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007482 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007483}
7484
Richard Smith66e05fe2012-01-18 05:21:49 +00007485bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7486 SourceLocation *Loc) const {
7487 // We support this checking in C++98 mode in order to diagnose compatibility
7488 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007489 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007490
Richard Smith98a0a492012-02-14 21:38:30 +00007491 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007492 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007493 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007494 Status.Diag = &Diags;
7495 EvalInfo Info(Ctx, Status);
7496
7497 APValue Scratch;
7498 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7499
7500 if (!Diags.empty()) {
7501 IsConstExpr = false;
7502 if (Loc) *Loc = Diags[0].first;
7503 } else if (!IsConstExpr) {
7504 // FIXME: This shouldn't happen.
7505 if (Loc) *Loc = getExprLoc();
7506 }
7507
7508 return IsConstExpr;
7509}
Richard Smith253c2a32012-01-27 01:14:48 +00007510
7511bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007512 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007513 PartialDiagnosticAt> &Diags) {
7514 // FIXME: It would be useful to check constexpr function templates, but at the
7515 // moment the constant expression evaluator cannot cope with the non-rigorous
7516 // ASTs which we build for dependent expressions.
7517 if (FD->isDependentContext())
7518 return true;
7519
7520 Expr::EvalStatus Status;
7521 Status.Diag = &Diags;
7522
7523 EvalInfo Info(FD->getASTContext(), Status);
7524 Info.CheckingPotentialConstantExpression = true;
7525
7526 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7527 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7528
7529 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7530 // is a temporary being used as the 'this' pointer.
7531 LValue This;
7532 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007533 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007534
Richard Smith253c2a32012-01-27 01:14:48 +00007535 ArrayRef<const Expr*> Args;
7536
7537 SourceLocation Loc = FD->getLocation();
7538
Richard Smith2e312c82012-03-03 22:46:17 +00007539 APValue Scratch;
7540 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00007541 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00007542 else
Richard Smith253c2a32012-01-27 01:14:48 +00007543 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7544 Args, FD->getBody(), Info, Scratch);
7545
7546 return Diags.empty();
7547}