blob: fbef525ce4f094d7c90d2e05735186b3436ec75f [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
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
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 Smitha3d3bd22013-05-08 02:12:03 +0000383 /// StepsLeft - The remaining number of evaluation steps we're permitted
384 /// to perform. This is essentially a limit for the number of statements
385 /// we will evaluate.
386 unsigned StepsLeft;
387
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000388 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000389 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000390 CallStackFrame BottomFrame;
391
Richard Smithd62306a2011-11-10 06:34:14 +0000392 /// EvaluatingDecl - This is the declaration whose initializer is being
393 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000394 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000395
396 /// EvaluatingDeclValue - This is the value being constructed for the
397 /// declaration whose initializer is being evaluated, if any.
398 APValue *EvaluatingDeclValue;
399
Richard Smith357362d2011-12-13 06:39:58 +0000400 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
401 /// notes attached to it will also be stored, otherwise they will not be.
402 bool HasActiveDiagnostic;
403
Richard Smith253c2a32012-01-27 01:14:48 +0000404 /// CheckingPotentialConstantExpression - Are we checking whether the
405 /// expression is a potential constant expression? If so, some diagnostics
406 /// are suppressed.
407 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000408
409 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000410
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000411 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
Richard Smitha3d3bd22013-05-08 02:12:03 +0000412 bool OverflowCheckMode = false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000413 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000414 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000415 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000416 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith7525ff62013-05-09 07:14:00 +0000417 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
418 HasActiveDiagnostic(false), CheckingPotentialConstantExpression(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000419 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000420
Richard Smith7525ff62013-05-09 07:14:00 +0000421 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
422 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000423 EvaluatingDeclValue = &Value;
424 }
425
David Blaikiebbafb8a2012-03-11 07:00:24 +0000426 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000427
Richard Smith357362d2011-12-13 06:39:58 +0000428 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000429 // Don't perform any constexpr calls (other than the call we're checking)
430 // when checking a potential constant expression.
431 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
432 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000433 if (NextCallIndex == 0) {
434 // NextCallIndex has wrapped around.
435 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
436 return false;
437 }
Richard Smith357362d2011-12-13 06:39:58 +0000438 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
439 return true;
440 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
441 << getLangOpts().ConstexprCallDepth;
442 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000443 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000444
Richard Smithb228a862012-02-15 02:18:13 +0000445 CallStackFrame *getCallFrame(unsigned CallIndex) {
446 assert(CallIndex && "no call index in getCallFrame");
447 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
448 // be null in this loop.
449 CallStackFrame *Frame = CurrentCall;
450 while (Frame->Index > CallIndex)
451 Frame = Frame->Caller;
452 return (Frame->Index == CallIndex) ? Frame : 0;
453 }
454
Richard Smitha3d3bd22013-05-08 02:12:03 +0000455 bool nextStep(const Stmt *S) {
456 if (!StepsLeft) {
457 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
458 return false;
459 }
460 --StepsLeft;
461 return true;
462 }
463
Richard Smith357362d2011-12-13 06:39:58 +0000464 private:
465 /// Add a diagnostic to the diagnostics list.
466 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
467 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
468 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
469 return EvalStatus.Diag->back().second;
470 }
471
Richard Smithf6f003a2011-12-16 19:06:07 +0000472 /// Add notes containing a call stack to the current point of evaluation.
473 void addCallStack(unsigned Limit);
474
Richard Smith357362d2011-12-13 06:39:58 +0000475 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000476 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000477 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
478 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000479 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000480 // If we have a prior diagnostic, it will be noting that the expression
481 // isn't a constant expression. This diagnostic is more important.
482 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000484 unsigned CallStackNotes = CallStackDepth - 1;
485 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
486 if (Limit)
487 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000488 if (CheckingPotentialConstantExpression)
489 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000490
Richard Smith357362d2011-12-13 06:39:58 +0000491 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000492 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000493 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
494 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000495 if (!CheckingPotentialConstantExpression)
496 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000497 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000498 }
Richard Smith357362d2011-12-13 06:39:58 +0000499 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000500 return OptionalDiagnostic();
501 }
502
Richard Smithce1ec5e2012-03-15 04:53:45 +0000503 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
504 = diag::note_invalid_subexpr_in_const_expr,
505 unsigned ExtraNotes = 0) {
506 if (EvalStatus.Diag)
507 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
508 HasActiveDiagnostic = false;
509 return OptionalDiagnostic();
510 }
511
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000512 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
513
Richard Smith92b1ce02011-12-12 09:28:41 +0000514 /// Diagnose that the evaluation does not produce a C++11 core constant
515 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000516 template<typename LocArg>
517 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000518 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000519 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000520 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000521 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
522 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000523 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000524 }
Richard Smith357362d2011-12-13 06:39:58 +0000525 return Diag(Loc, DiagId, ExtraNotes);
526 }
527
528 /// Add a note to a prior diagnostic.
529 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
530 if (!HasActiveDiagnostic)
531 return OptionalDiagnostic();
532 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000533 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000534
535 /// Add a stack of notes to a prior diagnostic.
536 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
537 if (HasActiveDiagnostic) {
538 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
539 Diags.begin(), Diags.end());
540 }
541 }
Richard Smith253c2a32012-01-27 01:14:48 +0000542
543 /// Should we continue evaluation as much as possible after encountering a
544 /// construct which can't be folded?
545 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000546 // Should return true in IntOverflowCheckMode, so that we check for
547 // overflow even if some subexpressions can't be evaluated as constants.
Richard Smitha3d3bd22013-05-08 02:12:03 +0000548 return StepsLeft && (IntOverflowCheckMode ||
549 (CheckingPotentialConstantExpression &&
550 EvalStatus.Diag && EvalStatus.Diag->empty()));
Richard Smith253c2a32012-01-27 01:14:48 +0000551 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000552 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000553
554 /// Object used to treat all foldable expressions as constant expressions.
555 struct FoldConstant {
556 bool Enabled;
557
558 explicit FoldConstant(EvalInfo &Info)
559 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
560 !Info.EvalStatus.HasSideEffects) {
561 }
562 // Treat the value we've computed since this object was created as constant.
563 void Fold(EvalInfo &Info) {
564 if (Enabled && !Info.EvalStatus.Diag->empty() &&
565 !Info.EvalStatus.HasSideEffects)
566 Info.EvalStatus.Diag->clear();
567 }
568 };
Richard Smith17100ba2012-02-16 02:46:34 +0000569
570 /// RAII object used to suppress diagnostics and side-effects from a
571 /// speculative evaluation.
572 class SpeculativeEvaluationRAII {
573 EvalInfo &Info;
574 Expr::EvalStatus Old;
575
576 public:
577 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000578 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000579 : Info(Info), Old(Info.EvalStatus) {
580 Info.EvalStatus.Diag = NewDiag;
581 }
582 ~SpeculativeEvaluationRAII() {
583 Info.EvalStatus = Old;
584 }
585 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000586}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000587
Richard Smitha8105bc2012-01-06 16:39:00 +0000588bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
589 CheckSubobjectKind CSK) {
590 if (Invalid)
591 return false;
592 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << CSK;
595 setInvalid();
596 return false;
597 }
598 return true;
599}
600
601void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
602 const Expr *E, uint64_t N) {
603 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000604 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000605 << static_cast<int>(N) << /*array*/ 0
606 << static_cast<unsigned>(MostDerivedArraySize);
607 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000608 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000609 << static_cast<int>(N) << /*non-array*/ 1;
610 setInvalid();
611}
612
Richard Smithf6f003a2011-12-16 19:06:07 +0000613CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
614 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000615 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000616 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000617 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000618 Info.CurrentCall = this;
619 ++Info.CallStackDepth;
620}
621
622CallStackFrame::~CallStackFrame() {
623 assert(Info.CurrentCall == this && "calls retired out of order");
624 --Info.CallStackDepth;
625 Info.CurrentCall = Caller;
626}
627
628/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000629static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000630 unsigned ArgIndex = 0;
631 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000632 !isa<CXXConstructorDecl>(Frame->Callee) &&
633 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000634
635 if (!IsMemberCall)
636 Out << *Frame->Callee << '(';
637
638 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
639 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000640 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000641 Out << ", ";
642
643 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000644 const APValue &Arg = Frame->Arguments[ArgIndex];
645 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000646
647 if (ArgIndex == 0 && IsMemberCall)
648 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000649 }
650
Richard Smithf6f003a2011-12-16 19:06:07 +0000651 Out << ')';
652}
653
654void EvalInfo::addCallStack(unsigned Limit) {
655 // Determine which calls to skip, if any.
656 unsigned ActiveCalls = CallStackDepth - 1;
657 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
658 if (Limit && Limit < ActiveCalls) {
659 SkipStart = Limit / 2 + Limit % 2;
660 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000661 }
662
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 // Walk the call stack and add the diagnostics.
664 unsigned CallIdx = 0;
665 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
666 Frame = Frame->Caller, ++CallIdx) {
667 // Skip this call?
668 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
669 if (CallIdx == SkipStart) {
670 // Note that we're skipping calls.
671 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
672 << unsigned(ActiveCalls - Limit);
673 }
674 continue;
675 }
676
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000677 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000678 llvm::raw_svector_ostream Out(Buffer);
679 describeCall(Frame, Out);
680 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
681 }
682}
683
684namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000685 struct ComplexValue {
686 private:
687 bool IsInt;
688
689 public:
690 APSInt IntReal, IntImag;
691 APFloat FloatReal, FloatImag;
692
693 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
694
695 void makeComplexFloat() { IsInt = false; }
696 bool isComplexFloat() const { return !IsInt; }
697 APFloat &getComplexFloatReal() { return FloatReal; }
698 APFloat &getComplexFloatImag() { return FloatImag; }
699
700 void makeComplexInt() { IsInt = true; }
701 bool isComplexInt() const { return IsInt; }
702 APSInt &getComplexIntReal() { return IntReal; }
703 APSInt &getComplexIntImag() { return IntImag; }
704
Richard Smith2e312c82012-03-03 22:46:17 +0000705 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000706 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000707 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000708 else
Richard Smith2e312c82012-03-03 22:46:17 +0000709 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000710 }
Richard Smith2e312c82012-03-03 22:46:17 +0000711 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000712 assert(v.isComplexFloat() || v.isComplexInt());
713 if (v.isComplexFloat()) {
714 makeComplexFloat();
715 FloatReal = v.getComplexFloatReal();
716 FloatImag = v.getComplexFloatImag();
717 } else {
718 makeComplexInt();
719 IntReal = v.getComplexIntReal();
720 IntImag = v.getComplexIntImag();
721 }
722 }
John McCall93d91dc2010-05-07 17:22:02 +0000723 };
John McCall45d55e42010-05-07 21:00:08 +0000724
725 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000726 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000727 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000728 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000729 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000730
Richard Smithce40ad62011-11-12 22:28:03 +0000731 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000732 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000733 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000734 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000735 SubobjectDesignator &getLValueDesignator() { return Designator; }
736 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000737
Richard Smith2e312c82012-03-03 22:46:17 +0000738 void moveInto(APValue &V) const {
739 if (Designator.Invalid)
740 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
741 else
742 V = APValue(Base, Offset, Designator.Entries,
743 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000744 }
Richard Smith2e312c82012-03-03 22:46:17 +0000745 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000746 assert(V.isLValue());
747 Base = V.getLValueBase();
748 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000749 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000750 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000751 }
752
Richard Smithb228a862012-02-15 02:18:13 +0000753 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000754 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000755 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000756 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000757 Designator = SubobjectDesignator(getType(B));
758 }
759
760 // Check that this LValue is not based on a null pointer. If it is, produce
761 // a diagnostic and mark the designator as invalid.
762 bool checkNullPointer(EvalInfo &Info, const Expr *E,
763 CheckSubobjectKind CSK) {
764 if (Designator.Invalid)
765 return false;
766 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000767 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000768 << CSK;
769 Designator.setInvalid();
770 return false;
771 }
772 return true;
773 }
774
775 // Check this LValue refers to an object. If not, set the designator to be
776 // invalid and emit a diagnostic.
777 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000778 // Outside C++11, do not build a designator referring to a subobject of
779 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000780 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000782 return checkNullPointer(Info, E, CSK) &&
783 Designator.checkSubobject(Info, E, CSK);
784 }
785
786 void addDecl(EvalInfo &Info, const Expr *E,
787 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000788 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
789 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000790 }
791 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000792 if (checkSubobject(Info, E, CSK_ArrayToPointer))
793 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000794 }
Richard Smith66c96992012-02-18 22:04:06 +0000795 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000796 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
797 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000798 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000799 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000800 if (checkNullPointer(Info, E, CSK_ArrayIndex))
801 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000802 }
John McCall45d55e42010-05-07 21:00:08 +0000803 };
Richard Smith027bf112011-11-17 22:56:20 +0000804
805 struct MemberPtr {
806 MemberPtr() {}
807 explicit MemberPtr(const ValueDecl *Decl) :
808 DeclAndIsDerivedMember(Decl, false), Path() {}
809
810 /// The member or (direct or indirect) field referred to by this member
811 /// pointer, or 0 if this is a null member pointer.
812 const ValueDecl *getDecl() const {
813 return DeclAndIsDerivedMember.getPointer();
814 }
815 /// Is this actually a member of some type derived from the relevant class?
816 bool isDerivedMember() const {
817 return DeclAndIsDerivedMember.getInt();
818 }
819 /// Get the class which the declaration actually lives in.
820 const CXXRecordDecl *getContainingRecord() const {
821 return cast<CXXRecordDecl>(
822 DeclAndIsDerivedMember.getPointer()->getDeclContext());
823 }
824
Richard Smith2e312c82012-03-03 22:46:17 +0000825 void moveInto(APValue &V) const {
826 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000827 }
Richard Smith2e312c82012-03-03 22:46:17 +0000828 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000829 assert(V.isMemberPointer());
830 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
831 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
832 Path.clear();
833 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
834 Path.insert(Path.end(), P.begin(), P.end());
835 }
836
837 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
838 /// whether the member is a member of some class derived from the class type
839 /// of the member pointer.
840 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
841 /// Path - The path of base/derived classes from the member declaration's
842 /// class (exclusive) to the class type of the member pointer (inclusive).
843 SmallVector<const CXXRecordDecl*, 4> Path;
844
845 /// Perform a cast towards the class of the Decl (either up or down the
846 /// hierarchy).
847 bool castBack(const CXXRecordDecl *Class) {
848 assert(!Path.empty());
849 const CXXRecordDecl *Expected;
850 if (Path.size() >= 2)
851 Expected = Path[Path.size() - 2];
852 else
853 Expected = getContainingRecord();
854 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
855 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
856 // if B does not contain the original member and is not a base or
857 // derived class of the class containing the original member, the result
858 // of the cast is undefined.
859 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
860 // (D::*). We consider that to be a language defect.
861 return false;
862 }
863 Path.pop_back();
864 return true;
865 }
866 /// Perform a base-to-derived member pointer cast.
867 bool castToDerived(const CXXRecordDecl *Derived) {
868 if (!getDecl())
869 return true;
870 if (!isDerivedMember()) {
871 Path.push_back(Derived);
872 return true;
873 }
874 if (!castBack(Derived))
875 return false;
876 if (Path.empty())
877 DeclAndIsDerivedMember.setInt(false);
878 return true;
879 }
880 /// Perform a derived-to-base member pointer cast.
881 bool castToBase(const CXXRecordDecl *Base) {
882 if (!getDecl())
883 return true;
884 if (Path.empty())
885 DeclAndIsDerivedMember.setInt(true);
886 if (isDerivedMember()) {
887 Path.push_back(Base);
888 return true;
889 }
890 return castBack(Base);
891 }
892 };
Richard Smith357362d2011-12-13 06:39:58 +0000893
Richard Smith7bb00672012-02-01 01:42:44 +0000894 /// Compare two member pointers, which are assumed to be of the same type.
895 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
896 if (!LHS.getDecl() || !RHS.getDecl())
897 return !LHS.getDecl() && !RHS.getDecl();
898 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
899 return false;
900 return LHS.Path == RHS.Path;
901 }
John McCall93d91dc2010-05-07 17:22:02 +0000902}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000903
Richard Smith2e312c82012-03-03 22:46:17 +0000904static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000905static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
906 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +0000907 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000908static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
909static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000910static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
911 EvalInfo &Info);
912static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000913static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000914static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000915 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000916static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000917static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000918
919//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000920// Misc utilities
921//===----------------------------------------------------------------------===//
922
Richard Smithd9f663b2013-04-22 15:31:51 +0000923/// Evaluate an expression to see if it had side-effects, and discard its
924/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +0000925/// \return \c true if the caller should keep evaluating.
926static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000927 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000928 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000929 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000930 return Info.keepEvaluatingAfterFailure();
931 }
932 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000933}
934
Richard Smith861b5b52013-05-07 23:34:45 +0000935/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
936/// return its existing value.
937static int64_t getExtValue(const APSInt &Value) {
938 return Value.isSigned() ? Value.getSExtValue()
939 : static_cast<int64_t>(Value.getZExtValue());
940}
941
Richard Smithd62306a2011-11-10 06:34:14 +0000942/// Should this call expression be treated as a string literal?
943static bool IsStringLiteralCall(const CallExpr *E) {
944 unsigned Builtin = E->isBuiltinCall();
945 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
946 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
947}
948
Richard Smithce40ad62011-11-12 22:28:03 +0000949static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000950 // C++11 [expr.const]p3 An address constant expression is a prvalue core
951 // constant expression of pointer type that evaluates to...
952
953 // ... a null pointer value, or a prvalue core constant expression of type
954 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000955 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000956
Richard Smithce40ad62011-11-12 22:28:03 +0000957 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
958 // ... the address of an object with static storage duration,
959 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
960 return VD->hasGlobalStorage();
961 // ... the address of a function,
962 return isa<FunctionDecl>(D);
963 }
964
965 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000966 switch (E->getStmtClass()) {
967 default:
968 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000969 case Expr::CompoundLiteralExprClass: {
970 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
971 return CLE->isFileScope() && CLE->isLValue();
972 }
Richard Smithd62306a2011-11-10 06:34:14 +0000973 // A string literal has static storage duration.
974 case Expr::StringLiteralClass:
975 case Expr::PredefinedExprClass:
976 case Expr::ObjCStringLiteralClass:
977 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000978 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000979 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000980 return true;
981 case Expr::CallExprClass:
982 return IsStringLiteralCall(cast<CallExpr>(E));
983 // For GCC compatibility, &&label has static storage duration.
984 case Expr::AddrLabelExprClass:
985 return true;
986 // A Block literal expression may be used as the initialization value for
987 // Block variables at global or local static scope.
988 case Expr::BlockExprClass:
989 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000990 case Expr::ImplicitValueInitExprClass:
991 // FIXME:
992 // We can never form an lvalue with an implicit value initialization as its
993 // base through expression evaluation, so these only appear in one case: the
994 // implicit variable declaration we invent when checking whether a constexpr
995 // constructor can produce a constant expression. We must assume that such
996 // an expression might be a global lvalue.
997 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000998 }
John McCall95007602010-05-10 23:27:23 +0000999}
1000
Richard Smithb228a862012-02-15 02:18:13 +00001001static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1002 assert(Base && "no location for a null lvalue");
1003 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1004 if (VD)
1005 Info.Note(VD->getLocation(), diag::note_declared_at);
1006 else
Ted Kremenek28831752012-08-23 20:46:57 +00001007 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001008 diag::note_constexpr_temporary_here);
1009}
1010
Richard Smith80815602011-11-07 05:07:52 +00001011/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001012/// value for an address or reference constant expression. Return true if we
1013/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001014static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1015 QualType Type, const LValue &LVal) {
1016 bool IsReferenceType = Type->isReferenceType();
1017
Richard Smith357362d2011-12-13 06:39:58 +00001018 APValue::LValueBase Base = LVal.getLValueBase();
1019 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1020
Richard Smith0dea49e2012-02-18 04:58:18 +00001021 // Check that the object is a global. Note that the fake 'this' object we
1022 // manufacture when checking potential constant expressions is conservatively
1023 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001024 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001025 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001026 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001027 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1028 << IsReferenceType << !Designator.Entries.empty()
1029 << !!VD << VD;
1030 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001031 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001032 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001033 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001034 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001035 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001036 }
Richard Smithb228a862012-02-15 02:18:13 +00001037 assert((Info.CheckingPotentialConstantExpression ||
1038 LVal.getLValueCallIndex() == 0) &&
1039 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001040
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001041 // Check if this is a thread-local variable.
1042 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1043 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001044 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001045 return false;
1046 }
1047 }
1048
Richard Smitha8105bc2012-01-06 16:39:00 +00001049 // Allow address constant expressions to be past-the-end pointers. This is
1050 // an extension: the standard requires them to point to an object.
1051 if (!IsReferenceType)
1052 return true;
1053
1054 // A reference constant expression must refer to an object.
1055 if (!Base) {
1056 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001057 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001058 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001059 }
1060
Richard Smith357362d2011-12-13 06:39:58 +00001061 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001062 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001063 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001064 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001065 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001066 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001067 }
1068
Richard Smith80815602011-11-07 05:07:52 +00001069 return true;
1070}
1071
Richard Smithfddd3842011-12-30 21:15:51 +00001072/// Check that this core constant expression is of literal type, and if not,
1073/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001074static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1075 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001076 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001077 return true;
1078
Richard Smith7525ff62013-05-09 07:14:00 +00001079 // C++1y: A constant initializer for an object o [...] may also invoke
1080 // constexpr constructors for o and its subobjects even if those objects
1081 // are of non-literal class types.
1082 if (Info.getLangOpts().CPlusPlus1y && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001083 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001084 return true;
1085
Richard Smithfddd3842011-12-30 21:15:51 +00001086 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001087 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001088 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001089 << E->getType();
1090 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001091 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001092 return false;
1093}
1094
Richard Smith0b0a0b62011-10-29 20:57:55 +00001095/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001096/// constant expression. If not, report an appropriate diagnostic. Does not
1097/// check that the expression is of literal type.
1098static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1099 QualType Type, const APValue &Value) {
1100 // Core issue 1454: For a literal constant expression of array or class type,
1101 // each subobject of its value shall have been initialized by a constant
1102 // expression.
1103 if (Value.isArray()) {
1104 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1105 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1106 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1107 Value.getArrayInitializedElt(I)))
1108 return false;
1109 }
1110 if (!Value.hasArrayFiller())
1111 return true;
1112 return CheckConstantExpression(Info, DiagLoc, EltTy,
1113 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001114 }
Richard Smithb228a862012-02-15 02:18:13 +00001115 if (Value.isUnion() && Value.getUnionField()) {
1116 return CheckConstantExpression(Info, DiagLoc,
1117 Value.getUnionField()->getType(),
1118 Value.getUnionValue());
1119 }
1120 if (Value.isStruct()) {
1121 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1122 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1123 unsigned BaseIndex = 0;
1124 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1125 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1126 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1127 Value.getStructBase(BaseIndex)))
1128 return false;
1129 }
1130 }
1131 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1132 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001133 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1134 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001135 return false;
1136 }
1137 }
1138
1139 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001140 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001141 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001142 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1143 }
1144
1145 // Everything else is fine.
1146 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001147}
1148
Richard Smith83c68212011-10-31 05:11:32 +00001149const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001150 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001151}
1152
1153static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001154 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001155}
1156
Richard Smithcecf1842011-11-01 21:06:14 +00001157static bool IsWeakLValue(const LValue &Value) {
1158 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001159 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001160}
1161
Richard Smith2e312c82012-03-03 22:46:17 +00001162static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001163 // A null base expression indicates a null pointer. These are always
1164 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001165 if (!Value.getLValueBase()) {
1166 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001167 return true;
1168 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001169
Richard Smith027bf112011-11-17 22:56:20 +00001170 // We have a non-null base. These are generally known to be true, but if it's
1171 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001172 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001173 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001174 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001175}
1176
Richard Smith2e312c82012-03-03 22:46:17 +00001177static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001178 switch (Val.getKind()) {
1179 case APValue::Uninitialized:
1180 return false;
1181 case APValue::Int:
1182 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001183 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001184 case APValue::Float:
1185 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001186 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001187 case APValue::ComplexInt:
1188 Result = Val.getComplexIntReal().getBoolValue() ||
1189 Val.getComplexIntImag().getBoolValue();
1190 return true;
1191 case APValue::ComplexFloat:
1192 Result = !Val.getComplexFloatReal().isZero() ||
1193 !Val.getComplexFloatImag().isZero();
1194 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001195 case APValue::LValue:
1196 return EvalPointerValueAsBool(Val, Result);
1197 case APValue::MemberPointer:
1198 Result = Val.getMemberPointerDecl();
1199 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001200 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001201 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001202 case APValue::Struct:
1203 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001204 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001205 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001206 }
1207
Richard Smith11562c52011-10-28 17:51:58 +00001208 llvm_unreachable("unknown APValue kind");
1209}
1210
1211static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1212 EvalInfo &Info) {
1213 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001214 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001215 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001216 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001217 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001218}
1219
Richard Smith357362d2011-12-13 06:39:58 +00001220template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001221static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001222 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001223 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001224 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001225}
1226
1227static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1228 QualType SrcType, const APFloat &Value,
1229 QualType DestType, APSInt &Result) {
1230 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001231 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001232 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001233
Richard Smith357362d2011-12-13 06:39:58 +00001234 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001235 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001236 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1237 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001238 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001239 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001240}
1241
Richard Smith357362d2011-12-13 06:39:58 +00001242static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1243 QualType SrcType, QualType DestType,
1244 APFloat &Result) {
1245 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001246 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001247 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1248 APFloat::rmNearestTiesToEven, &ignored)
1249 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001250 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001251 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001252}
1253
Richard Smith911e1422012-01-30 22:27:01 +00001254static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1255 QualType DestType, QualType SrcType,
1256 APSInt &Value) {
1257 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001258 APSInt Result = Value;
1259 // Figure out if this is a truncate, extend or noop cast.
1260 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001261 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001262 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001263 return Result;
1264}
1265
Richard Smith357362d2011-12-13 06:39:58 +00001266static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1267 QualType SrcType, const APSInt &Value,
1268 QualType DestType, APFloat &Result) {
1269 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1270 if (Result.convertFromAPInt(Value, Value.isSigned(),
1271 APFloat::rmNearestTiesToEven)
1272 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001273 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001274 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001275}
1276
Eli Friedman803acb32011-12-22 03:51:45 +00001277static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1278 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001279 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001280 if (!Evaluate(SVal, Info, E))
1281 return false;
1282 if (SVal.isInt()) {
1283 Res = SVal.getInt();
1284 return true;
1285 }
1286 if (SVal.isFloat()) {
1287 Res = SVal.getFloat().bitcastToAPInt();
1288 return true;
1289 }
1290 if (SVal.isVector()) {
1291 QualType VecTy = E->getType();
1292 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1293 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1294 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1295 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1296 Res = llvm::APInt::getNullValue(VecSize);
1297 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1298 APValue &Elt = SVal.getVectorElt(i);
1299 llvm::APInt EltAsInt;
1300 if (Elt.isInt()) {
1301 EltAsInt = Elt.getInt();
1302 } else if (Elt.isFloat()) {
1303 EltAsInt = Elt.getFloat().bitcastToAPInt();
1304 } else {
1305 // Don't try to handle vectors of anything other than int or float
1306 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001307 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001308 return false;
1309 }
1310 unsigned BaseEltSize = EltAsInt.getBitWidth();
1311 if (BigEndian)
1312 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1313 else
1314 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1315 }
1316 return true;
1317 }
1318 // Give up if the input isn't an int, float, or vector. For example, we
1319 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001320 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001321 return false;
1322}
1323
Richard Smith43e77732013-05-07 04:50:00 +00001324/// Perform the given integer operation, which is known to need at most BitWidth
1325/// bits, and check for overflow in the original type (if that type was not an
1326/// unsigned type).
1327template<typename Operation>
1328static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1329 const APSInt &LHS, const APSInt &RHS,
1330 unsigned BitWidth, Operation Op) {
1331 if (LHS.isUnsigned())
1332 return Op(LHS, RHS);
1333
1334 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1335 APSInt Result = Value.trunc(LHS.getBitWidth());
1336 if (Result.extend(BitWidth) != Value) {
1337 if (Info.getIntOverflowCheckMode())
1338 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1339 diag::warn_integer_constant_overflow)
1340 << Result.toString(10) << E->getType();
1341 else
1342 HandleOverflow(Info, E, Value, E->getType());
1343 }
1344 return Result;
1345}
1346
1347/// Perform the given binary integer operation.
1348static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1349 BinaryOperatorKind Opcode, APSInt RHS,
1350 APSInt &Result) {
1351 switch (Opcode) {
1352 default:
1353 Info.Diag(E);
1354 return false;
1355 case BO_Mul:
1356 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1357 std::multiplies<APSInt>());
1358 return true;
1359 case BO_Add:
1360 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1361 std::plus<APSInt>());
1362 return true;
1363 case BO_Sub:
1364 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1365 std::minus<APSInt>());
1366 return true;
1367 case BO_And: Result = LHS & RHS; return true;
1368 case BO_Xor: Result = LHS ^ RHS; return true;
1369 case BO_Or: Result = LHS | RHS; return true;
1370 case BO_Div:
1371 case BO_Rem:
1372 if (RHS == 0) {
1373 Info.Diag(E, diag::note_expr_divide_by_zero);
1374 return false;
1375 }
1376 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1377 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1378 LHS.isSigned() && LHS.isMinSignedValue())
1379 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1380 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1381 return true;
1382 case BO_Shl: {
1383 if (Info.getLangOpts().OpenCL)
1384 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1385 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1386 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1387 RHS.isUnsigned());
1388 else if (RHS.isSigned() && RHS.isNegative()) {
1389 // During constant-folding, a negative shift is an opposite shift. Such
1390 // a shift is not a constant expression.
1391 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1392 RHS = -RHS;
1393 goto shift_right;
1394 }
1395 shift_left:
1396 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1397 // the shifted type.
1398 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1399 if (SA != RHS) {
1400 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1401 << RHS << E->getType() << LHS.getBitWidth();
1402 } else if (LHS.isSigned()) {
1403 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1404 // operand, and must not overflow the corresponding unsigned type.
1405 if (LHS.isNegative())
1406 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1407 else if (LHS.countLeadingZeros() < SA)
1408 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1409 }
1410 Result = LHS << SA;
1411 return true;
1412 }
1413 case BO_Shr: {
1414 if (Info.getLangOpts().OpenCL)
1415 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1416 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1417 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1418 RHS.isUnsigned());
1419 else if (RHS.isSigned() && RHS.isNegative()) {
1420 // During constant-folding, a negative shift is an opposite shift. Such a
1421 // shift is not a constant expression.
1422 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1423 RHS = -RHS;
1424 goto shift_left;
1425 }
1426 shift_right:
1427 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1428 // shifted type.
1429 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1430 if (SA != RHS)
1431 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1432 << RHS << E->getType() << LHS.getBitWidth();
1433 Result = LHS >> SA;
1434 return true;
1435 }
1436
1437 case BO_LT: Result = LHS < RHS; return true;
1438 case BO_GT: Result = LHS > RHS; return true;
1439 case BO_LE: Result = LHS <= RHS; return true;
1440 case BO_GE: Result = LHS >= RHS; return true;
1441 case BO_EQ: Result = LHS == RHS; return true;
1442 case BO_NE: Result = LHS != RHS; return true;
1443 }
1444}
1445
Richard Smith861b5b52013-05-07 23:34:45 +00001446/// Perform the given binary floating-point operation, in-place, on LHS.
1447static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1448 APFloat &LHS, BinaryOperatorKind Opcode,
1449 const APFloat &RHS) {
1450 switch (Opcode) {
1451 default:
1452 Info.Diag(E);
1453 return false;
1454 case BO_Mul:
1455 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1456 break;
1457 case BO_Add:
1458 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1459 break;
1460 case BO_Sub:
1461 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1462 break;
1463 case BO_Div:
1464 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1465 break;
1466 }
1467
1468 if (LHS.isInfinity() || LHS.isNaN())
1469 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1470 return true;
1471}
1472
Richard Smitha8105bc2012-01-06 16:39:00 +00001473/// Cast an lvalue referring to a base subobject to a derived class, by
1474/// truncating the lvalue's path to the given length.
1475static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1476 const RecordDecl *TruncatedType,
1477 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001478 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001479
1480 // Check we actually point to a derived class object.
1481 if (TruncatedElements == D.Entries.size())
1482 return true;
1483 assert(TruncatedElements >= D.MostDerivedPathLength &&
1484 "not casting to a derived class");
1485 if (!Result.checkSubobject(Info, E, CSK_Derived))
1486 return false;
1487
1488 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001489 const RecordDecl *RD = TruncatedType;
1490 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001491 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001492 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1493 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001494 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001495 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001496 else
Richard Smithd62306a2011-11-10 06:34:14 +00001497 Result.Offset -= Layout.getBaseClassOffset(Base);
1498 RD = Base;
1499 }
Richard Smith027bf112011-11-17 22:56:20 +00001500 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001501 return true;
1502}
1503
John McCalld7bca762012-05-01 00:38:49 +00001504static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001505 const CXXRecordDecl *Derived,
1506 const CXXRecordDecl *Base,
1507 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001508 if (!RL) {
1509 if (Derived->isInvalidDecl()) return false;
1510 RL = &Info.Ctx.getASTRecordLayout(Derived);
1511 }
1512
Richard Smithd62306a2011-11-10 06:34:14 +00001513 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001514 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001515 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001516}
1517
Richard Smitha8105bc2012-01-06 16:39:00 +00001518static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001519 const CXXRecordDecl *DerivedDecl,
1520 const CXXBaseSpecifier *Base) {
1521 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1522
John McCalld7bca762012-05-01 00:38:49 +00001523 if (!Base->isVirtual())
1524 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001525
Richard Smitha8105bc2012-01-06 16:39:00 +00001526 SubobjectDesignator &D = Obj.Designator;
1527 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001528 return false;
1529
Richard Smitha8105bc2012-01-06 16:39:00 +00001530 // Extract most-derived object and corresponding type.
1531 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1532 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1533 return false;
1534
1535 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001536 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001537 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1538 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001539 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001540 return true;
1541}
1542
1543/// Update LVal to refer to the given field, which must be a member of the type
1544/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001545static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001546 const FieldDecl *FD,
1547 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001548 if (!RL) {
1549 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001550 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001551 }
Richard Smithd62306a2011-11-10 06:34:14 +00001552
1553 unsigned I = FD->getFieldIndex();
1554 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001555 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001556 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001557}
1558
Richard Smith1b78b3d2012-01-25 22:15:11 +00001559/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001560static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001561 LValue &LVal,
1562 const IndirectFieldDecl *IFD) {
1563 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1564 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001565 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1566 return false;
1567 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001568}
1569
Richard Smithd62306a2011-11-10 06:34:14 +00001570/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001571static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1572 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001573 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1574 // extension.
1575 if (Type->isVoidType() || Type->isFunctionType()) {
1576 Size = CharUnits::One();
1577 return true;
1578 }
1579
1580 if (!Type->isConstantSizeType()) {
1581 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001582 // FIXME: Better diagnostic.
1583 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001584 return false;
1585 }
1586
1587 Size = Info.Ctx.getTypeSizeInChars(Type);
1588 return true;
1589}
1590
1591/// Update a pointer value to model pointer arithmetic.
1592/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001593/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001594/// \param LVal - The pointer value to be updated.
1595/// \param EltTy - The pointee type represented by LVal.
1596/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001597static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1598 LValue &LVal, QualType EltTy,
1599 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001600 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001601 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001602 return false;
1603
1604 // Compute the new offset in the appropriate width.
1605 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001606 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001607 return true;
1608}
1609
Richard Smith66c96992012-02-18 22:04:06 +00001610/// Update an lvalue to refer to a component of a complex number.
1611/// \param Info - Information about the ongoing evaluation.
1612/// \param LVal - The lvalue to be updated.
1613/// \param EltTy - The complex number's component type.
1614/// \param Imag - False for the real component, true for the imaginary.
1615static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1616 LValue &LVal, QualType EltTy,
1617 bool Imag) {
1618 if (Imag) {
1619 CharUnits SizeOfComponent;
1620 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1621 return false;
1622 LVal.Offset += SizeOfComponent;
1623 }
1624 LVal.addComplex(Info, E, EltTy, Imag);
1625 return true;
1626}
1627
Richard Smith27908702011-10-24 17:54:18 +00001628/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001629///
1630/// \param Info Information about the ongoing evaluation.
1631/// \param E An expression to be used when printing diagnostics.
1632/// \param VD The variable whose initializer should be obtained.
1633/// \param Frame The frame in which the variable was created. Must be null
1634/// if this variable is not local to the evaluation.
1635/// \param Result Filled in with a pointer to the value of the variable.
1636static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1637 const VarDecl *VD, CallStackFrame *Frame,
1638 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001639 // If this is a parameter to an active constexpr function call, perform
1640 // argument substitution.
1641 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001642 // Assume arguments of a potential constant expression are unknown
1643 // constant expressions.
1644 if (Info.CheckingPotentialConstantExpression)
1645 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001646 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001647 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001648 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001649 }
Richard Smith3229b742013-05-05 21:17:10 +00001650 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001651 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001652 }
Richard Smith27908702011-10-24 17:54:18 +00001653
Richard Smithd9f663b2013-04-22 15:31:51 +00001654 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001655 if (Frame) {
1656 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001657 // If we've carried on past an unevaluatable local variable initializer,
1658 // we can't go any further. This can happen during potential constant
1659 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001660 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001661 }
1662
Richard Smithd0b4dd62011-12-19 06:19:21 +00001663 // Dig out the initializer, and use the declaration which it's attached to.
1664 const Expr *Init = VD->getAnyInitializer(VD);
1665 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001666 // If we're checking a potential constant expression, the variable could be
1667 // initialized later.
1668 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001669 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001670 return false;
1671 }
1672
Richard Smithd62306a2011-11-10 06:34:14 +00001673 // If we're currently evaluating the initializer of this declaration, use that
1674 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001675 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001676 Result = Info.EvaluatingDeclValue;
1677 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001678 }
1679
Richard Smithcecf1842011-11-01 21:06:14 +00001680 // Never evaluate the initializer of a weak variable. We can't be sure that
1681 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001682 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001683 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001684 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001685 }
Richard Smithcecf1842011-11-01 21:06:14 +00001686
Richard Smithd0b4dd62011-12-19 06:19:21 +00001687 // Check that we can fold the initializer. In C++, we will have already done
1688 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001689 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001690 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001691 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001692 Notes.size() + 1) << VD;
1693 Info.Note(VD->getLocation(), diag::note_declared_at);
1694 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001695 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001696 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001697 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001698 Notes.size() + 1) << VD;
1699 Info.Note(VD->getLocation(), diag::note_declared_at);
1700 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001701 }
Richard Smith27908702011-10-24 17:54:18 +00001702
Richard Smith3229b742013-05-05 21:17:10 +00001703 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001704 return true;
Richard Smith27908702011-10-24 17:54:18 +00001705}
1706
Richard Smith11562c52011-10-28 17:51:58 +00001707static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001708 Qualifiers Quals = T.getQualifiers();
1709 return Quals.hasConst() && !Quals.hasVolatile();
1710}
1711
Richard Smithe97cbd72011-11-11 04:05:33 +00001712/// Get the base index of the given base class within an APValue representing
1713/// the given derived class.
1714static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1715 const CXXRecordDecl *Base) {
1716 Base = Base->getCanonicalDecl();
1717 unsigned Index = 0;
1718 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1719 E = Derived->bases_end(); I != E; ++I, ++Index) {
1720 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1721 return Index;
1722 }
1723
1724 llvm_unreachable("base class missing from derived class's bases list");
1725}
1726
Richard Smith3da88fa2013-04-26 14:36:30 +00001727/// Extract the value of a character from a string literal.
1728static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1729 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001730 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001731 const StringLiteral *S = cast<StringLiteral>(Lit);
1732 const ConstantArrayType *CAT =
1733 Info.Ctx.getAsConstantArrayType(S->getType());
1734 assert(CAT && "string literal isn't an array");
1735 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001736 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001737
1738 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001739 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001740 if (Index < S->getLength())
1741 Value = S->getCodeUnit(Index);
1742 return Value;
1743}
1744
Richard Smith3da88fa2013-04-26 14:36:30 +00001745// Expand a string literal into an array of characters.
1746static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1747 APValue &Result) {
1748 const StringLiteral *S = cast<StringLiteral>(Lit);
1749 const ConstantArrayType *CAT =
1750 Info.Ctx.getAsConstantArrayType(S->getType());
1751 assert(CAT && "string literal isn't an array");
1752 QualType CharType = CAT->getElementType();
1753 assert(CharType->isIntegerType() && "unexpected character type");
1754
1755 unsigned Elts = CAT->getSize().getZExtValue();
1756 Result = APValue(APValue::UninitArray(),
1757 std::min(S->getLength(), Elts), Elts);
1758 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1759 CharType->isUnsignedIntegerType());
1760 if (Result.hasArrayFiller())
1761 Result.getArrayFiller() = APValue(Value);
1762 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1763 Value = S->getCodeUnit(I);
1764 Result.getArrayInitializedElt(I) = APValue(Value);
1765 }
1766}
1767
1768// Expand an array so that it has more than Index filled elements.
1769static void expandArray(APValue &Array, unsigned Index) {
1770 unsigned Size = Array.getArraySize();
1771 assert(Index < Size);
1772
1773 // Always at least double the number of elements for which we store a value.
1774 unsigned OldElts = Array.getArrayInitializedElts();
1775 unsigned NewElts = std::max(Index+1, OldElts * 2);
1776 NewElts = std::min(Size, std::max(NewElts, 8u));
1777
1778 // Copy the data across.
1779 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1780 for (unsigned I = 0; I != OldElts; ++I)
1781 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1782 for (unsigned I = OldElts; I != NewElts; ++I)
1783 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1784 if (NewValue.hasArrayFiller())
1785 NewValue.getArrayFiller() = Array.getArrayFiller();
1786 Array.swap(NewValue);
1787}
1788
Richard Smith861b5b52013-05-07 23:34:45 +00001789/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001790enum AccessKinds {
1791 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001792 AK_Assign,
1793 AK_Increment,
1794 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001795};
1796
Richard Smith3229b742013-05-05 21:17:10 +00001797/// A handle to a complete object (an object that is not a subobject of
1798/// another object).
1799struct CompleteObject {
1800 /// The value of the complete object.
1801 APValue *Value;
1802 /// The type of the complete object.
1803 QualType Type;
1804
1805 CompleteObject() : Value(0) {}
1806 CompleteObject(APValue *Value, QualType Type)
1807 : Value(Value), Type(Type) {
1808 assert(Value && "missing value for complete object");
1809 }
1810
David Blaikie7d170102013-05-15 07:37:26 +00001811 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00001812};
1813
Richard Smith3da88fa2013-04-26 14:36:30 +00001814/// Find the designated sub-object of an rvalue.
1815template<typename SubobjectHandler>
1816typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001817findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001818 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001819 if (Sub.Invalid)
1820 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001821 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001822 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001823 if (Info.getLangOpts().CPlusPlus11)
1824 Info.Diag(E, diag::note_constexpr_access_past_end)
1825 << handler.AccessKind;
1826 else
1827 Info.Diag(E);
1828 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001829 }
Richard Smith6804be52011-11-11 08:28:03 +00001830 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001831 return handler.found(*Obj.Value, Obj.Type);
1832 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001833 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001834 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001835
Richard Smith3229b742013-05-05 21:17:10 +00001836 APValue *O = Obj.Value;
1837 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001838 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001839 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001840 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001841 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001842 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001843 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001844 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001845 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001846 // Note, it should not be possible to form a pointer with a valid
1847 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001848 if (Info.getLangOpts().CPlusPlus11)
1849 Info.Diag(E, diag::note_constexpr_access_past_end)
1850 << handler.AccessKind;
1851 else
1852 Info.Diag(E);
1853 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001854 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001855
1856 ObjType = CAT->getElementType();
1857
Richard Smith14a94132012-02-17 03:35:37 +00001858 // An array object is represented as either an Array APValue or as an
1859 // LValue which refers to a string literal.
1860 if (O->isLValue()) {
1861 assert(I == N - 1 && "extracting subobject of character?");
1862 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001863 if (handler.AccessKind != AK_Read)
1864 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1865 *O);
1866 else
1867 return handler.foundString(*O, ObjType, Index);
1868 }
1869
1870 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001871 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001872 else if (handler.AccessKind != AK_Read) {
1873 expandArray(*O, Index);
1874 O = &O->getArrayInitializedElt(Index);
1875 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001876 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001877 } else if (ObjType->isAnyComplexType()) {
1878 // Next subobject is a complex number.
1879 uint64_t Index = Sub.Entries[I].ArrayIndex;
1880 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001881 if (Info.getLangOpts().CPlusPlus11)
1882 Info.Diag(E, diag::note_constexpr_access_past_end)
1883 << handler.AccessKind;
1884 else
1885 Info.Diag(E);
1886 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001887 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001888
1889 bool WasConstQualified = ObjType.isConstQualified();
1890 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1891 if (WasConstQualified)
1892 ObjType.addConst();
1893
Richard Smith66c96992012-02-18 22:04:06 +00001894 assert(I == N - 1 && "extracting subobject of scalar?");
1895 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001896 return handler.found(Index ? O->getComplexIntImag()
1897 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001898 } else {
1899 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001900 return handler.found(Index ? O->getComplexFloatImag()
1901 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001902 }
Richard Smithd62306a2011-11-10 06:34:14 +00001903 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001904 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001905 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001906 << Field;
1907 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001908 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001909 }
1910
Richard Smithd62306a2011-11-10 06:34:14 +00001911 // Next subobject is a class, struct or union field.
1912 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1913 if (RD->isUnion()) {
1914 const FieldDecl *UnionField = O->getUnionField();
1915 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001916 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001917 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1918 << handler.AccessKind << Field << !UnionField << UnionField;
1919 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001920 }
Richard Smithd62306a2011-11-10 06:34:14 +00001921 O = &O->getUnionValue();
1922 } else
1923 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001924
1925 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001926 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001927 if (WasConstQualified && !Field->isMutable())
1928 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001929
1930 if (ObjType.isVolatileQualified()) {
1931 if (Info.getLangOpts().CPlusPlus) {
1932 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001933 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1934 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001935 Info.Note(Field->getLocation(), diag::note_declared_at);
1936 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001937 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001938 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001939 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001940 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001941 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001942 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001943 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1944 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1945 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001946
1947 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001948 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001949 if (WasConstQualified)
1950 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001951 }
Richard Smithd62306a2011-11-10 06:34:14 +00001952
Richard Smithf57d8cb2011-12-09 22:58:01 +00001953 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001954 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001955 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1956 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001957 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001958 }
1959
Richard Smith3da88fa2013-04-26 14:36:30 +00001960 return handler.found(*O, ObjType);
1961}
1962
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001963namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001964struct ExtractSubobjectHandler {
1965 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001966 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001967
1968 static const AccessKinds AccessKind = AK_Read;
1969
1970 typedef bool result_type;
1971 bool failed() { return false; }
1972 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001973 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001974 return true;
1975 }
1976 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001977 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001978 return true;
1979 }
1980 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001981 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001982 return true;
1983 }
1984 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001985 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001986 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1987 return true;
1988 }
1989};
Richard Smith3229b742013-05-05 21:17:10 +00001990} // end anonymous namespace
1991
Richard Smith3da88fa2013-04-26 14:36:30 +00001992const AccessKinds ExtractSubobjectHandler::AccessKind;
1993
1994/// Extract the designated sub-object of an rvalue.
1995static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001996 const CompleteObject &Obj,
1997 const SubobjectDesignator &Sub,
1998 APValue &Result) {
1999 ExtractSubobjectHandler Handler = { Info, Result };
2000 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002001}
2002
Richard Smith3229b742013-05-05 21:17:10 +00002003namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002004struct ModifySubobjectHandler {
2005 EvalInfo &Info;
2006 APValue &NewVal;
2007 const Expr *E;
2008
2009 typedef bool result_type;
2010 static const AccessKinds AccessKind = AK_Assign;
2011
2012 bool checkConst(QualType QT) {
2013 // Assigning to a const object has undefined behavior.
2014 if (QT.isConstQualified()) {
2015 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2016 return false;
2017 }
2018 return true;
2019 }
2020
2021 bool failed() { return false; }
2022 bool found(APValue &Subobj, QualType SubobjType) {
2023 if (!checkConst(SubobjType))
2024 return false;
2025 // We've been given ownership of NewVal, so just swap it in.
2026 Subobj.swap(NewVal);
2027 return true;
2028 }
2029 bool found(APSInt &Value, QualType SubobjType) {
2030 if (!checkConst(SubobjType))
2031 return false;
2032 if (!NewVal.isInt()) {
2033 // Maybe trying to write a cast pointer value into a complex?
2034 Info.Diag(E);
2035 return false;
2036 }
2037 Value = NewVal.getInt();
2038 return true;
2039 }
2040 bool found(APFloat &Value, QualType SubobjType) {
2041 if (!checkConst(SubobjType))
2042 return false;
2043 Value = NewVal.getFloat();
2044 return true;
2045 }
2046 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2047 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2048 }
2049};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002050} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002051
Richard Smith3229b742013-05-05 21:17:10 +00002052const AccessKinds ModifySubobjectHandler::AccessKind;
2053
Richard Smith3da88fa2013-04-26 14:36:30 +00002054/// Update the designated sub-object of an rvalue to the given value.
2055static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002056 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002057 const SubobjectDesignator &Sub,
2058 APValue &NewVal) {
2059 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002060 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002061}
2062
Richard Smith84f6dcf2012-02-02 01:16:57 +00002063/// Find the position where two subobject designators diverge, or equivalently
2064/// the length of the common initial subsequence.
2065static unsigned FindDesignatorMismatch(QualType ObjType,
2066 const SubobjectDesignator &A,
2067 const SubobjectDesignator &B,
2068 bool &WasArrayIndex) {
2069 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2070 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002071 if (!ObjType.isNull() &&
2072 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002073 // Next subobject is an array element.
2074 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2075 WasArrayIndex = true;
2076 return I;
2077 }
Richard Smith66c96992012-02-18 22:04:06 +00002078 if (ObjType->isAnyComplexType())
2079 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2080 else
2081 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002082 } else {
2083 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2084 WasArrayIndex = false;
2085 return I;
2086 }
2087 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2088 // Next subobject is a field.
2089 ObjType = FD->getType();
2090 else
2091 // Next subobject is a base class.
2092 ObjType = QualType();
2093 }
2094 }
2095 WasArrayIndex = false;
2096 return I;
2097}
2098
2099/// Determine whether the given subobject designators refer to elements of the
2100/// same array object.
2101static bool AreElementsOfSameArray(QualType ObjType,
2102 const SubobjectDesignator &A,
2103 const SubobjectDesignator &B) {
2104 if (A.Entries.size() != B.Entries.size())
2105 return false;
2106
2107 bool IsArray = A.MostDerivedArraySize != 0;
2108 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2109 // A is a subobject of the array element.
2110 return false;
2111
2112 // If A (and B) designates an array element, the last entry will be the array
2113 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2114 // of length 1' case, and the entire path must match.
2115 bool WasArrayIndex;
2116 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2117 return CommonLength >= A.Entries.size() - IsArray;
2118}
2119
Richard Smith3229b742013-05-05 21:17:10 +00002120/// Find the complete object to which an LValue refers.
2121CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2122 const LValue &LVal, QualType LValType) {
2123 if (!LVal.Base) {
2124 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2125 return CompleteObject();
2126 }
2127
2128 CallStackFrame *Frame = 0;
2129 if (LVal.CallIndex) {
2130 Frame = Info.getCallFrame(LVal.CallIndex);
2131 if (!Frame) {
2132 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2133 << AK << LVal.Base.is<const ValueDecl*>();
2134 NoteLValueLocation(Info, LVal.Base);
2135 return CompleteObject();
2136 }
Richard Smith3229b742013-05-05 21:17:10 +00002137 }
2138
2139 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2140 // is not a constant expression (even if the object is non-volatile). We also
2141 // apply this rule to C++98, in order to conform to the expected 'volatile'
2142 // semantics.
2143 if (LValType.isVolatileQualified()) {
2144 if (Info.getLangOpts().CPlusPlus)
2145 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2146 << AK << LValType;
2147 else
2148 Info.Diag(E);
2149 return CompleteObject();
2150 }
2151
2152 // Compute value storage location and type of base object.
2153 APValue *BaseVal = 0;
2154 QualType BaseType;
2155
2156 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2157 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2158 // In C++11, constexpr, non-volatile variables initialized with constant
2159 // expressions are constant expressions too. Inside constexpr functions,
2160 // parameters are constant expressions even if they're non-const.
2161 // In C++1y, objects local to a constant expression (those with a Frame) are
2162 // both readable and writable inside constant expressions.
2163 // In C, such things can also be folded, although they are not ICEs.
2164 const VarDecl *VD = dyn_cast<VarDecl>(D);
2165 if (VD) {
2166 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2167 VD = VDef;
2168 }
2169 if (!VD || VD->isInvalidDecl()) {
2170 Info.Diag(E);
2171 return CompleteObject();
2172 }
2173
2174 // Accesses of volatile-qualified objects are not allowed.
2175 BaseType = VD->getType();
2176 if (BaseType.isVolatileQualified()) {
2177 if (Info.getLangOpts().CPlusPlus) {
2178 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2179 << AK << 1 << VD;
2180 Info.Note(VD->getLocation(), diag::note_declared_at);
2181 } else {
2182 Info.Diag(E);
2183 }
2184 return CompleteObject();
2185 }
2186
2187 // Unless we're looking at a local variable or argument in a constexpr call,
2188 // the variable we're reading must be const.
2189 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002190 if (Info.getLangOpts().CPlusPlus1y &&
2191 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2192 // OK, we can read and modify an object if we're in the process of
2193 // evaluating its initializer, because its lifetime began in this
2194 // evaluation.
2195 } else if (AK != AK_Read) {
2196 // All the remaining cases only permit reading.
2197 Info.Diag(E, diag::note_constexpr_modify_global);
2198 return CompleteObject();
2199 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002200 // OK, we can read this variable.
2201 } else if (BaseType->isIntegralOrEnumerationType()) {
2202 if (!BaseType.isConstQualified()) {
2203 if (Info.getLangOpts().CPlusPlus) {
2204 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2205 Info.Note(VD->getLocation(), diag::note_declared_at);
2206 } else {
2207 Info.Diag(E);
2208 }
2209 return CompleteObject();
2210 }
2211 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2212 // We support folding of const floating-point types, in order to make
2213 // static const data members of such types (supported as an extension)
2214 // more useful.
2215 if (Info.getLangOpts().CPlusPlus11) {
2216 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2217 Info.Note(VD->getLocation(), diag::note_declared_at);
2218 } else {
2219 Info.CCEDiag(E);
2220 }
2221 } else {
2222 // FIXME: Allow folding of values of any literal type in all languages.
2223 if (Info.getLangOpts().CPlusPlus11) {
2224 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2225 Info.Note(VD->getLocation(), diag::note_declared_at);
2226 } else {
2227 Info.Diag(E);
2228 }
2229 return CompleteObject();
2230 }
2231 }
2232
2233 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2234 return CompleteObject();
2235 } else {
2236 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2237
2238 if (!Frame) {
2239 Info.Diag(E);
2240 return CompleteObject();
2241 }
2242
2243 BaseType = Base->getType();
2244 BaseVal = &Frame->Temporaries[Base];
2245
2246 // Volatile temporary objects cannot be accessed in constant expressions.
2247 if (BaseType.isVolatileQualified()) {
2248 if (Info.getLangOpts().CPlusPlus) {
2249 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2250 << AK << 0;
2251 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2252 } else {
2253 Info.Diag(E);
2254 }
2255 return CompleteObject();
2256 }
2257 }
2258
Richard Smith7525ff62013-05-09 07:14:00 +00002259 // During the construction of an object, it is not yet 'const'.
2260 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2261 // and this doesn't do quite the right thing for const subobjects of the
2262 // object under construction.
2263 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2264 BaseType = Info.Ctx.getCanonicalType(BaseType);
2265 BaseType.removeLocalConst();
2266 }
2267
Richard Smith3229b742013-05-05 21:17:10 +00002268 // In C++1y, we can't safely access any mutable state when checking a
2269 // potential constant expression.
2270 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2271 Info.CheckingPotentialConstantExpression)
2272 return CompleteObject();
2273
2274 return CompleteObject(BaseVal, BaseType);
2275}
2276
Richard Smith243ef902013-05-05 23:31:59 +00002277/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2278/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2279/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002280///
2281/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002282/// \param Conv - The expression for which we are performing the conversion.
2283/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002284/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2285/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002286/// \param LVal - The glvalue on which we are attempting to perform this action.
2287/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002288static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002289 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002290 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002291 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002292 return false;
2293
Richard Smith3229b742013-05-05 21:17:10 +00002294 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002295 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002296 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2297 !Type.isVolatileQualified()) {
2298 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2299 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2300 // initializer until now for such expressions. Such an expression can't be
2301 // an ICE in C, so this only matters for fold.
2302 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2303 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002304 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002305 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002306 }
Richard Smith3229b742013-05-05 21:17:10 +00002307 APValue Lit;
2308 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2309 return false;
2310 CompleteObject LitObj(&Lit, Base->getType());
2311 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2312 } else if (isa<StringLiteral>(Base)) {
2313 // We represent a string literal array as an lvalue pointing at the
2314 // corresponding expression, rather than building an array of chars.
2315 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2316 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2317 CompleteObject StrObj(&Str, Base->getType());
2318 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002319 }
Richard Smith11562c52011-10-28 17:51:58 +00002320 }
2321
Richard Smith3229b742013-05-05 21:17:10 +00002322 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2323 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002324}
2325
2326/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002327static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002328 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002329 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002330 return false;
2331
Richard Smith3229b742013-05-05 21:17:10 +00002332 if (!Info.getLangOpts().CPlusPlus1y) {
2333 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002334 return false;
2335 }
2336
Richard Smith3229b742013-05-05 21:17:10 +00002337 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2338 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002339}
2340
Richard Smith243ef902013-05-05 23:31:59 +00002341static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2342 return T->isSignedIntegerType() &&
2343 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2344}
2345
2346namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002347struct CompoundAssignSubobjectHandler {
2348 EvalInfo &Info;
2349 const Expr *E;
2350 QualType PromotedLHSType;
2351 BinaryOperatorKind Opcode;
2352 const APValue &RHS;
2353
2354 static const AccessKinds AccessKind = AK_Assign;
2355
2356 typedef bool result_type;
2357
2358 bool checkConst(QualType QT) {
2359 // Assigning to a const object has undefined behavior.
2360 if (QT.isConstQualified()) {
2361 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2362 return false;
2363 }
2364 return true;
2365 }
2366
2367 bool failed() { return false; }
2368 bool found(APValue &Subobj, QualType SubobjType) {
2369 switch (Subobj.getKind()) {
2370 case APValue::Int:
2371 return found(Subobj.getInt(), SubobjType);
2372 case APValue::Float:
2373 return found(Subobj.getFloat(), SubobjType);
2374 case APValue::ComplexInt:
2375 case APValue::ComplexFloat:
2376 // FIXME: Implement complex compound assignment.
2377 Info.Diag(E);
2378 return false;
2379 case APValue::LValue:
2380 return foundPointer(Subobj, SubobjType);
2381 default:
2382 // FIXME: can this happen?
2383 Info.Diag(E);
2384 return false;
2385 }
2386 }
2387 bool found(APSInt &Value, QualType SubobjType) {
2388 if (!checkConst(SubobjType))
2389 return false;
2390
2391 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2392 // We don't support compound assignment on integer-cast-to-pointer
2393 // values.
2394 Info.Diag(E);
2395 return false;
2396 }
2397
2398 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2399 SubobjType, Value);
2400 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2401 return false;
2402 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2403 return true;
2404 }
2405 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002406 return checkConst(SubobjType) &&
2407 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2408 Value) &&
2409 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2410 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002411 }
2412 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2413 if (!checkConst(SubobjType))
2414 return false;
2415
2416 QualType PointeeType;
2417 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2418 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002419
2420 if (PointeeType.isNull() || !RHS.isInt() ||
2421 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002422 Info.Diag(E);
2423 return false;
2424 }
2425
Richard Smith861b5b52013-05-07 23:34:45 +00002426 int64_t Offset = getExtValue(RHS.getInt());
2427 if (Opcode == BO_Sub)
2428 Offset = -Offset;
2429
2430 LValue LVal;
2431 LVal.setFrom(Info.Ctx, Subobj);
2432 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2433 return false;
2434 LVal.moveInto(Subobj);
2435 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002436 }
2437 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2438 llvm_unreachable("shouldn't encounter string elements here");
2439 }
2440};
2441} // end anonymous namespace
2442
2443const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2444
2445/// Perform a compound assignment of LVal <op>= RVal.
2446static bool handleCompoundAssignment(
2447 EvalInfo &Info, const Expr *E,
2448 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2449 BinaryOperatorKind Opcode, const APValue &RVal) {
2450 if (LVal.Designator.Invalid)
2451 return false;
2452
2453 if (!Info.getLangOpts().CPlusPlus1y) {
2454 Info.Diag(E);
2455 return false;
2456 }
2457
2458 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2459 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2460 RVal };
2461 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2462}
2463
2464namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002465struct IncDecSubobjectHandler {
2466 EvalInfo &Info;
2467 const Expr *E;
2468 AccessKinds AccessKind;
2469 APValue *Old;
2470
2471 typedef bool result_type;
2472
2473 bool checkConst(QualType QT) {
2474 // Assigning to a const object has undefined behavior.
2475 if (QT.isConstQualified()) {
2476 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2477 return false;
2478 }
2479 return true;
2480 }
2481
2482 bool failed() { return false; }
2483 bool found(APValue &Subobj, QualType SubobjType) {
2484 // Stash the old value. Also clear Old, so we don't clobber it later
2485 // if we're post-incrementing a complex.
2486 if (Old) {
2487 *Old = Subobj;
2488 Old = 0;
2489 }
2490
2491 switch (Subobj.getKind()) {
2492 case APValue::Int:
2493 return found(Subobj.getInt(), SubobjType);
2494 case APValue::Float:
2495 return found(Subobj.getFloat(), SubobjType);
2496 case APValue::ComplexInt:
2497 return found(Subobj.getComplexIntReal(),
2498 SubobjType->castAs<ComplexType>()->getElementType()
2499 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2500 case APValue::ComplexFloat:
2501 return found(Subobj.getComplexFloatReal(),
2502 SubobjType->castAs<ComplexType>()->getElementType()
2503 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2504 case APValue::LValue:
2505 return foundPointer(Subobj, SubobjType);
2506 default:
2507 // FIXME: can this happen?
2508 Info.Diag(E);
2509 return false;
2510 }
2511 }
2512 bool found(APSInt &Value, QualType SubobjType) {
2513 if (!checkConst(SubobjType))
2514 return false;
2515
2516 if (!SubobjType->isIntegerType()) {
2517 // We don't support increment / decrement on integer-cast-to-pointer
2518 // values.
2519 Info.Diag(E);
2520 return false;
2521 }
2522
2523 if (Old) *Old = APValue(Value);
2524
2525 // bool arithmetic promotes to int, and the conversion back to bool
2526 // doesn't reduce mod 2^n, so special-case it.
2527 if (SubobjType->isBooleanType()) {
2528 if (AccessKind == AK_Increment)
2529 Value = 1;
2530 else
2531 Value = !Value;
2532 return true;
2533 }
2534
2535 bool WasNegative = Value.isNegative();
2536 if (AccessKind == AK_Increment) {
2537 ++Value;
2538
2539 if (!WasNegative && Value.isNegative() &&
2540 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2541 APSInt ActualValue(Value, /*IsUnsigned*/true);
2542 HandleOverflow(Info, E, ActualValue, SubobjType);
2543 }
2544 } else {
2545 --Value;
2546
2547 if (WasNegative && !Value.isNegative() &&
2548 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2549 unsigned BitWidth = Value.getBitWidth();
2550 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2551 ActualValue.setBit(BitWidth);
2552 HandleOverflow(Info, E, ActualValue, SubobjType);
2553 }
2554 }
2555 return true;
2556 }
2557 bool found(APFloat &Value, QualType SubobjType) {
2558 if (!checkConst(SubobjType))
2559 return false;
2560
2561 if (Old) *Old = APValue(Value);
2562
2563 APFloat One(Value.getSemantics(), 1);
2564 if (AccessKind == AK_Increment)
2565 Value.add(One, APFloat::rmNearestTiesToEven);
2566 else
2567 Value.subtract(One, APFloat::rmNearestTiesToEven);
2568 return true;
2569 }
2570 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2571 if (!checkConst(SubobjType))
2572 return false;
2573
2574 QualType PointeeType;
2575 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2576 PointeeType = PT->getPointeeType();
2577 else {
2578 Info.Diag(E);
2579 return false;
2580 }
2581
2582 LValue LVal;
2583 LVal.setFrom(Info.Ctx, Subobj);
2584 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2585 AccessKind == AK_Increment ? 1 : -1))
2586 return false;
2587 LVal.moveInto(Subobj);
2588 return true;
2589 }
2590 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2591 llvm_unreachable("shouldn't encounter string elements here");
2592 }
2593};
2594} // end anonymous namespace
2595
2596/// Perform an increment or decrement on LVal.
2597static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2598 QualType LValType, bool IsIncrement, APValue *Old) {
2599 if (LVal.Designator.Invalid)
2600 return false;
2601
2602 if (!Info.getLangOpts().CPlusPlus1y) {
2603 Info.Diag(E);
2604 return false;
2605 }
2606
2607 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2608 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2609 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2610 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2611}
2612
Richard Smithe97cbd72011-11-11 04:05:33 +00002613/// Build an lvalue for the object argument of a member function call.
2614static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2615 LValue &This) {
2616 if (Object->getType()->isPointerType())
2617 return EvaluatePointer(Object, This, Info);
2618
2619 if (Object->isGLValue())
2620 return EvaluateLValue(Object, This, Info);
2621
Richard Smithd9f663b2013-04-22 15:31:51 +00002622 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002623 return EvaluateTemporary(Object, This, Info);
2624
2625 return false;
2626}
2627
2628/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2629/// lvalue referring to the result.
2630///
2631/// \param Info - Information about the ongoing evaluation.
2632/// \param BO - The member pointer access operation.
2633/// \param LV - Filled in with a reference to the resulting object.
2634/// \param IncludeMember - Specifies whether the member itself is included in
2635/// the resulting LValue subobject designator. This is not possible when
2636/// creating a bound member function.
2637/// \return The field or method declaration to which the member pointer refers,
2638/// or 0 if evaluation fails.
2639static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2640 const BinaryOperator *BO,
2641 LValue &LV,
2642 bool IncludeMember = true) {
2643 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2644
Richard Smith253c2a32012-01-27 01:14:48 +00002645 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2646 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002647 return 0;
2648
2649 MemberPtr MemPtr;
2650 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2651 return 0;
2652
2653 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2654 // member value, the behavior is undefined.
2655 if (!MemPtr.getDecl())
2656 return 0;
2657
Richard Smith253c2a32012-01-27 01:14:48 +00002658 if (!EvalObjOK)
2659 return 0;
2660
Richard Smith027bf112011-11-17 22:56:20 +00002661 if (MemPtr.isDerivedMember()) {
2662 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002663 // The end of the derived-to-base path for the base object must match the
2664 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002665 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002666 LV.Designator.Entries.size())
2667 return 0;
2668 unsigned PathLengthToMember =
2669 LV.Designator.Entries.size() - MemPtr.Path.size();
2670 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2671 const CXXRecordDecl *LVDecl = getAsBaseClass(
2672 LV.Designator.Entries[PathLengthToMember + I]);
2673 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2674 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2675 return 0;
2676 }
2677
2678 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002679 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2680 PathLengthToMember))
2681 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002682 } else if (!MemPtr.Path.empty()) {
2683 // Extend the LValue path with the member pointer's path.
2684 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2685 MemPtr.Path.size() + IncludeMember);
2686
2687 // Walk down to the appropriate base class.
2688 QualType LVType = BO->getLHS()->getType();
2689 if (const PointerType *PT = LVType->getAs<PointerType>())
2690 LVType = PT->getPointeeType();
2691 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2692 assert(RD && "member pointer access on non-class-type expression");
2693 // The first class in the path is that of the lvalue.
2694 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2695 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002696 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2697 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002698 RD = Base;
2699 }
2700 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002701 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2702 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002703 }
2704
2705 // Add the member. Note that we cannot build bound member functions here.
2706 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002707 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2708 if (!HandleLValueMember(Info, BO, LV, FD))
2709 return 0;
2710 } else if (const IndirectFieldDecl *IFD =
2711 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2712 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2713 return 0;
2714 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002715 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002716 }
Richard Smith027bf112011-11-17 22:56:20 +00002717 }
2718
2719 return MemPtr.getDecl();
2720}
2721
2722/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2723/// the provided lvalue, which currently refers to the base object.
2724static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2725 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002726 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002727 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002728 return false;
2729
Richard Smitha8105bc2012-01-06 16:39:00 +00002730 QualType TargetQT = E->getType();
2731 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2732 TargetQT = PT->getPointeeType();
2733
2734 // Check this cast lands within the final derived-to-base subobject path.
2735 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002736 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002737 << D.MostDerivedType << TargetQT;
2738 return false;
2739 }
2740
Richard Smith027bf112011-11-17 22:56:20 +00002741 // Check the type of the final cast. We don't need to check the path,
2742 // since a cast can only be formed if the path is unique.
2743 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002744 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2745 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002746 if (NewEntriesSize == D.MostDerivedPathLength)
2747 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2748 else
Richard Smith027bf112011-11-17 22:56:20 +00002749 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002750 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002751 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002752 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002753 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002754 }
Richard Smith027bf112011-11-17 22:56:20 +00002755
2756 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002757 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002758}
2759
Mike Stump876387b2009-10-27 22:09:17 +00002760namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002761enum EvalStmtResult {
2762 /// Evaluation failed.
2763 ESR_Failed,
2764 /// Hit a 'return' statement.
2765 ESR_Returned,
2766 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002767 ESR_Succeeded,
2768 /// Hit a 'continue' statement.
2769 ESR_Continue,
2770 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00002771 ESR_Break,
2772 /// Still scanning for 'case' or 'default' statement.
2773 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00002774};
2775}
2776
Richard Smithd9f663b2013-04-22 15:31:51 +00002777static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2778 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2779 // We don't need to evaluate the initializer for a static local.
2780 if (!VD->hasLocalStorage())
2781 return true;
2782
2783 LValue Result;
2784 Result.set(VD, Info.CurrentCall->Index);
2785 APValue &Val = Info.CurrentCall->Temporaries[VD];
2786
2787 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2788 // Wipe out any partially-computed value, to allow tracking that this
2789 // evaluation failed.
2790 Val = APValue();
2791 return false;
2792 }
2793 }
2794
2795 return true;
2796}
2797
Richard Smith4e18ca52013-05-06 05:56:11 +00002798/// Evaluate a condition (either a variable declaration or an expression).
2799static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2800 const Expr *Cond, bool &Result) {
2801 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2802 return false;
2803 return EvaluateAsBooleanCondition(Cond, Result, Info);
2804}
2805
2806static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002807 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00002808
2809/// Evaluate the body of a loop, and translate the result as appropriate.
2810static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002811 const Stmt *Body,
2812 const SwitchCase *Case = 0) {
2813 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00002814 case ESR_Break:
2815 return ESR_Succeeded;
2816 case ESR_Succeeded:
2817 case ESR_Continue:
2818 return ESR_Continue;
2819 case ESR_Failed:
2820 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00002821 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00002822 return ESR;
2823 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002824 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002825}
2826
Richard Smith496ddcf2013-05-12 17:32:42 +00002827/// Evaluate a switch statement.
2828static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
2829 const SwitchStmt *SS) {
2830 // Evaluate the switch condition.
2831 if (SS->getConditionVariable() &&
2832 !EvaluateDecl(Info, SS->getConditionVariable()))
2833 return ESR_Failed;
2834 APSInt Value;
2835 if (!EvaluateInteger(SS->getCond(), Value, Info))
2836 return ESR_Failed;
2837
2838 // Find the switch case corresponding to the value of the condition.
2839 // FIXME: Cache this lookup.
2840 const SwitchCase *Found = 0;
2841 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
2842 SC = SC->getNextSwitchCase()) {
2843 if (isa<DefaultStmt>(SC)) {
2844 Found = SC;
2845 continue;
2846 }
2847
2848 const CaseStmt *CS = cast<CaseStmt>(SC);
2849 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
2850 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
2851 : LHS;
2852 if (LHS <= Value && Value <= RHS) {
2853 Found = SC;
2854 break;
2855 }
2856 }
2857
2858 if (!Found)
2859 return ESR_Succeeded;
2860
2861 // Search the switch body for the switch case and evaluate it from there.
2862 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
2863 case ESR_Break:
2864 return ESR_Succeeded;
2865 case ESR_Succeeded:
2866 case ESR_Continue:
2867 case ESR_Failed:
2868 case ESR_Returned:
2869 return ESR;
2870 case ESR_CaseNotFound:
Richard Smith496ddcf2013-05-12 17:32:42 +00002871 llvm_unreachable("couldn't find switch case");
2872 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00002873 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00002874}
2875
Richard Smith254a73d2011-10-28 22:34:42 +00002876// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002877static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002878 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00002879 if (!Info.nextStep(S))
2880 return ESR_Failed;
2881
Richard Smith496ddcf2013-05-12 17:32:42 +00002882 // If we're hunting down a 'case' or 'default' label, recurse through
2883 // substatements until we hit the label.
2884 if (Case) {
2885 // FIXME: We don't start the lifetime of objects whose initialization we
2886 // jump over. However, such objects must be of class type with a trivial
2887 // default constructor that initialize all subobjects, so must be empty,
2888 // so this almost never matters.
2889 switch (S->getStmtClass()) {
2890 case Stmt::CompoundStmtClass:
2891 // FIXME: Precompute which substatement of a compound statement we
2892 // would jump to, and go straight there rather than performing a
2893 // linear scan each time.
2894 case Stmt::LabelStmtClass:
2895 case Stmt::AttributedStmtClass:
2896 case Stmt::DoStmtClass:
2897 break;
2898
2899 case Stmt::CaseStmtClass:
2900 case Stmt::DefaultStmtClass:
2901 if (Case == S)
2902 Case = 0;
2903 break;
2904
2905 case Stmt::IfStmtClass: {
2906 // FIXME: Precompute which side of an 'if' we would jump to, and go
2907 // straight there rather than scanning both sides.
2908 const IfStmt *IS = cast<IfStmt>(S);
2909 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
2910 if (ESR != ESR_CaseNotFound || !IS->getElse())
2911 return ESR;
2912 return EvaluateStmt(Result, Info, IS->getElse(), Case);
2913 }
2914
2915 case Stmt::WhileStmtClass: {
2916 EvalStmtResult ESR =
2917 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
2918 if (ESR != ESR_Continue)
2919 return ESR;
2920 break;
2921 }
2922
2923 case Stmt::ForStmtClass: {
2924 const ForStmt *FS = cast<ForStmt>(S);
2925 EvalStmtResult ESR =
2926 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
2927 if (ESR != ESR_Continue)
2928 return ESR;
2929 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2930 return ESR_Failed;
2931 break;
2932 }
2933
2934 case Stmt::DeclStmtClass:
2935 // FIXME: If the variable has initialization that can't be jumped over,
2936 // bail out of any immediately-surrounding compound-statement too.
2937 default:
2938 return ESR_CaseNotFound;
2939 }
2940 }
2941
Richard Smithd9f663b2013-04-22 15:31:51 +00002942 // FIXME: Mark all temporaries in the current frame as destroyed at
2943 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002944 switch (S->getStmtClass()) {
2945 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002946 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002947 // Don't bother evaluating beyond an expression-statement which couldn't
2948 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00002949 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00002950 return ESR_Failed;
2951 return ESR_Succeeded;
2952 }
2953
2954 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002955 return ESR_Failed;
2956
2957 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002958 return ESR_Succeeded;
2959
Richard Smithd9f663b2013-04-22 15:31:51 +00002960 case Stmt::DeclStmtClass: {
2961 const DeclStmt *DS = cast<DeclStmt>(S);
2962 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2963 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2964 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2965 return ESR_Failed;
2966 return ESR_Succeeded;
2967 }
2968
Richard Smith357362d2011-12-13 06:39:58 +00002969 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002970 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002971 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002972 return ESR_Failed;
2973 return ESR_Returned;
2974 }
Richard Smith254a73d2011-10-28 22:34:42 +00002975
2976 case Stmt::CompoundStmtClass: {
2977 const CompoundStmt *CS = cast<CompoundStmt>(S);
2978 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2979 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00002980 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
2981 if (ESR == ESR_Succeeded)
2982 Case = 0;
2983 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00002984 return ESR;
2985 }
Richard Smith496ddcf2013-05-12 17:32:42 +00002986 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00002987 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002988
2989 case Stmt::IfStmtClass: {
2990 const IfStmt *IS = cast<IfStmt>(S);
2991
2992 // Evaluate the condition, as either a var decl or as an expression.
2993 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00002994 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00002995 return ESR_Failed;
2996
2997 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2998 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2999 if (ESR != ESR_Succeeded)
3000 return ESR;
3001 }
3002 return ESR_Succeeded;
3003 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003004
3005 case Stmt::WhileStmtClass: {
3006 const WhileStmt *WS = cast<WhileStmt>(S);
3007 while (true) {
3008 bool Continue;
3009 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3010 Continue))
3011 return ESR_Failed;
3012 if (!Continue)
3013 break;
3014
3015 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3016 if (ESR != ESR_Continue)
3017 return ESR;
3018 }
3019 return ESR_Succeeded;
3020 }
3021
3022 case Stmt::DoStmtClass: {
3023 const DoStmt *DS = cast<DoStmt>(S);
3024 bool Continue;
3025 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003026 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003027 if (ESR != ESR_Continue)
3028 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003029 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003030
3031 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3032 return ESR_Failed;
3033 } while (Continue);
3034 return ESR_Succeeded;
3035 }
3036
3037 case Stmt::ForStmtClass: {
3038 const ForStmt *FS = cast<ForStmt>(S);
3039 if (FS->getInit()) {
3040 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3041 if (ESR != ESR_Succeeded)
3042 return ESR;
3043 }
3044 while (true) {
3045 bool Continue = true;
3046 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3047 FS->getCond(), Continue))
3048 return ESR_Failed;
3049 if (!Continue)
3050 break;
3051
3052 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3053 if (ESR != ESR_Continue)
3054 return ESR;
3055
3056 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3057 return ESR_Failed;
3058 }
3059 return ESR_Succeeded;
3060 }
3061
Richard Smith896e0d72013-05-06 06:51:17 +00003062 case Stmt::CXXForRangeStmtClass: {
3063 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3064
3065 // Initialize the __range variable.
3066 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3067 if (ESR != ESR_Succeeded)
3068 return ESR;
3069
3070 // Create the __begin and __end iterators.
3071 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3072 if (ESR != ESR_Succeeded)
3073 return ESR;
3074
3075 while (true) {
3076 // Condition: __begin != __end.
3077 bool Continue = true;
3078 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3079 return ESR_Failed;
3080 if (!Continue)
3081 break;
3082
3083 // User's variable declaration, initialized by *__begin.
3084 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3085 if (ESR != ESR_Succeeded)
3086 return ESR;
3087
3088 // Loop body.
3089 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3090 if (ESR != ESR_Continue)
3091 return ESR;
3092
3093 // Increment: ++__begin
3094 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3095 return ESR_Failed;
3096 }
3097
3098 return ESR_Succeeded;
3099 }
3100
Richard Smith496ddcf2013-05-12 17:32:42 +00003101 case Stmt::SwitchStmtClass:
3102 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3103
Richard Smith4e18ca52013-05-06 05:56:11 +00003104 case Stmt::ContinueStmtClass:
3105 return ESR_Continue;
3106
3107 case Stmt::BreakStmtClass:
3108 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003109
3110 case Stmt::LabelStmtClass:
3111 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3112
3113 case Stmt::AttributedStmtClass:
3114 // As a general principle, C++11 attributes can be ignored without
3115 // any semantic impact.
3116 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3117 Case);
3118
3119 case Stmt::CaseStmtClass:
3120 case Stmt::DefaultStmtClass:
3121 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003122 }
3123}
3124
Richard Smithcc36f692011-12-22 02:22:31 +00003125/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3126/// default constructor. If so, we'll fold it whether or not it's marked as
3127/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3128/// so we need special handling.
3129static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003130 const CXXConstructorDecl *CD,
3131 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003132 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3133 return false;
3134
Richard Smith66e05fe2012-01-18 05:21:49 +00003135 // Value-initialization does not call a trivial default constructor, so such a
3136 // call is a core constant expression whether or not the constructor is
3137 // constexpr.
3138 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003139 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003140 // FIXME: If DiagDecl is an implicitly-declared special member function,
3141 // we should be much more explicit about why it's not constexpr.
3142 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3143 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3144 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003145 } else {
3146 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3147 }
3148 }
3149 return true;
3150}
3151
Richard Smith357362d2011-12-13 06:39:58 +00003152/// CheckConstexprFunction - Check that a function can be called in a constant
3153/// expression.
3154static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3155 const FunctionDecl *Declaration,
3156 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003157 // Potential constant expressions can contain calls to declared, but not yet
3158 // defined, constexpr functions.
3159 if (Info.CheckingPotentialConstantExpression && !Definition &&
3160 Declaration->isConstexpr())
3161 return false;
3162
Richard Smith0838f3a2013-05-14 05:18:44 +00003163 // Bail out with no diagnostic if the function declaration itself is invalid.
3164 // We will have produced a relevant diagnostic while parsing it.
3165 if (Declaration->isInvalidDecl())
3166 return false;
3167
Richard Smith357362d2011-12-13 06:39:58 +00003168 // Can we evaluate this function call?
3169 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3170 return true;
3171
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003172 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003173 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003174 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3175 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003176 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3177 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3178 << DiagDecl;
3179 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3180 } else {
3181 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3182 }
3183 return false;
3184}
3185
Richard Smithd62306a2011-11-10 06:34:14 +00003186namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003187typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003188}
3189
3190/// EvaluateArgs - Evaluate the arguments to a function call.
3191static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3192 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003193 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003194 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003195 I != E; ++I) {
3196 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3197 // If we're checking for a potential constant expression, evaluate all
3198 // initializers even if some of them fail.
3199 if (!Info.keepEvaluatingAfterFailure())
3200 return false;
3201 Success = false;
3202 }
3203 }
3204 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003205}
3206
Richard Smith254a73d2011-10-28 22:34:42 +00003207/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003208static bool HandleFunctionCall(SourceLocation CallLoc,
3209 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003210 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003211 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003212 ArgVector ArgValues(Args.size());
3213 if (!EvaluateArgs(Args, ArgValues, Info))
3214 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003215
Richard Smith253c2a32012-01-27 01:14:48 +00003216 if (!Info.CheckCallLimit(CallLoc))
3217 return false;
3218
3219 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003220
3221 // For a trivial copy or move assignment, perform an APValue copy. This is
3222 // essential for unions, where the operations performed by the assignment
3223 // operator cannot be represented as statements.
3224 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3225 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3226 assert(This &&
3227 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3228 LValue RHS;
3229 RHS.setFrom(Info.Ctx, ArgValues[0]);
3230 APValue RHSValue;
3231 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3232 RHS, RHSValue))
3233 return false;
3234 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3235 RHSValue))
3236 return false;
3237 This->moveInto(Result);
3238 return true;
3239 }
3240
Richard Smithd9f663b2013-04-22 15:31:51 +00003241 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003242 if (ESR == ESR_Succeeded) {
3243 if (Callee->getResultType()->isVoidType())
3244 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003245 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003246 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003247 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003248}
3249
Richard Smithd62306a2011-11-10 06:34:14 +00003250/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003251static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003252 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003253 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003254 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003255 ArgVector ArgValues(Args.size());
3256 if (!EvaluateArgs(Args, ArgValues, Info))
3257 return false;
3258
Richard Smith253c2a32012-01-27 01:14:48 +00003259 if (!Info.CheckCallLimit(CallLoc))
3260 return false;
3261
Richard Smith3607ffe2012-02-13 03:54:03 +00003262 const CXXRecordDecl *RD = Definition->getParent();
3263 if (RD->getNumVBases()) {
3264 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3265 return false;
3266 }
3267
Richard Smith253c2a32012-01-27 01:14:48 +00003268 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003269
3270 // If it's a delegating constructor, just delegate.
3271 if (Definition->isDelegatingConstructor()) {
3272 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003273 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3274 return false;
3275 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003276 }
3277
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003278 // For a trivial copy or move constructor, perform an APValue copy. This is
3279 // essential for unions, where the operations performed by the constructor
3280 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003281 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003282 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3283 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003284 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003285 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003286 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003287 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003288 }
3289
3290 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003291 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003292 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3293 std::distance(RD->field_begin(), RD->field_end()));
3294
John McCalld7bca762012-05-01 00:38:49 +00003295 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003296 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3297
Richard Smith253c2a32012-01-27 01:14:48 +00003298 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003299 unsigned BasesSeen = 0;
3300#ifndef NDEBUG
3301 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3302#endif
3303 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3304 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003305 LValue Subobject = This;
3306 APValue *Value = &Result;
3307
3308 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003309 if ((*I)->isBaseInitializer()) {
3310 QualType BaseType((*I)->getBaseClass(), 0);
3311#ifndef NDEBUG
3312 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003313 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003314 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3315 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3316 "base class initializers not in expected order");
3317 ++BaseIt;
3318#endif
John McCalld7bca762012-05-01 00:38:49 +00003319 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3320 BaseType->getAsCXXRecordDecl(), &Layout))
3321 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003322 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003323 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003324 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3325 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003326 if (RD->isUnion()) {
3327 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003328 Value = &Result.getUnionValue();
3329 } else {
3330 Value = &Result.getStructField(FD->getFieldIndex());
3331 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003332 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003333 // Walk the indirect field decl's chain to find the object to initialize,
3334 // and make sure we've initialized every step along it.
3335 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3336 CE = IFD->chain_end();
3337 C != CE; ++C) {
3338 FieldDecl *FD = cast<FieldDecl>(*C);
3339 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3340 // Switch the union field if it differs. This happens if we had
3341 // preceding zero-initialization, and we're now initializing a union
3342 // subobject other than the first.
3343 // FIXME: In this case, the values of the other subobjects are
3344 // specified, since zero-initialization sets all padding bits to zero.
3345 if (Value->isUninit() ||
3346 (Value->isUnion() && Value->getUnionField() != FD)) {
3347 if (CD->isUnion())
3348 *Value = APValue(FD);
3349 else
3350 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3351 std::distance(CD->field_begin(), CD->field_end()));
3352 }
John McCalld7bca762012-05-01 00:38:49 +00003353 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3354 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003355 if (CD->isUnion())
3356 Value = &Value->getUnionValue();
3357 else
3358 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003359 }
Richard Smithd62306a2011-11-10 06:34:14 +00003360 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003361 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003362 }
Richard Smith253c2a32012-01-27 01:14:48 +00003363
Richard Smith7525ff62013-05-09 07:14:00 +00003364 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003365 // If we're checking for a potential constant expression, evaluate all
3366 // initializers even if some of them fail.
3367 if (!Info.keepEvaluatingAfterFailure())
3368 return false;
3369 Success = false;
3370 }
Richard Smithd62306a2011-11-10 06:34:14 +00003371 }
3372
Richard Smithd9f663b2013-04-22 15:31:51 +00003373 return Success &&
3374 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003375}
3376
Eli Friedman9a156e52008-11-12 09:44:48 +00003377//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003378// Generic Evaluation
3379//===----------------------------------------------------------------------===//
3380namespace {
3381
Richard Smithf57d8cb2011-12-09 22:58:01 +00003382// FIXME: RetTy is always bool. Remove it.
3383template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003384class ExprEvaluatorBase
3385 : public ConstStmtVisitor<Derived, RetTy> {
3386private:
Richard Smith2e312c82012-03-03 22:46:17 +00003387 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003388 return static_cast<Derived*>(this)->Success(V, E);
3389 }
Richard Smithfddd3842011-12-30 21:15:51 +00003390 RetTy DerivedZeroInitialization(const Expr *E) {
3391 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003392 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003393
Richard Smith17100ba2012-02-16 02:46:34 +00003394 // Check whether a conditional operator with a non-constant condition is a
3395 // potential constant expression. If neither arm is a potential constant
3396 // expression, then the conditional operator is not either.
3397 template<typename ConditionalOperator>
3398 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3399 assert(Info.CheckingPotentialConstantExpression);
3400
3401 // Speculatively evaluate both arms.
3402 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003403 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003404 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3405
3406 StmtVisitorTy::Visit(E->getFalseExpr());
3407 if (Diag.empty())
3408 return;
3409
3410 Diag.clear();
3411 StmtVisitorTy::Visit(E->getTrueExpr());
3412 if (Diag.empty())
3413 return;
3414 }
3415
3416 Error(E, diag::note_constexpr_conditional_never_const);
3417 }
3418
3419
3420 template<typename ConditionalOperator>
3421 bool HandleConditionalOperator(const ConditionalOperator *E) {
3422 bool BoolResult;
3423 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3424 if (Info.CheckingPotentialConstantExpression)
3425 CheckPotentialConstantConditional(E);
3426 return false;
3427 }
3428
3429 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3430 return StmtVisitorTy::Visit(EvalExpr);
3431 }
3432
Peter Collingbournee9200682011-05-13 03:29:01 +00003433protected:
3434 EvalInfo &Info;
3435 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3436 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3437
Richard Smith92b1ce02011-12-12 09:28:41 +00003438 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003439 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003440 }
3441
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003442 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3443
3444public:
3445 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3446
3447 EvalInfo &getEvalInfo() { return Info; }
3448
Richard Smithf57d8cb2011-12-09 22:58:01 +00003449 /// Report an evaluation error. This should only be called when an error is
3450 /// first discovered. When propagating an error, just return false.
3451 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003452 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003453 return false;
3454 }
3455 bool Error(const Expr *E) {
3456 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3457 }
3458
Peter Collingbournee9200682011-05-13 03:29:01 +00003459 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003460 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003461 }
3462 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003463 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003464 }
3465
3466 RetTy VisitParenExpr(const ParenExpr *E)
3467 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3468 RetTy VisitUnaryExtension(const UnaryOperator *E)
3469 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3470 RetTy VisitUnaryPlus(const UnaryOperator *E)
3471 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3472 RetTy VisitChooseExpr(const ChooseExpr *E)
3473 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3474 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3475 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003476 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3477 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003478 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3479 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003480 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3481 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003482 // We cannot create any objects for which cleanups are required, so there is
3483 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3484 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3485 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003486
Richard Smith6d6ecc32011-12-12 12:46:16 +00003487 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3488 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3489 return static_cast<Derived*>(this)->VisitCastExpr(E);
3490 }
3491 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3492 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3493 return static_cast<Derived*>(this)->VisitCastExpr(E);
3494 }
3495
Richard Smith027bf112011-11-17 22:56:20 +00003496 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3497 switch (E->getOpcode()) {
3498 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003499 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003500
3501 case BO_Comma:
3502 VisitIgnoredValue(E->getLHS());
3503 return StmtVisitorTy::Visit(E->getRHS());
3504
3505 case BO_PtrMemD:
3506 case BO_PtrMemI: {
3507 LValue Obj;
3508 if (!HandleMemberPointerAccess(Info, E, Obj))
3509 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003510 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003511 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003512 return false;
3513 return DerivedSuccess(Result, E);
3514 }
3515 }
3516 }
3517
Peter Collingbournee9200682011-05-13 03:29:01 +00003518 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003519 // Evaluate and cache the common expression. We treat it as a temporary,
3520 // even though it's not quite the same thing.
3521 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3522 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003523 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003524
Richard Smith17100ba2012-02-16 02:46:34 +00003525 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003526 }
3527
3528 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003529 bool IsBcpCall = false;
3530 // If the condition (ignoring parens) is a __builtin_constant_p call,
3531 // the result is a constant expression if it can be folded without
3532 // side-effects. This is an important GNU extension. See GCC PR38377
3533 // for discussion.
3534 if (const CallExpr *CallCE =
3535 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3536 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3537 IsBcpCall = true;
3538
3539 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3540 // constant expression; we can't check whether it's potentially foldable.
3541 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3542 return false;
3543
3544 FoldConstant Fold(Info);
3545
Richard Smith17100ba2012-02-16 02:46:34 +00003546 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003547 return false;
3548
3549 if (IsBcpCall)
3550 Fold.Fold(Info);
3551
3552 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003553 }
3554
3555 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003556 APValue &Value = Info.CurrentCall->Temporaries[E];
3557 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003558 const Expr *Source = E->getSourceExpr();
3559 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003560 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003561 if (Source == E) { // sanity checking.
3562 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003563 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003564 }
3565 return StmtVisitorTy::Visit(Source);
3566 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003567 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003568 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003569
Richard Smith254a73d2011-10-28 22:34:42 +00003570 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003571 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003572 QualType CalleeType = Callee->getType();
3573
Richard Smith254a73d2011-10-28 22:34:42 +00003574 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003575 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003576 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003577 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003578
Richard Smithe97cbd72011-11-11 04:05:33 +00003579 // Extract function decl and 'this' pointer from the callee.
3580 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003581 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003582 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3583 // Explicit bound member calls, such as x.f() or p->g();
3584 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003585 return false;
3586 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003587 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003588 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003589 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3590 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003591 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3592 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003593 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003594 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003595 return Error(Callee);
3596
3597 FD = dyn_cast<FunctionDecl>(Member);
3598 if (!FD)
3599 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003600 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003601 LValue Call;
3602 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003603 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003604
Richard Smitha8105bc2012-01-06 16:39:00 +00003605 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003606 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003607 FD = dyn_cast_or_null<FunctionDecl>(
3608 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003609 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003610 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003611
3612 // Overloaded operator calls to member functions are represented as normal
3613 // calls with '*this' as the first argument.
3614 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3615 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003616 // FIXME: When selecting an implicit conversion for an overloaded
3617 // operator delete, we sometimes try to evaluate calls to conversion
3618 // operators without a 'this' parameter!
3619 if (Args.empty())
3620 return Error(E);
3621
Richard Smithe97cbd72011-11-11 04:05:33 +00003622 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3623 return false;
3624 This = &ThisVal;
3625 Args = Args.slice(1);
3626 }
3627
3628 // Don't call function pointers which have been cast to some other type.
3629 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003630 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003631 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003632 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003633
Richard Smith47b34932012-02-01 02:39:43 +00003634 if (This && !This->checkSubobject(Info, E, CSK_This))
3635 return false;
3636
Richard Smith3607ffe2012-02-13 03:54:03 +00003637 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3638 // calls to such functions in constant expressions.
3639 if (This && !HasQualifier &&
3640 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3641 return Error(E, diag::note_constexpr_virtual_call);
3642
Richard Smith357362d2011-12-13 06:39:58 +00003643 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003644 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003645 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003646
Richard Smith357362d2011-12-13 06:39:58 +00003647 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003648 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3649 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003650 return false;
3651
Richard Smithb228a862012-02-15 02:18:13 +00003652 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003653 }
3654
Richard Smith11562c52011-10-28 17:51:58 +00003655 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3656 return StmtVisitorTy::Visit(E->getInitializer());
3657 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003658 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003659 if (E->getNumInits() == 0)
3660 return DerivedZeroInitialization(E);
3661 if (E->getNumInits() == 1)
3662 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003663 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003664 }
3665 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003666 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003667 }
3668 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003669 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003670 }
Richard Smith027bf112011-11-17 22:56:20 +00003671 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003672 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003673 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003674
Richard Smithd62306a2011-11-10 06:34:14 +00003675 /// A member expression where the object is a prvalue is itself a prvalue.
3676 RetTy VisitMemberExpr(const MemberExpr *E) {
3677 assert(!E->isArrow() && "missing call to bound member function?");
3678
Richard Smith2e312c82012-03-03 22:46:17 +00003679 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003680 if (!Evaluate(Val, Info, E->getBase()))
3681 return false;
3682
3683 QualType BaseTy = E->getBase()->getType();
3684
3685 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003686 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003687 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003688 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003689 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3690
Richard Smith3229b742013-05-05 21:17:10 +00003691 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003692 SubobjectDesignator Designator(BaseTy);
3693 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003694
Richard Smith3229b742013-05-05 21:17:10 +00003695 APValue Result;
3696 return extractSubobject(Info, E, Obj, Designator, Result) &&
3697 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003698 }
3699
Richard Smith11562c52011-10-28 17:51:58 +00003700 RetTy VisitCastExpr(const CastExpr *E) {
3701 switch (E->getCastKind()) {
3702 default:
3703 break;
3704
David Chisnallfa35df62012-01-16 17:27:18 +00003705 case CK_AtomicToNonAtomic:
3706 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003707 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003708 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003709 return StmtVisitorTy::Visit(E->getSubExpr());
3710
3711 case CK_LValueToRValue: {
3712 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003713 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3714 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003715 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003716 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003717 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003718 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003719 return false;
3720 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003721 }
3722 }
3723
Richard Smithf57d8cb2011-12-09 22:58:01 +00003724 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003725 }
3726
Richard Smith243ef902013-05-05 23:31:59 +00003727 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3728 return VisitUnaryPostIncDec(UO);
3729 }
3730 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3731 return VisitUnaryPostIncDec(UO);
3732 }
3733 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3734 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3735 return Error(UO);
3736
3737 LValue LVal;
3738 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3739 return false;
3740 APValue RVal;
3741 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3742 UO->isIncrementOp(), &RVal))
3743 return false;
3744 return DerivedSuccess(RVal, UO);
3745 }
3746
Richard Smith4a678122011-10-24 18:44:57 +00003747 /// Visit a value which is evaluated, but whose value is ignored.
3748 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003749 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003750 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003751};
3752
3753}
3754
3755//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003756// Common base class for lvalue and temporary evaluation.
3757//===----------------------------------------------------------------------===//
3758namespace {
3759template<class Derived>
3760class LValueExprEvaluatorBase
3761 : public ExprEvaluatorBase<Derived, bool> {
3762protected:
3763 LValue &Result;
3764 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3765 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3766
3767 bool Success(APValue::LValueBase B) {
3768 Result.set(B);
3769 return true;
3770 }
3771
3772public:
3773 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3774 ExprEvaluatorBaseTy(Info), Result(Result) {}
3775
Richard Smith2e312c82012-03-03 22:46:17 +00003776 bool Success(const APValue &V, const Expr *E) {
3777 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003778 return true;
3779 }
Richard Smith027bf112011-11-17 22:56:20 +00003780
Richard Smith027bf112011-11-17 22:56:20 +00003781 bool VisitMemberExpr(const MemberExpr *E) {
3782 // Handle non-static data members.
3783 QualType BaseTy;
3784 if (E->isArrow()) {
3785 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3786 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003787 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003788 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003789 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003790 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3791 return false;
3792 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003793 } else {
3794 if (!this->Visit(E->getBase()))
3795 return false;
3796 BaseTy = E->getBase()->getType();
3797 }
Richard Smith027bf112011-11-17 22:56:20 +00003798
Richard Smith1b78b3d2012-01-25 22:15:11 +00003799 const ValueDecl *MD = E->getMemberDecl();
3800 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3801 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3802 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3803 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003804 if (!HandleLValueMember(this->Info, E, Result, FD))
3805 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003806 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003807 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3808 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003809 } else
3810 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003811
Richard Smith1b78b3d2012-01-25 22:15:11 +00003812 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003813 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003814 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003815 RefValue))
3816 return false;
3817 return Success(RefValue, E);
3818 }
3819 return true;
3820 }
3821
3822 bool VisitBinaryOperator(const BinaryOperator *E) {
3823 switch (E->getOpcode()) {
3824 default:
3825 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3826
3827 case BO_PtrMemD:
3828 case BO_PtrMemI:
3829 return HandleMemberPointerAccess(this->Info, E, Result);
3830 }
3831 }
3832
3833 bool VisitCastExpr(const CastExpr *E) {
3834 switch (E->getCastKind()) {
3835 default:
3836 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3837
3838 case CK_DerivedToBase:
3839 case CK_UncheckedDerivedToBase: {
3840 if (!this->Visit(E->getSubExpr()))
3841 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003842
3843 // Now figure out the necessary offset to add to the base LV to get from
3844 // the derived class to the base class.
3845 QualType Type = E->getSubExpr()->getType();
3846
3847 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3848 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003849 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003850 *PathI))
3851 return false;
3852 Type = (*PathI)->getType();
3853 }
3854
3855 return true;
3856 }
3857 }
3858 }
3859};
3860}
3861
3862//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003863// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003864//
3865// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3866// function designators (in C), decl references to void objects (in C), and
3867// temporaries (if building with -Wno-address-of-temporary).
3868//
3869// LValue evaluation produces values comprising a base expression of one of the
3870// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003871// - Declarations
3872// * VarDecl
3873// * FunctionDecl
3874// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003875// * CompoundLiteralExpr in C
3876// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003877// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003878// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003879// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003880// * ObjCEncodeExpr
3881// * AddrLabelExpr
3882// * BlockExpr
3883// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003884// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003885// * Any Expr, with a CallIndex indicating the function in which the temporary
3886// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003887// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003888//===----------------------------------------------------------------------===//
3889namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003890class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003891 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003892public:
Richard Smith027bf112011-11-17 22:56:20 +00003893 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3894 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003895
Richard Smith11562c52011-10-28 17:51:58 +00003896 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003897 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003898
Peter Collingbournee9200682011-05-13 03:29:01 +00003899 bool VisitDeclRefExpr(const DeclRefExpr *E);
3900 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003901 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003902 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3903 bool VisitMemberExpr(const MemberExpr *E);
3904 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3905 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003906 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003907 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003908 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3909 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003910 bool VisitUnaryReal(const UnaryOperator *E);
3911 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003912 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3913 return VisitUnaryPreIncDec(UO);
3914 }
3915 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3916 return VisitUnaryPreIncDec(UO);
3917 }
Richard Smith3229b742013-05-05 21:17:10 +00003918 bool VisitBinAssign(const BinaryOperator *BO);
3919 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003920
Peter Collingbournee9200682011-05-13 03:29:01 +00003921 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003922 switch (E->getCastKind()) {
3923 default:
Richard Smith027bf112011-11-17 22:56:20 +00003924 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003925
Eli Friedmance3e02a2011-10-11 00:13:24 +00003926 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003927 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003928 if (!Visit(E->getSubExpr()))
3929 return false;
3930 Result.Designator.setInvalid();
3931 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003932
Richard Smith027bf112011-11-17 22:56:20 +00003933 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003934 if (!Visit(E->getSubExpr()))
3935 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003936 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003937 }
3938 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003939};
3940} // end anonymous namespace
3941
Richard Smith11562c52011-10-28 17:51:58 +00003942/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003943/// expressions which are not glvalues, in two cases:
3944/// * function designators in C, and
3945/// * "extern void" objects
3946static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3947 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3948 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003949 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003950}
3951
Peter Collingbournee9200682011-05-13 03:29:01 +00003952bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003953 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3954 return Success(FD);
3955 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003956 return VisitVarDecl(E, VD);
3957 return Error(E);
3958}
Richard Smith733237d2011-10-24 23:14:33 +00003959
Richard Smith11562c52011-10-28 17:51:58 +00003960bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003961 CallStackFrame *Frame = 0;
3962 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3963 Frame = Info.CurrentCall;
3964
Richard Smithfec09922011-11-01 16:57:24 +00003965 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003966 if (Frame) {
3967 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003968 return true;
3969 }
Richard Smithce40ad62011-11-12 22:28:03 +00003970 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003971 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003972
Richard Smith3229b742013-05-05 21:17:10 +00003973 APValue *V;
3974 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003975 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003976 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003977}
3978
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003979bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3980 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003981 if (E->getType()->isRecordType())
3982 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003983
Richard Smithb228a862012-02-15 02:18:13 +00003984 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003985 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3986 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003987}
3988
Peter Collingbournee9200682011-05-13 03:29:01 +00003989bool
3990LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003991 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3992 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3993 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003994 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003995}
3996
Richard Smith6e525142011-12-27 12:18:28 +00003997bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003998 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003999 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004000
4001 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4002 << E->getExprOperand()->getType()
4003 << E->getExprOperand()->getSourceRange();
4004 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004005}
4006
Francois Pichet0066db92012-04-16 04:08:35 +00004007bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4008 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004009}
Francois Pichet0066db92012-04-16 04:08:35 +00004010
Peter Collingbournee9200682011-05-13 03:29:01 +00004011bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004012 // Handle static data members.
4013 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4014 VisitIgnoredValue(E->getBase());
4015 return VisitVarDecl(E, VD);
4016 }
4017
Richard Smith254a73d2011-10-28 22:34:42 +00004018 // Handle static member functions.
4019 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4020 if (MD->isStatic()) {
4021 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004022 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004023 }
4024 }
4025
Richard Smithd62306a2011-11-10 06:34:14 +00004026 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004027 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004028}
4029
Peter Collingbournee9200682011-05-13 03:29:01 +00004030bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004031 // FIXME: Deal with vectors as array subscript bases.
4032 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004033 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004034
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004035 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004036 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004037
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004038 APSInt Index;
4039 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004040 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004041
Richard Smith861b5b52013-05-07 23:34:45 +00004042 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4043 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004044}
Eli Friedman9a156e52008-11-12 09:44:48 +00004045
Peter Collingbournee9200682011-05-13 03:29:01 +00004046bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004047 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004048}
4049
Richard Smith66c96992012-02-18 22:04:06 +00004050bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4051 if (!Visit(E->getSubExpr()))
4052 return false;
4053 // __real is a no-op on scalar lvalues.
4054 if (E->getSubExpr()->getType()->isAnyComplexType())
4055 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4056 return true;
4057}
4058
4059bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4060 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4061 "lvalue __imag__ on scalar?");
4062 if (!Visit(E->getSubExpr()))
4063 return false;
4064 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4065 return true;
4066}
4067
Richard Smith243ef902013-05-05 23:31:59 +00004068bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4069 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004070 return Error(UO);
4071
4072 if (!this->Visit(UO->getSubExpr()))
4073 return false;
4074
Richard Smith243ef902013-05-05 23:31:59 +00004075 return handleIncDec(
4076 this->Info, UO, Result, UO->getSubExpr()->getType(),
4077 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004078}
4079
4080bool LValueExprEvaluator::VisitCompoundAssignOperator(
4081 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004082 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004083 return Error(CAO);
4084
Richard Smith3229b742013-05-05 21:17:10 +00004085 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004086
4087 // The overall lvalue result is the result of evaluating the LHS.
4088 if (!this->Visit(CAO->getLHS())) {
4089 if (Info.keepEvaluatingAfterFailure())
4090 Evaluate(RHS, this->Info, CAO->getRHS());
4091 return false;
4092 }
4093
Richard Smith3229b742013-05-05 21:17:10 +00004094 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4095 return false;
4096
Richard Smith43e77732013-05-07 04:50:00 +00004097 return handleCompoundAssignment(
4098 this->Info, CAO,
4099 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4100 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004101}
4102
4103bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004104 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4105 return Error(E);
4106
Richard Smith3229b742013-05-05 21:17:10 +00004107 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004108
4109 if (!this->Visit(E->getLHS())) {
4110 if (Info.keepEvaluatingAfterFailure())
4111 Evaluate(NewVal, this->Info, E->getRHS());
4112 return false;
4113 }
4114
Richard Smith3229b742013-05-05 21:17:10 +00004115 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4116 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004117
4118 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004119 NewVal);
4120}
4121
Eli Friedman9a156e52008-11-12 09:44:48 +00004122//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004123// Pointer Evaluation
4124//===----------------------------------------------------------------------===//
4125
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004126namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004127class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004128 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004129 LValue &Result;
4130
Peter Collingbournee9200682011-05-13 03:29:01 +00004131 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004132 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004133 return true;
4134 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004135public:
Mike Stump11289f42009-09-09 15:08:12 +00004136
John McCall45d55e42010-05-07 21:00:08 +00004137 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004138 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004139
Richard Smith2e312c82012-03-03 22:46:17 +00004140 bool Success(const APValue &V, const Expr *E) {
4141 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004142 return true;
4143 }
Richard Smithfddd3842011-12-30 21:15:51 +00004144 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004145 return Success((Expr*)0);
4146 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004147
John McCall45d55e42010-05-07 21:00:08 +00004148 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004149 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004150 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004151 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004152 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004153 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004154 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004155 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004156 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004157 bool VisitCallExpr(const CallExpr *E);
4158 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004159 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004160 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004161 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004162 }
Richard Smithd62306a2011-11-10 06:34:14 +00004163 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4164 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004165 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004166 Result = *Info.CurrentCall->This;
4167 return true;
4168 }
John McCallc07a0c72011-02-17 10:25:35 +00004169
Eli Friedman449fe542009-03-23 04:56:01 +00004170 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004171};
Chris Lattner05706e882008-07-11 18:11:29 +00004172} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004173
John McCall45d55e42010-05-07 21:00:08 +00004174static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004175 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004176 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004177}
4178
John McCall45d55e42010-05-07 21:00:08 +00004179bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004180 if (E->getOpcode() != BO_Add &&
4181 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004182 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004183
Chris Lattner05706e882008-07-11 18:11:29 +00004184 const Expr *PExp = E->getLHS();
4185 const Expr *IExp = E->getRHS();
4186 if (IExp->getType()->isPointerType())
4187 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004188
Richard Smith253c2a32012-01-27 01:14:48 +00004189 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4190 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004191 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004192
John McCall45d55e42010-05-07 21:00:08 +00004193 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004194 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004195 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004196
4197 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004198 if (E->getOpcode() == BO_Sub)
4199 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004200
Ted Kremenek28831752012-08-23 20:46:57 +00004201 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004202 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4203 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004204}
Eli Friedman9a156e52008-11-12 09:44:48 +00004205
John McCall45d55e42010-05-07 21:00:08 +00004206bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4207 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004208}
Mike Stump11289f42009-09-09 15:08:12 +00004209
Peter Collingbournee9200682011-05-13 03:29:01 +00004210bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4211 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004212
Eli Friedman847a2bc2009-12-27 05:43:15 +00004213 switch (E->getCastKind()) {
4214 default:
4215 break;
4216
John McCalle3027922010-08-25 11:45:40 +00004217 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004218 case CK_CPointerToObjCPointerCast:
4219 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004220 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004221 if (!Visit(SubExpr))
4222 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004223 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4224 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4225 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004226 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004227 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004228 if (SubExpr->getType()->isVoidPointerType())
4229 CCEDiag(E, diag::note_constexpr_invalid_cast)
4230 << 3 << SubExpr->getType();
4231 else
4232 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4233 }
Richard Smith96e0c102011-11-04 02:25:55 +00004234 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004235
Anders Carlsson18275092010-10-31 20:41:46 +00004236 case CK_DerivedToBase:
4237 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004238 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004239 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004240 if (!Result.Base && Result.Offset.isZero())
4241 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004242
Richard Smithd62306a2011-11-10 06:34:14 +00004243 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004244 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00004245 QualType Type =
4246 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00004247
Richard Smithd62306a2011-11-10 06:34:14 +00004248 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00004249 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004250 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
4251 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00004252 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004253 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00004254 }
4255
Anders Carlsson18275092010-10-31 20:41:46 +00004256 return true;
4257 }
4258
Richard Smith027bf112011-11-17 22:56:20 +00004259 case CK_BaseToDerived:
4260 if (!Visit(E->getSubExpr()))
4261 return false;
4262 if (!Result.Base && Result.Offset.isZero())
4263 return true;
4264 return HandleBaseToDerivedCast(Info, E, Result);
4265
Richard Smith0b0a0b62011-10-29 20:57:55 +00004266 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004267 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004268 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004269
John McCalle3027922010-08-25 11:45:40 +00004270 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004271 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4272
Richard Smith2e312c82012-03-03 22:46:17 +00004273 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004274 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004275 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004276
John McCall45d55e42010-05-07 21:00:08 +00004277 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004278 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4279 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004280 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004281 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004282 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004283 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004284 return true;
4285 } else {
4286 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004287 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004288 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004289 }
4290 }
John McCalle3027922010-08-25 11:45:40 +00004291 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004292 if (SubExpr->isGLValue()) {
4293 if (!EvaluateLValue(SubExpr, Result, Info))
4294 return false;
4295 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004296 Result.set(SubExpr, Info.CurrentCall->Index);
4297 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4298 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004299 return false;
4300 }
Richard Smith96e0c102011-11-04 02:25:55 +00004301 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004302 if (const ConstantArrayType *CAT
4303 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4304 Result.addArray(Info, E, CAT);
4305 else
4306 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004307 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004308
John McCalle3027922010-08-25 11:45:40 +00004309 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004310 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004311 }
4312
Richard Smith11562c52011-10-28 17:51:58 +00004313 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004314}
Chris Lattner05706e882008-07-11 18:11:29 +00004315
Peter Collingbournee9200682011-05-13 03:29:01 +00004316bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004317 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004318 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004319
Peter Collingbournee9200682011-05-13 03:29:01 +00004320 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004321}
Chris Lattner05706e882008-07-11 18:11:29 +00004322
4323//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004324// Member Pointer Evaluation
4325//===----------------------------------------------------------------------===//
4326
4327namespace {
4328class MemberPointerExprEvaluator
4329 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4330 MemberPtr &Result;
4331
4332 bool Success(const ValueDecl *D) {
4333 Result = MemberPtr(D);
4334 return true;
4335 }
4336public:
4337
4338 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4339 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4340
Richard Smith2e312c82012-03-03 22:46:17 +00004341 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004342 Result.setFrom(V);
4343 return true;
4344 }
Richard Smithfddd3842011-12-30 21:15:51 +00004345 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004346 return Success((const ValueDecl*)0);
4347 }
4348
4349 bool VisitCastExpr(const CastExpr *E);
4350 bool VisitUnaryAddrOf(const UnaryOperator *E);
4351};
4352} // end anonymous namespace
4353
4354static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4355 EvalInfo &Info) {
4356 assert(E->isRValue() && E->getType()->isMemberPointerType());
4357 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4358}
4359
4360bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4361 switch (E->getCastKind()) {
4362 default:
4363 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4364
4365 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004366 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004367 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004368
4369 case CK_BaseToDerivedMemberPointer: {
4370 if (!Visit(E->getSubExpr()))
4371 return false;
4372 if (E->path_empty())
4373 return true;
4374 // Base-to-derived member pointer casts store the path in derived-to-base
4375 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4376 // the wrong end of the derived->base arc, so stagger the path by one class.
4377 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4378 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4379 PathI != PathE; ++PathI) {
4380 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4381 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4382 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004383 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004384 }
4385 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4386 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004387 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004388 return true;
4389 }
4390
4391 case CK_DerivedToBaseMemberPointer:
4392 if (!Visit(E->getSubExpr()))
4393 return false;
4394 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4395 PathE = E->path_end(); PathI != PathE; ++PathI) {
4396 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4397 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4398 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004399 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004400 }
4401 return true;
4402 }
4403}
4404
4405bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4406 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4407 // member can be formed.
4408 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4409}
4410
4411//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004412// Record Evaluation
4413//===----------------------------------------------------------------------===//
4414
4415namespace {
4416 class RecordExprEvaluator
4417 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4418 const LValue &This;
4419 APValue &Result;
4420 public:
4421
4422 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4423 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4424
Richard Smith2e312c82012-03-03 22:46:17 +00004425 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004426 Result = V;
4427 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004428 }
Richard Smithfddd3842011-12-30 21:15:51 +00004429 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004430
Richard Smithe97cbd72011-11-11 04:05:33 +00004431 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004432 bool VisitInitListExpr(const InitListExpr *E);
4433 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4434 };
4435}
4436
Richard Smithfddd3842011-12-30 21:15:51 +00004437/// Perform zero-initialization on an object of non-union class type.
4438/// C++11 [dcl.init]p5:
4439/// To zero-initialize an object or reference of type T means:
4440/// [...]
4441/// -- if T is a (possibly cv-qualified) non-union class type,
4442/// each non-static data member and each base-class subobject is
4443/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004444static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4445 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004446 const LValue &This, APValue &Result) {
4447 assert(!RD->isUnion() && "Expected non-union class type");
4448 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4449 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4450 std::distance(RD->field_begin(), RD->field_end()));
4451
John McCalld7bca762012-05-01 00:38:49 +00004452 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004453 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4454
4455 if (CD) {
4456 unsigned Index = 0;
4457 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004458 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004459 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4460 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004461 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4462 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004463 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004464 Result.getStructBase(Index)))
4465 return false;
4466 }
4467 }
4468
Richard Smitha8105bc2012-01-06 16:39:00 +00004469 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4470 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004471 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004472 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004473 continue;
4474
4475 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004476 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004477 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004478
David Blaikie2d7c57e2012-04-30 02:36:29 +00004479 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004480 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004481 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004482 return false;
4483 }
4484
4485 return true;
4486}
4487
4488bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4489 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004490 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004491 if (RD->isUnion()) {
4492 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4493 // object's first non-static named data member is zero-initialized
4494 RecordDecl::field_iterator I = RD->field_begin();
4495 if (I == RD->field_end()) {
4496 Result = APValue((const FieldDecl*)0);
4497 return true;
4498 }
4499
4500 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004501 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004502 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004503 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004504 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004505 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004506 }
4507
Richard Smith5d108602012-02-17 00:44:16 +00004508 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004509 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004510 return false;
4511 }
4512
Richard Smitha8105bc2012-01-06 16:39:00 +00004513 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004514}
4515
Richard Smithe97cbd72011-11-11 04:05:33 +00004516bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4517 switch (E->getCastKind()) {
4518 default:
4519 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4520
4521 case CK_ConstructorConversion:
4522 return Visit(E->getSubExpr());
4523
4524 case CK_DerivedToBase:
4525 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004526 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004527 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004528 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004529 if (!DerivedObject.isStruct())
4530 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004531
4532 // Derived-to-base rvalue conversion: just slice off the derived part.
4533 APValue *Value = &DerivedObject;
4534 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4535 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4536 PathE = E->path_end(); PathI != PathE; ++PathI) {
4537 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4538 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4539 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4540 RD = Base;
4541 }
4542 Result = *Value;
4543 return true;
4544 }
4545 }
4546}
4547
Richard Smithd62306a2011-11-10 06:34:14 +00004548bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004549 // Cannot constant-evaluate std::initializer_list inits.
4550 if (E->initializesStdInitializerList())
4551 return false;
4552
Richard Smithd62306a2011-11-10 06:34:14 +00004553 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004554 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004555 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4556
4557 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004558 const FieldDecl *Field = E->getInitializedFieldInUnion();
4559 Result = APValue(Field);
4560 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004561 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004562
4563 // If the initializer list for a union does not contain any elements, the
4564 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004565 // FIXME: The element should be initialized from an initializer list.
4566 // Is this difference ever observable for initializer lists which
4567 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004568 ImplicitValueInitExpr VIE(Field->getType());
4569 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4570
Richard Smithd62306a2011-11-10 06:34:14 +00004571 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004572 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4573 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004574
4575 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4576 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4577 isa<CXXDefaultInitExpr>(InitExpr));
4578
Richard Smithb228a862012-02-15 02:18:13 +00004579 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004580 }
4581
4582 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4583 "initializer list for class with base classes");
4584 Result = APValue(APValue::UninitStruct(), 0,
4585 std::distance(RD->field_begin(), RD->field_end()));
4586 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004587 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004588 for (RecordDecl::field_iterator Field = RD->field_begin(),
4589 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4590 // Anonymous bit-fields are not considered members of the class for
4591 // purposes of aggregate initialization.
4592 if (Field->isUnnamedBitfield())
4593 continue;
4594
4595 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004596
Richard Smith253c2a32012-01-27 01:14:48 +00004597 bool HaveInit = ElementNo < E->getNumInits();
4598
4599 // FIXME: Diagnostics here should point to the end of the initializer
4600 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004601 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004602 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004603 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004604
4605 // Perform an implicit value-initialization for members beyond the end of
4606 // the initializer list.
4607 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004608 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004609
Richard Smith852c9db2013-04-20 22:23:05 +00004610 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4611 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4612 isa<CXXDefaultInitExpr>(Init));
4613
4614 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4615 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004616 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004617 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004618 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004619 }
4620 }
4621
Richard Smith253c2a32012-01-27 01:14:48 +00004622 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004623}
4624
4625bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4626 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004627 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4628
Richard Smithfddd3842011-12-30 21:15:51 +00004629 bool ZeroInit = E->requiresZeroInitialization();
4630 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004631 // If we've already performed zero-initialization, we're already done.
4632 if (!Result.isUninit())
4633 return true;
4634
Richard Smithfddd3842011-12-30 21:15:51 +00004635 if (ZeroInit)
4636 return ZeroInitialization(E);
4637
Richard Smithcc36f692011-12-22 02:22:31 +00004638 const CXXRecordDecl *RD = FD->getParent();
4639 if (RD->isUnion())
4640 Result = APValue((FieldDecl*)0);
4641 else
4642 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4643 std::distance(RD->field_begin(), RD->field_end()));
4644 return true;
4645 }
4646
Richard Smithd62306a2011-11-10 06:34:14 +00004647 const FunctionDecl *Definition = 0;
4648 FD->getBody(Definition);
4649
Richard Smith357362d2011-12-13 06:39:58 +00004650 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4651 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004652
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004653 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004654 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004655 if (const MaterializeTemporaryExpr *ME
4656 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4657 return Visit(ME->GetTemporaryExpr());
4658
Richard Smithfddd3842011-12-30 21:15:51 +00004659 if (ZeroInit && !ZeroInitialization(E))
4660 return false;
4661
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004662 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004663 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004664 cast<CXXConstructorDecl>(Definition), Info,
4665 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004666}
4667
4668static bool EvaluateRecord(const Expr *E, const LValue &This,
4669 APValue &Result, EvalInfo &Info) {
4670 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004671 "can't evaluate expression as a record rvalue");
4672 return RecordExprEvaluator(Info, This, Result).Visit(E);
4673}
4674
4675//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004676// Temporary Evaluation
4677//
4678// Temporaries are represented in the AST as rvalues, but generally behave like
4679// lvalues. The full-object of which the temporary is a subobject is implicitly
4680// materialized so that a reference can bind to it.
4681//===----------------------------------------------------------------------===//
4682namespace {
4683class TemporaryExprEvaluator
4684 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4685public:
4686 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4687 LValueExprEvaluatorBaseTy(Info, Result) {}
4688
4689 /// Visit an expression which constructs the value of this temporary.
4690 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004691 Result.set(E, Info.CurrentCall->Index);
4692 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004693 }
4694
4695 bool VisitCastExpr(const CastExpr *E) {
4696 switch (E->getCastKind()) {
4697 default:
4698 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4699
4700 case CK_ConstructorConversion:
4701 return VisitConstructExpr(E->getSubExpr());
4702 }
4703 }
4704 bool VisitInitListExpr(const InitListExpr *E) {
4705 return VisitConstructExpr(E);
4706 }
4707 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4708 return VisitConstructExpr(E);
4709 }
4710 bool VisitCallExpr(const CallExpr *E) {
4711 return VisitConstructExpr(E);
4712 }
4713};
4714} // end anonymous namespace
4715
4716/// Evaluate an expression of record type as a temporary.
4717static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004718 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004719 return TemporaryExprEvaluator(Info, Result).Visit(E);
4720}
4721
4722//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004723// Vector Evaluation
4724//===----------------------------------------------------------------------===//
4725
4726namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004727 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004728 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4729 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004730 public:
Mike Stump11289f42009-09-09 15:08:12 +00004731
Richard Smith2d406342011-10-22 21:10:00 +00004732 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4733 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004734
Richard Smith2d406342011-10-22 21:10:00 +00004735 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4736 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4737 // FIXME: remove this APValue copy.
4738 Result = APValue(V.data(), V.size());
4739 return true;
4740 }
Richard Smith2e312c82012-03-03 22:46:17 +00004741 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004742 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004743 Result = V;
4744 return true;
4745 }
Richard Smithfddd3842011-12-30 21:15:51 +00004746 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004747
Richard Smith2d406342011-10-22 21:10:00 +00004748 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004749 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004750 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004751 bool VisitInitListExpr(const InitListExpr *E);
4752 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004753 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004754 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004755 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004756 };
4757} // end anonymous namespace
4758
4759static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004760 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004761 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004762}
4763
Richard Smith2d406342011-10-22 21:10:00 +00004764bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4765 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004766 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004767
Richard Smith161f09a2011-12-06 22:44:34 +00004768 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004769 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004770
Eli Friedmanc757de22011-03-25 00:43:55 +00004771 switch (E->getCastKind()) {
4772 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004773 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004774 if (SETy->isIntegerType()) {
4775 APSInt IntResult;
4776 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004777 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004778 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004779 } else if (SETy->isRealFloatingType()) {
4780 APFloat F(0.0);
4781 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004782 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004783 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004784 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004785 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004786 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004787
4788 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004789 SmallVector<APValue, 4> Elts(NElts, Val);
4790 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004791 }
Eli Friedman803acb32011-12-22 03:51:45 +00004792 case CK_BitCast: {
4793 // Evaluate the operand into an APInt we can extract from.
4794 llvm::APInt SValInt;
4795 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4796 return false;
4797 // Extract the elements
4798 QualType EltTy = VTy->getElementType();
4799 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4800 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4801 SmallVector<APValue, 4> Elts;
4802 if (EltTy->isRealFloatingType()) {
4803 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004804 unsigned FloatEltSize = EltSize;
4805 if (&Sem == &APFloat::x87DoubleExtended)
4806 FloatEltSize = 80;
4807 for (unsigned i = 0; i < NElts; i++) {
4808 llvm::APInt Elt;
4809 if (BigEndian)
4810 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4811 else
4812 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004813 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004814 }
4815 } else if (EltTy->isIntegerType()) {
4816 for (unsigned i = 0; i < NElts; i++) {
4817 llvm::APInt Elt;
4818 if (BigEndian)
4819 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4820 else
4821 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4822 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4823 }
4824 } else {
4825 return Error(E);
4826 }
4827 return Success(Elts, E);
4828 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004829 default:
Richard Smith11562c52011-10-28 17:51:58 +00004830 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004831 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004832}
4833
Richard Smith2d406342011-10-22 21:10:00 +00004834bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004835VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004836 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004837 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004838 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004839
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004840 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004841 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004842
Eli Friedmanb9c71292012-01-03 23:24:20 +00004843 // The number of initializers can be less than the number of
4844 // vector elements. For OpenCL, this can be due to nested vector
4845 // initialization. For GCC compatibility, missing trailing elements
4846 // should be initialized with zeroes.
4847 unsigned CountInits = 0, CountElts = 0;
4848 while (CountElts < NumElements) {
4849 // Handle nested vector initialization.
4850 if (CountInits < NumInits
4851 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4852 APValue v;
4853 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4854 return Error(E);
4855 unsigned vlen = v.getVectorLength();
4856 for (unsigned j = 0; j < vlen; j++)
4857 Elements.push_back(v.getVectorElt(j));
4858 CountElts += vlen;
4859 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004860 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004861 if (CountInits < NumInits) {
4862 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004863 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004864 } else // trailing integer zero.
4865 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4866 Elements.push_back(APValue(sInt));
4867 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004868 } else {
4869 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004870 if (CountInits < NumInits) {
4871 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004872 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004873 } else // trailing float zero.
4874 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4875 Elements.push_back(APValue(f));
4876 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004877 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004878 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004879 }
Richard Smith2d406342011-10-22 21:10:00 +00004880 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004881}
4882
Richard Smith2d406342011-10-22 21:10:00 +00004883bool
Richard Smithfddd3842011-12-30 21:15:51 +00004884VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004885 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004886 QualType EltTy = VT->getElementType();
4887 APValue ZeroElement;
4888 if (EltTy->isIntegerType())
4889 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4890 else
4891 ZeroElement =
4892 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4893
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004894 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004895 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004896}
4897
Richard Smith2d406342011-10-22 21:10:00 +00004898bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004899 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004900 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004901}
4902
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004903//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004904// Array Evaluation
4905//===----------------------------------------------------------------------===//
4906
4907namespace {
4908 class ArrayExprEvaluator
4909 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004910 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004911 APValue &Result;
4912 public:
4913
Richard Smithd62306a2011-11-10 06:34:14 +00004914 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4915 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004916
4917 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004918 assert((V.isArray() || V.isLValue()) &&
4919 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004920 Result = V;
4921 return true;
4922 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004923
Richard Smithfddd3842011-12-30 21:15:51 +00004924 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004925 const ConstantArrayType *CAT =
4926 Info.Ctx.getAsConstantArrayType(E->getType());
4927 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004928 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004929
4930 Result = APValue(APValue::UninitArray(), 0,
4931 CAT->getSize().getZExtValue());
4932 if (!Result.hasArrayFiller()) return true;
4933
Richard Smithfddd3842011-12-30 21:15:51 +00004934 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004935 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004936 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004937 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004938 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004939 }
4940
Richard Smithf3e9e432011-11-07 09:22:26 +00004941 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004942 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004943 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4944 const LValue &Subobject,
4945 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004946 };
4947} // end anonymous namespace
4948
Richard Smithd62306a2011-11-10 06:34:14 +00004949static bool EvaluateArray(const Expr *E, const LValue &This,
4950 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004951 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004952 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004953}
4954
4955bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4956 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4957 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004958 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004959
Richard Smithca2cfbf2011-12-22 01:07:19 +00004960 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4961 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004962 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004963 LValue LV;
4964 if (!EvaluateLValue(E->getInit(0), LV, Info))
4965 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004966 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004967 LV.moveInto(Val);
4968 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004969 }
4970
Richard Smith253c2a32012-01-27 01:14:48 +00004971 bool Success = true;
4972
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004973 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4974 "zero-initialized array shouldn't have any initialized elts");
4975 APValue Filler;
4976 if (Result.isArray() && Result.hasArrayFiller())
4977 Filler = Result.getArrayFiller();
4978
Richard Smith9543c5e2013-04-22 14:44:29 +00004979 unsigned NumEltsToInit = E->getNumInits();
4980 unsigned NumElts = CAT->getSize().getZExtValue();
4981 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4982
4983 // If the initializer might depend on the array index, run it for each
4984 // array element. For now, just whitelist non-class value-initialization.
4985 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4986 NumEltsToInit = NumElts;
4987
4988 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004989
4990 // If the array was previously zero-initialized, preserve the
4991 // zero-initialized values.
4992 if (!Filler.isUninit()) {
4993 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4994 Result.getArrayInitializedElt(I) = Filler;
4995 if (Result.hasArrayFiller())
4996 Result.getArrayFiller() = Filler;
4997 }
4998
Richard Smithd62306a2011-11-10 06:34:14 +00004999 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005000 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005001 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5002 const Expr *Init =
5003 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005004 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005005 Info, Subobject, Init) ||
5006 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005007 CAT->getElementType(), 1)) {
5008 if (!Info.keepEvaluatingAfterFailure())
5009 return false;
5010 Success = false;
5011 }
Richard Smithd62306a2011-11-10 06:34:14 +00005012 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005013
Richard Smith9543c5e2013-04-22 14:44:29 +00005014 if (!Result.hasArrayFiller())
5015 return Success;
5016
5017 // If we get here, we have a trivial filler, which we can just evaluate
5018 // once and splat over the rest of the array elements.
5019 assert(FillerExpr && "no array filler for incomplete init list");
5020 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5021 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005022}
5023
Richard Smith027bf112011-11-17 22:56:20 +00005024bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005025 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5026}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005027
Richard Smith9543c5e2013-04-22 14:44:29 +00005028bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5029 const LValue &Subobject,
5030 APValue *Value,
5031 QualType Type) {
5032 bool HadZeroInit = !Value->isUninit();
5033
5034 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5035 unsigned N = CAT->getSize().getZExtValue();
5036
5037 // Preserve the array filler if we had prior zero-initialization.
5038 APValue Filler =
5039 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5040 : APValue();
5041
5042 *Value = APValue(APValue::UninitArray(), N, N);
5043
5044 if (HadZeroInit)
5045 for (unsigned I = 0; I != N; ++I)
5046 Value->getArrayInitializedElt(I) = Filler;
5047
5048 // Initialize the elements.
5049 LValue ArrayElt = Subobject;
5050 ArrayElt.addArray(Info, E, CAT);
5051 for (unsigned I = 0; I != N; ++I)
5052 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5053 CAT->getElementType()) ||
5054 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5055 CAT->getElementType(), 1))
5056 return false;
5057
5058 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005059 }
Richard Smith027bf112011-11-17 22:56:20 +00005060
Richard Smith9543c5e2013-04-22 14:44:29 +00005061 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005062 return Error(E);
5063
Richard Smith027bf112011-11-17 22:56:20 +00005064 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005065
Richard Smithfddd3842011-12-30 21:15:51 +00005066 bool ZeroInit = E->requiresZeroInitialization();
5067 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005068 if (HadZeroInit)
5069 return true;
5070
Richard Smithfddd3842011-12-30 21:15:51 +00005071 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005072 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005073 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005074 }
5075
Richard Smithcc36f692011-12-22 02:22:31 +00005076 const CXXRecordDecl *RD = FD->getParent();
5077 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005078 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005079 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005080 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005081 APValue(APValue::UninitStruct(), RD->getNumBases(),
5082 std::distance(RD->field_begin(), RD->field_end()));
5083 return true;
5084 }
5085
Richard Smith027bf112011-11-17 22:56:20 +00005086 const FunctionDecl *Definition = 0;
5087 FD->getBody(Definition);
5088
Richard Smith357362d2011-12-13 06:39:58 +00005089 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5090 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005091
Richard Smith9eae7232012-01-12 18:54:33 +00005092 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005093 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005094 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005095 return false;
5096 }
5097
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005098 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005099 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005100 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005101 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005102}
5103
Richard Smithf3e9e432011-11-07 09:22:26 +00005104//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005105// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005106//
5107// As a GNU extension, we support casting pointers to sufficiently-wide integer
5108// types and back in constant folding. Integer values are thus represented
5109// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005110//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005111
5112namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005113class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005114 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005115 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005116public:
Richard Smith2e312c82012-03-03 22:46:17 +00005117 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005118 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005119
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005120 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005121 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005122 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005123 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005124 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005125 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005126 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005127 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005128 return true;
5129 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005130 bool Success(const llvm::APSInt &SI, const Expr *E) {
5131 return Success(SI, E, Result);
5132 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005133
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005134 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005135 assert(E->getType()->isIntegralOrEnumerationType() &&
5136 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005137 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005138 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005139 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005140 Result.getInt().setIsUnsigned(
5141 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005142 return true;
5143 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005144 bool Success(const llvm::APInt &I, const Expr *E) {
5145 return Success(I, E, Result);
5146 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005147
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005148 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005149 assert(E->getType()->isIntegralOrEnumerationType() &&
5150 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005151 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005152 return true;
5153 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005154 bool Success(uint64_t Value, const Expr *E) {
5155 return Success(Value, E, Result);
5156 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005157
Ken Dyckdbc01912011-03-11 02:13:43 +00005158 bool Success(CharUnits Size, const Expr *E) {
5159 return Success(Size.getQuantity(), E);
5160 }
5161
Richard Smith2e312c82012-03-03 22:46:17 +00005162 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005163 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005164 Result = V;
5165 return true;
5166 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005167 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005168 }
Mike Stump11289f42009-09-09 15:08:12 +00005169
Richard Smithfddd3842011-12-30 21:15:51 +00005170 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005171
Peter Collingbournee9200682011-05-13 03:29:01 +00005172 //===--------------------------------------------------------------------===//
5173 // Visitor Methods
5174 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005175
Chris Lattner7174bf32008-07-12 00:38:25 +00005176 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005177 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005178 }
5179 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005180 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005181 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005182
5183 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5184 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005185 if (CheckReferencedDecl(E, E->getDecl()))
5186 return true;
5187
5188 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005189 }
5190 bool VisitMemberExpr(const MemberExpr *E) {
5191 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005192 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005193 return true;
5194 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005195
5196 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005197 }
5198
Peter Collingbournee9200682011-05-13 03:29:01 +00005199 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005200 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005201 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005202 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005203
Peter Collingbournee9200682011-05-13 03:29:01 +00005204 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005205 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005206
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005207 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005208 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005209 }
Mike Stump11289f42009-09-09 15:08:12 +00005210
Ted Kremeneke65b0862012-03-06 20:05:56 +00005211 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5212 return Success(E->getValue(), E);
5213 }
5214
Richard Smith4ce706a2011-10-11 21:43:33 +00005215 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005216 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005217 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005218 }
5219
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005220 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005221 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005222 }
5223
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005224 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5225 return Success(E->getValue(), E);
5226 }
5227
Douglas Gregor29c42f22012-02-24 07:38:34 +00005228 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5229 return Success(E->getValue(), E);
5230 }
5231
John Wiegley6242b6a2011-04-28 00:16:57 +00005232 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5233 return Success(E->getValue(), E);
5234 }
5235
John Wiegleyf9f65842011-04-25 06:54:41 +00005236 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5237 return Success(E->getValue(), E);
5238 }
5239
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005240 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005241 bool VisitUnaryImag(const UnaryOperator *E);
5242
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005243 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005244 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005245
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005246private:
Ken Dyck160146e2010-01-27 17:10:57 +00005247 CharUnits GetAlignOfExpr(const Expr *E);
5248 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005249 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005250 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005251 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005252};
Chris Lattner05706e882008-07-11 18:11:29 +00005253} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005254
Richard Smith11562c52011-10-28 17:51:58 +00005255/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5256/// produce either the integer value or a pointer.
5257///
5258/// GCC has a heinous extension which folds casts between pointer types and
5259/// pointer-sized integral types. We support this by allowing the evaluation of
5260/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5261/// Some simple arithmetic on such values is supported (they are treated much
5262/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005263static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005264 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005265 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005266 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005267}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005268
Richard Smithf57d8cb2011-12-09 22:58:01 +00005269static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005270 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005271 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005272 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005273 if (!Val.isInt()) {
5274 // FIXME: It would be better to produce the diagnostic for casting
5275 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005276 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005277 return false;
5278 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005279 Result = Val.getInt();
5280 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005281}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005282
Richard Smithf57d8cb2011-12-09 22:58:01 +00005283/// Check whether the given declaration can be directly converted to an integral
5284/// rvalue. If not, no diagnostic is produced; there are other things we can
5285/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005286bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005287 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005288 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005289 // Check for signedness/width mismatches between E type and ECD value.
5290 bool SameSign = (ECD->getInitVal().isSigned()
5291 == E->getType()->isSignedIntegerOrEnumerationType());
5292 bool SameWidth = (ECD->getInitVal().getBitWidth()
5293 == Info.Ctx.getIntWidth(E->getType()));
5294 if (SameSign && SameWidth)
5295 return Success(ECD->getInitVal(), E);
5296 else {
5297 // Get rid of mismatch (otherwise Success assertions will fail)
5298 // by computing a new value matching the type of E.
5299 llvm::APSInt Val = ECD->getInitVal();
5300 if (!SameSign)
5301 Val.setIsSigned(!ECD->getInitVal().isSigned());
5302 if (!SameWidth)
5303 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5304 return Success(Val, E);
5305 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005306 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005307 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005308}
5309
Chris Lattner86ee2862008-10-06 06:40:35 +00005310/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5311/// as GCC.
5312static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5313 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005314 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005315 enum gcc_type_class {
5316 no_type_class = -1,
5317 void_type_class, integer_type_class, char_type_class,
5318 enumeral_type_class, boolean_type_class,
5319 pointer_type_class, reference_type_class, offset_type_class,
5320 real_type_class, complex_type_class,
5321 function_type_class, method_type_class,
5322 record_type_class, union_type_class,
5323 array_type_class, string_type_class,
5324 lang_type_class
5325 };
Mike Stump11289f42009-09-09 15:08:12 +00005326
5327 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005328 // ideal, however it is what gcc does.
5329 if (E->getNumArgs() == 0)
5330 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005331
Chris Lattner86ee2862008-10-06 06:40:35 +00005332 QualType ArgTy = E->getArg(0)->getType();
5333 if (ArgTy->isVoidType())
5334 return void_type_class;
5335 else if (ArgTy->isEnumeralType())
5336 return enumeral_type_class;
5337 else if (ArgTy->isBooleanType())
5338 return boolean_type_class;
5339 else if (ArgTy->isCharType())
5340 return string_type_class; // gcc doesn't appear to use char_type_class
5341 else if (ArgTy->isIntegerType())
5342 return integer_type_class;
5343 else if (ArgTy->isPointerType())
5344 return pointer_type_class;
5345 else if (ArgTy->isReferenceType())
5346 return reference_type_class;
5347 else if (ArgTy->isRealType())
5348 return real_type_class;
5349 else if (ArgTy->isComplexType())
5350 return complex_type_class;
5351 else if (ArgTy->isFunctionType())
5352 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005353 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005354 return record_type_class;
5355 else if (ArgTy->isUnionType())
5356 return union_type_class;
5357 else if (ArgTy->isArrayType())
5358 return array_type_class;
5359 else if (ArgTy->isUnionType())
5360 return union_type_class;
5361 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005362 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005363}
5364
Richard Smith5fab0c92011-12-28 19:48:30 +00005365/// EvaluateBuiltinConstantPForLValue - Determine the result of
5366/// __builtin_constant_p when applied to the given lvalue.
5367///
5368/// An lvalue is only "constant" if it is a pointer or reference to the first
5369/// character of a string literal.
5370template<typename LValue>
5371static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005372 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005373 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5374}
5375
5376/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5377/// GCC as we can manage.
5378static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5379 QualType ArgType = Arg->getType();
5380
5381 // __builtin_constant_p always has one operand. The rules which gcc follows
5382 // are not precisely documented, but are as follows:
5383 //
5384 // - If the operand is of integral, floating, complex or enumeration type,
5385 // and can be folded to a known value of that type, it returns 1.
5386 // - If the operand and can be folded to a pointer to the first character
5387 // of a string literal (or such a pointer cast to an integral type), it
5388 // returns 1.
5389 //
5390 // Otherwise, it returns 0.
5391 //
5392 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5393 // its support for this does not currently work.
5394 if (ArgType->isIntegralOrEnumerationType()) {
5395 Expr::EvalResult Result;
5396 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5397 return false;
5398
5399 APValue &V = Result.Val;
5400 if (V.getKind() == APValue::Int)
5401 return true;
5402
5403 return EvaluateBuiltinConstantPForLValue(V);
5404 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5405 return Arg->isEvaluatable(Ctx);
5406 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5407 LValue LV;
5408 Expr::EvalStatus Status;
5409 EvalInfo Info(Ctx, Status);
5410 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5411 : EvaluatePointer(Arg, LV, Info)) &&
5412 !Status.HasSideEffects)
5413 return EvaluateBuiltinConstantPForLValue(LV);
5414 }
5415
5416 // Anything else isn't considered to be sufficiently constant.
5417 return false;
5418}
5419
John McCall95007602010-05-10 23:27:23 +00005420/// Retrieves the "underlying object type" of the given expression,
5421/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005422QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5423 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5424 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005425 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005426 } else if (const Expr *E = B.get<const Expr*>()) {
5427 if (isa<CompoundLiteralExpr>(E))
5428 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005429 }
5430
5431 return QualType();
5432}
5433
Peter Collingbournee9200682011-05-13 03:29:01 +00005434bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005435 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005436
5437 {
5438 // The operand of __builtin_object_size is never evaluated for side-effects.
5439 // If there are any, but we can determine the pointed-to object anyway, then
5440 // ignore the side-effects.
5441 SpeculativeEvaluationRAII SpeculativeEval(Info);
5442 if (!EvaluatePointer(E->getArg(0), Base, Info))
5443 return false;
5444 }
John McCall95007602010-05-10 23:27:23 +00005445
5446 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005447 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005448
Richard Smithce40ad62011-11-12 22:28:03 +00005449 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005450 if (T.isNull() ||
5451 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005452 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005453 T->isVariablyModifiedType() ||
5454 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005455 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005456
5457 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5458 CharUnits Offset = Base.getLValueOffset();
5459
5460 if (!Offset.isNegative() && Offset <= Size)
5461 Size -= Offset;
5462 else
5463 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005464 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005465}
5466
Peter Collingbournee9200682011-05-13 03:29:01 +00005467bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005468 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005469 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005470 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005471
5472 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005473 if (TryEvaluateBuiltinObjectSize(E))
5474 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005475
Richard Smith0421ce72012-08-07 04:16:51 +00005476 // If evaluating the argument has side-effects, we can't determine the size
5477 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5478 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005479 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005480 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005481 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005482 return Success(0, E);
5483 }
Mike Stump876387b2009-10-27 22:09:17 +00005484
Richard Smith01ade172012-05-23 04:13:20 +00005485 // Expression had no side effects, but we couldn't statically determine the
5486 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005487 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005488 }
5489
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005490 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005491 case Builtin::BI__builtin_bswap32:
5492 case Builtin::BI__builtin_bswap64: {
5493 APSInt Val;
5494 if (!EvaluateInteger(E->getArg(0), Val, Info))
5495 return false;
5496
5497 return Success(Val.byteSwap(), E);
5498 }
5499
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005500 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005501 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005502
Richard Smith5fab0c92011-12-28 19:48:30 +00005503 case Builtin::BI__builtin_constant_p:
5504 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005505
Chris Lattnerd545ad12009-09-23 06:06:36 +00005506 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005507 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005508 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005509 return Success(Operand, E);
5510 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005511
5512 case Builtin::BI__builtin_expect:
5513 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005514
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005515 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005516 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005517 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005518 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005519 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5520 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005521 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005522 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005523 case Builtin::BI__builtin_strlen:
5524 // As an extension, we support strlen() and __builtin_strlen() as constant
5525 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005526 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005527 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5528 // The string literal may have embedded null characters. Find the first
5529 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005530 StringRef Str = S->getString();
5531 StringRef::size_type Pos = Str.find(0);
5532 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005533 Str = Str.substr(0, Pos);
5534
5535 return Success(Str.size(), E);
5536 }
5537
Richard Smithf57d8cb2011-12-09 22:58:01 +00005538 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005539
Richard Smith01ba47d2012-04-13 00:45:38 +00005540 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005541 case Builtin::BI__atomic_is_lock_free:
5542 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005543 APSInt SizeVal;
5544 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5545 return false;
5546
5547 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5548 // of two less than the maximum inline atomic width, we know it is
5549 // lock-free. If the size isn't a power of two, or greater than the
5550 // maximum alignment where we promote atomics, we know it is not lock-free
5551 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5552 // the answer can only be determined at runtime; for example, 16-byte
5553 // atomics have lock-free implementations on some, but not all,
5554 // x86-64 processors.
5555
5556 // Check power-of-two.
5557 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005558 if (Size.isPowerOfTwo()) {
5559 // Check against inlining width.
5560 unsigned InlineWidthBits =
5561 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5562 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5563 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5564 Size == CharUnits::One() ||
5565 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5566 Expr::NPC_NeverValueDependent))
5567 // OK, we will inline appropriately-aligned operations of this size,
5568 // and _Atomic(T) is appropriately-aligned.
5569 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005570
Richard Smith01ba47d2012-04-13 00:45:38 +00005571 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5572 castAs<PointerType>()->getPointeeType();
5573 if (!PointeeType->isIncompleteType() &&
5574 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5575 // OK, we will inline operations on this object.
5576 return Success(1, E);
5577 }
5578 }
5579 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005580
Richard Smith01ba47d2012-04-13 00:45:38 +00005581 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5582 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005583 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005584 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005585}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005586
Richard Smith8b3497e2011-10-31 01:37:14 +00005587static bool HasSameBase(const LValue &A, const LValue &B) {
5588 if (!A.getLValueBase())
5589 return !B.getLValueBase();
5590 if (!B.getLValueBase())
5591 return false;
5592
Richard Smithce40ad62011-11-12 22:28:03 +00005593 if (A.getLValueBase().getOpaqueValue() !=
5594 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005595 const Decl *ADecl = GetLValueBaseDecl(A);
5596 if (!ADecl)
5597 return false;
5598 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005599 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005600 return false;
5601 }
5602
5603 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005604 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005605}
5606
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005607namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005608
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005609/// \brief Data recursive integer evaluator of certain binary operators.
5610///
5611/// We use a data recursive algorithm for binary operators so that we are able
5612/// to handle extreme cases of chained binary operators without causing stack
5613/// overflow.
5614class DataRecursiveIntBinOpEvaluator {
5615 struct EvalResult {
5616 APValue Val;
5617 bool Failed;
5618
5619 EvalResult() : Failed(false) { }
5620
5621 void swap(EvalResult &RHS) {
5622 Val.swap(RHS.Val);
5623 Failed = RHS.Failed;
5624 RHS.Failed = false;
5625 }
5626 };
5627
5628 struct Job {
5629 const Expr *E;
5630 EvalResult LHSResult; // meaningful only for binary operator expression.
5631 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5632
5633 Job() : StoredInfo(0) { }
5634 void startSpeculativeEval(EvalInfo &Info) {
5635 OldEvalStatus = Info.EvalStatus;
5636 Info.EvalStatus.Diag = 0;
5637 StoredInfo = &Info;
5638 }
5639 ~Job() {
5640 if (StoredInfo) {
5641 StoredInfo->EvalStatus = OldEvalStatus;
5642 }
5643 }
5644 private:
5645 EvalInfo *StoredInfo; // non-null if status changed.
5646 Expr::EvalStatus OldEvalStatus;
5647 };
5648
5649 SmallVector<Job, 16> Queue;
5650
5651 IntExprEvaluator &IntEval;
5652 EvalInfo &Info;
5653 APValue &FinalResult;
5654
5655public:
5656 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5657 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5658
5659 /// \brief True if \param E is a binary operator that we are going to handle
5660 /// data recursively.
5661 /// We handle binary operators that are comma, logical, or that have operands
5662 /// with integral or enumeration type.
5663 static bool shouldEnqueue(const BinaryOperator *E) {
5664 return E->getOpcode() == BO_Comma ||
5665 E->isLogicalOp() ||
5666 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5667 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005668 }
5669
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005670 bool Traverse(const BinaryOperator *E) {
5671 enqueue(E);
5672 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005673 while (!Queue.empty())
5674 process(PrevResult);
5675
5676 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005677
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005678 FinalResult.swap(PrevResult.Val);
5679 return true;
5680 }
5681
5682private:
5683 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5684 return IntEval.Success(Value, E, Result);
5685 }
5686 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5687 return IntEval.Success(Value, E, Result);
5688 }
5689 bool Error(const Expr *E) {
5690 return IntEval.Error(E);
5691 }
5692 bool Error(const Expr *E, diag::kind D) {
5693 return IntEval.Error(E, D);
5694 }
5695
5696 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5697 return Info.CCEDiag(E, D);
5698 }
5699
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005700 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5701 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005702 bool &SuppressRHSDiags);
5703
5704 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5705 const BinaryOperator *E, APValue &Result);
5706
5707 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5708 Result.Failed = !Evaluate(Result.Val, Info, E);
5709 if (Result.Failed)
5710 Result.Val = APValue();
5711 }
5712
Richard Trieuba4d0872012-03-21 23:30:30 +00005713 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005714
5715 void enqueue(const Expr *E) {
5716 E = E->IgnoreParens();
5717 Queue.resize(Queue.size()+1);
5718 Queue.back().E = E;
5719 Queue.back().Kind = Job::AnyExprKind;
5720 }
5721};
5722
5723}
5724
5725bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005726 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005727 bool &SuppressRHSDiags) {
5728 if (E->getOpcode() == BO_Comma) {
5729 // Ignore LHS but note if we could not evaluate it.
5730 if (LHSResult.Failed)
5731 Info.EvalStatus.HasSideEffects = true;
5732 return true;
5733 }
5734
5735 if (E->isLogicalOp()) {
5736 bool lhsResult;
5737 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005738 // We were able to evaluate the LHS, see if we can get away with not
5739 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005740 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005741 Success(lhsResult, E, LHSResult.Val);
5742 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005743 }
5744 } else {
5745 // Since we weren't able to evaluate the left hand side, it
5746 // must have had side effects.
5747 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005748
5749 // We can't evaluate the LHS; however, sometimes the result
5750 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5751 // Don't ignore RHS and suppress diagnostics from this arm.
5752 SuppressRHSDiags = true;
5753 }
5754
5755 return true;
5756 }
5757
5758 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5759 E->getRHS()->getType()->isIntegralOrEnumerationType());
5760
5761 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005762 return false; // Ignore RHS;
5763
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005764 return true;
5765}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005766
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005767bool DataRecursiveIntBinOpEvaluator::
5768 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5769 const BinaryOperator *E, APValue &Result) {
5770 if (E->getOpcode() == BO_Comma) {
5771 if (RHSResult.Failed)
5772 return false;
5773 Result = RHSResult.Val;
5774 return true;
5775 }
5776
5777 if (E->isLogicalOp()) {
5778 bool lhsResult, rhsResult;
5779 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5780 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5781
5782 if (LHSIsOK) {
5783 if (RHSIsOK) {
5784 if (E->getOpcode() == BO_LOr)
5785 return Success(lhsResult || rhsResult, E, Result);
5786 else
5787 return Success(lhsResult && rhsResult, E, Result);
5788 }
5789 } else {
5790 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005791 // We can't evaluate the LHS; however, sometimes the result
5792 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5793 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005794 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005795 }
5796 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005797
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005798 return false;
5799 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005800
5801 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5802 E->getRHS()->getType()->isIntegralOrEnumerationType());
5803
5804 if (LHSResult.Failed || RHSResult.Failed)
5805 return false;
5806
5807 const APValue &LHSVal = LHSResult.Val;
5808 const APValue &RHSVal = RHSResult.Val;
5809
5810 // Handle cases like (unsigned long)&a + 4.
5811 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5812 Result = LHSVal;
5813 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5814 RHSVal.getInt().getZExtValue());
5815 if (E->getOpcode() == BO_Add)
5816 Result.getLValueOffset() += AdditionalOffset;
5817 else
5818 Result.getLValueOffset() -= AdditionalOffset;
5819 return true;
5820 }
5821
5822 // Handle cases like 4 + (unsigned long)&a
5823 if (E->getOpcode() == BO_Add &&
5824 RHSVal.isLValue() && LHSVal.isInt()) {
5825 Result = RHSVal;
5826 Result.getLValueOffset() += CharUnits::fromQuantity(
5827 LHSVal.getInt().getZExtValue());
5828 return true;
5829 }
5830
5831 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5832 // Handle (intptr_t)&&A - (intptr_t)&&B.
5833 if (!LHSVal.getLValueOffset().isZero() ||
5834 !RHSVal.getLValueOffset().isZero())
5835 return false;
5836 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5837 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5838 if (!LHSExpr || !RHSExpr)
5839 return false;
5840 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5841 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5842 if (!LHSAddrExpr || !RHSAddrExpr)
5843 return false;
5844 // Make sure both labels come from the same function.
5845 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5846 RHSAddrExpr->getLabel()->getDeclContext())
5847 return false;
5848 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5849 return true;
5850 }
Richard Smith43e77732013-05-07 04:50:00 +00005851
5852 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005853 if (!LHSVal.isInt() || !RHSVal.isInt())
5854 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00005855
5856 // Set up the width and signedness manually, in case it can't be deduced
5857 // from the operation we're performing.
5858 // FIXME: Don't do this in the cases where we can deduce it.
5859 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
5860 E->getType()->isUnsignedIntegerOrEnumerationType());
5861 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
5862 RHSVal.getInt(), Value))
5863 return false;
5864 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005865}
5866
Richard Trieuba4d0872012-03-21 23:30:30 +00005867void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005868 Job &job = Queue.back();
5869
5870 switch (job.Kind) {
5871 case Job::AnyExprKind: {
5872 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5873 if (shouldEnqueue(Bop)) {
5874 job.Kind = Job::BinOpKind;
5875 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005876 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005877 }
5878 }
5879
5880 EvaluateExpr(job.E, Result);
5881 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005882 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005883 }
5884
5885 case Job::BinOpKind: {
5886 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005887 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005888 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005889 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005890 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005891 }
5892 if (SuppressRHSDiags)
5893 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005894 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005895 job.Kind = Job::BinOpVisitedLHSKind;
5896 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005897 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005898 }
5899
5900 case Job::BinOpVisitedLHSKind: {
5901 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5902 EvalResult RHS;
5903 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005904 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005905 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005906 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005907 }
5908 }
5909
5910 llvm_unreachable("Invalid Job::Kind!");
5911}
5912
5913bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5914 if (E->isAssignmentOp())
5915 return Error(E);
5916
5917 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5918 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005919
Anders Carlssonacc79812008-11-16 07:17:21 +00005920 QualType LHSTy = E->getLHS()->getType();
5921 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005922
5923 if (LHSTy->isAnyComplexType()) {
5924 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005925 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005926
Richard Smith253c2a32012-01-27 01:14:48 +00005927 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5928 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005929 return false;
5930
Richard Smith253c2a32012-01-27 01:14:48 +00005931 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005932 return false;
5933
5934 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005935 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005936 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005937 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005938 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5939
John McCalle3027922010-08-25 11:45:40 +00005940 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005941 return Success((CR_r == APFloat::cmpEqual &&
5942 CR_i == APFloat::cmpEqual), E);
5943 else {
John McCalle3027922010-08-25 11:45:40 +00005944 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005945 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005946 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005947 CR_r == APFloat::cmpLessThan ||
5948 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005949 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005950 CR_i == APFloat::cmpLessThan ||
5951 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005952 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005953 } else {
John McCalle3027922010-08-25 11:45:40 +00005954 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005955 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5956 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5957 else {
John McCalle3027922010-08-25 11:45:40 +00005958 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005959 "Invalid compex comparison.");
5960 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5961 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5962 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005963 }
5964 }
Mike Stump11289f42009-09-09 15:08:12 +00005965
Anders Carlssonacc79812008-11-16 07:17:21 +00005966 if (LHSTy->isRealFloatingType() &&
5967 RHSTy->isRealFloatingType()) {
5968 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005969
Richard Smith253c2a32012-01-27 01:14:48 +00005970 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5971 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005972 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005973
Richard Smith253c2a32012-01-27 01:14:48 +00005974 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005975 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005976
Anders Carlssonacc79812008-11-16 07:17:21 +00005977 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005978
Anders Carlssonacc79812008-11-16 07:17:21 +00005979 switch (E->getOpcode()) {
5980 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005981 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005982 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005983 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005984 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005985 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005986 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005987 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005988 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005989 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005990 E);
John McCalle3027922010-08-25 11:45:40 +00005991 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005992 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005993 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005994 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005995 || CR == APFloat::cmpLessThan
5996 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005997 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005998 }
Mike Stump11289f42009-09-09 15:08:12 +00005999
Eli Friedmana38da572009-04-28 19:17:36 +00006000 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006001 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006002 LValue LHSValue, RHSValue;
6003
6004 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6005 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006006 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006007
Richard Smith253c2a32012-01-27 01:14:48 +00006008 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006009 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006010
Richard Smith8b3497e2011-10-31 01:37:14 +00006011 // Reject differing bases from the normal codepath; we special-case
6012 // comparisons to null.
6013 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006014 if (E->getOpcode() == BO_Sub) {
6015 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006016 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6017 return false;
6018 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006019 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006020 if (!LHSExpr || !RHSExpr)
6021 return false;
6022 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6023 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6024 if (!LHSAddrExpr || !RHSAddrExpr)
6025 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006026 // Make sure both labels come from the same function.
6027 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6028 RHSAddrExpr->getLabel()->getDeclContext())
6029 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006030 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006031 return true;
6032 }
Richard Smith83c68212011-10-31 05:11:32 +00006033 // Inequalities and subtractions between unrelated pointers have
6034 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006035 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006036 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006037 // A constant address may compare equal to the address of a symbol.
6038 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006039 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006040 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6041 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006042 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006043 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006044 // distinct addresses. In clang, the result of such a comparison is
6045 // unspecified, so it is not a constant expression. However, we do know
6046 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006047 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6048 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006049 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006050 // We can't tell whether weak symbols will end up pointing to the same
6051 // object.
6052 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006053 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006054 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006055 // (Note that clang defaults to -fmerge-all-constants, which can
6056 // lead to inconsistent results for comparisons involving the address
6057 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006058 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006059 }
Eli Friedman64004332009-03-23 04:38:34 +00006060
Richard Smith1b470412012-02-01 08:10:20 +00006061 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6062 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6063
Richard Smith84f6dcf2012-02-02 01:16:57 +00006064 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6065 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6066
John McCalle3027922010-08-25 11:45:40 +00006067 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006068 // C++11 [expr.add]p6:
6069 // Unless both pointers point to elements of the same array object, or
6070 // one past the last element of the array object, the behavior is
6071 // undefined.
6072 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6073 !AreElementsOfSameArray(getType(LHSValue.Base),
6074 LHSDesignator, RHSDesignator))
6075 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6076
Chris Lattner882bdf22010-04-20 17:13:14 +00006077 QualType Type = E->getLHS()->getType();
6078 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006079
Richard Smithd62306a2011-11-10 06:34:14 +00006080 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006081 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006082 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006083
Richard Smith1b470412012-02-01 08:10:20 +00006084 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6085 // and produce incorrect results when it overflows. Such behavior
6086 // appears to be non-conforming, but is common, so perhaps we should
6087 // assume the standard intended for such cases to be undefined behavior
6088 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006089
Richard Smith1b470412012-02-01 08:10:20 +00006090 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6091 // overflow in the final conversion to ptrdiff_t.
6092 APSInt LHS(
6093 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6094 APSInt RHS(
6095 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6096 APSInt ElemSize(
6097 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6098 APSInt TrueResult = (LHS - RHS) / ElemSize;
6099 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6100
6101 if (Result.extend(65) != TrueResult)
6102 HandleOverflow(Info, E, TrueResult, E->getType());
6103 return Success(Result, E);
6104 }
Richard Smithde21b242012-01-31 06:41:30 +00006105
6106 // C++11 [expr.rel]p3:
6107 // Pointers to void (after pointer conversions) can be compared, with a
6108 // result defined as follows: If both pointers represent the same
6109 // address or are both the null pointer value, the result is true if the
6110 // operator is <= or >= and false otherwise; otherwise the result is
6111 // unspecified.
6112 // We interpret this as applying to pointers to *cv* void.
6113 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006114 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006115 CCEDiag(E, diag::note_constexpr_void_comparison);
6116
Richard Smith84f6dcf2012-02-02 01:16:57 +00006117 // C++11 [expr.rel]p2:
6118 // - If two pointers point to non-static data members of the same object,
6119 // or to subobjects or array elements fo such members, recursively, the
6120 // pointer to the later declared member compares greater provided the
6121 // two members have the same access control and provided their class is
6122 // not a union.
6123 // [...]
6124 // - Otherwise pointer comparisons are unspecified.
6125 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6126 E->isRelationalOp()) {
6127 bool WasArrayIndex;
6128 unsigned Mismatch =
6129 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6130 RHSDesignator, WasArrayIndex);
6131 // At the point where the designators diverge, the comparison has a
6132 // specified value if:
6133 // - we are comparing array indices
6134 // - we are comparing fields of a union, or fields with the same access
6135 // Otherwise, the result is unspecified and thus the comparison is not a
6136 // constant expression.
6137 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6138 Mismatch < RHSDesignator.Entries.size()) {
6139 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6140 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6141 if (!LF && !RF)
6142 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6143 else if (!LF)
6144 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6145 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6146 << RF->getParent() << RF;
6147 else if (!RF)
6148 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6149 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6150 << LF->getParent() << LF;
6151 else if (!LF->getParent()->isUnion() &&
6152 LF->getAccess() != RF->getAccess())
6153 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6154 << LF << LF->getAccess() << RF << RF->getAccess()
6155 << LF->getParent();
6156 }
6157 }
6158
Eli Friedman6c31cb42012-04-16 04:30:08 +00006159 // The comparison here must be unsigned, and performed with the same
6160 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006161 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6162 uint64_t CompareLHS = LHSOffset.getQuantity();
6163 uint64_t CompareRHS = RHSOffset.getQuantity();
6164 assert(PtrSize <= 64 && "Unexpected pointer width");
6165 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6166 CompareLHS &= Mask;
6167 CompareRHS &= Mask;
6168
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006169 // If there is a base and this is a relational operator, we can only
6170 // compare pointers within the object in question; otherwise, the result
6171 // depends on where the object is located in memory.
6172 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6173 QualType BaseTy = getType(LHSValue.Base);
6174 if (BaseTy->isIncompleteType())
6175 return Error(E);
6176 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6177 uint64_t OffsetLimit = Size.getQuantity();
6178 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6179 return Error(E);
6180 }
6181
Richard Smith8b3497e2011-10-31 01:37:14 +00006182 switch (E->getOpcode()) {
6183 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006184 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6185 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6186 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6187 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6188 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6189 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006190 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006191 }
6192 }
Richard Smith7bb00672012-02-01 01:42:44 +00006193
6194 if (LHSTy->isMemberPointerType()) {
6195 assert(E->isEqualityOp() && "unexpected member pointer operation");
6196 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6197
6198 MemberPtr LHSValue, RHSValue;
6199
6200 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6201 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6202 return false;
6203
6204 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6205 return false;
6206
6207 // C++11 [expr.eq]p2:
6208 // If both operands are null, they compare equal. Otherwise if only one is
6209 // null, they compare unequal.
6210 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6211 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6212 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6213 }
6214
6215 // Otherwise if either is a pointer to a virtual member function, the
6216 // result is unspecified.
6217 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6218 if (MD->isVirtual())
6219 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6220 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6221 if (MD->isVirtual())
6222 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6223
6224 // Otherwise they compare equal if and only if they would refer to the
6225 // same member of the same most derived object or the same subobject if
6226 // they were dereferenced with a hypothetical object of the associated
6227 // class type.
6228 bool Equal = LHSValue == RHSValue;
6229 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6230 }
6231
Richard Smithab44d9b2012-02-14 22:35:28 +00006232 if (LHSTy->isNullPtrType()) {
6233 assert(E->isComparisonOp() && "unexpected nullptr operation");
6234 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6235 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6236 // are compared, the result is true of the operator is <=, >= or ==, and
6237 // false otherwise.
6238 BinaryOperator::Opcode Opcode = E->getOpcode();
6239 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6240 }
6241
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006242 assert((!LHSTy->isIntegralOrEnumerationType() ||
6243 !RHSTy->isIntegralOrEnumerationType()) &&
6244 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6245 // We can't continue from here for non-integral types.
6246 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006247}
6248
Ken Dyck160146e2010-01-27 17:10:57 +00006249CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006250 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6251 // result shall be the alignment of the referenced type."
6252 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6253 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006254
6255 // __alignof is defined to return the preferred alignment.
6256 return Info.Ctx.toCharUnitsFromBits(
6257 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006258}
6259
Ken Dyck160146e2010-01-27 17:10:57 +00006260CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006261 E = E->IgnoreParens();
6262
John McCall768439e2013-05-06 07:40:34 +00006263 // The kinds of expressions that we have special-case logic here for
6264 // should be kept up to date with the special checks for those
6265 // expressions in Sema.
6266
Chris Lattner68061312009-01-24 21:53:27 +00006267 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006268 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006269 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006270 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6271 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006272
Chris Lattner68061312009-01-24 21:53:27 +00006273 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006274 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6275 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006276
Chris Lattner24aeeab2009-01-24 21:09:06 +00006277 return GetAlignOfType(E->getType());
6278}
6279
6280
Peter Collingbournee190dee2011-03-11 19:24:49 +00006281/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6282/// a result as the expression's type.
6283bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6284 const UnaryExprOrTypeTraitExpr *E) {
6285 switch(E->getKind()) {
6286 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006287 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006288 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006289 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006290 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006291 }
Eli Friedman64004332009-03-23 04:38:34 +00006292
Peter Collingbournee190dee2011-03-11 19:24:49 +00006293 case UETT_VecStep: {
6294 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006295
Peter Collingbournee190dee2011-03-11 19:24:49 +00006296 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006297 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006298
Peter Collingbournee190dee2011-03-11 19:24:49 +00006299 // The vec_step built-in functions that take a 3-component
6300 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6301 if (n == 3)
6302 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006303
Peter Collingbournee190dee2011-03-11 19:24:49 +00006304 return Success(n, E);
6305 } else
6306 return Success(1, E);
6307 }
6308
6309 case UETT_SizeOf: {
6310 QualType SrcTy = E->getTypeOfArgument();
6311 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6312 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006313 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6314 SrcTy = Ref->getPointeeType();
6315
Richard Smithd62306a2011-11-10 06:34:14 +00006316 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006317 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006318 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006319 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006320 }
6321 }
6322
6323 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006324}
6325
Peter Collingbournee9200682011-05-13 03:29:01 +00006326bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006327 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006328 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006329 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006330 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006331 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006332 for (unsigned i = 0; i != n; ++i) {
6333 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6334 switch (ON.getKind()) {
6335 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006336 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006337 APSInt IdxResult;
6338 if (!EvaluateInteger(Idx, IdxResult, Info))
6339 return false;
6340 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6341 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006342 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006343 CurrentType = AT->getElementType();
6344 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6345 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006346 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006347 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006348
Douglas Gregor882211c2010-04-28 22:16:22 +00006349 case OffsetOfExpr::OffsetOfNode::Field: {
6350 FieldDecl *MemberDecl = ON.getField();
6351 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006352 if (!RT)
6353 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006354 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006355 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006356 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006357 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006358 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006359 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006360 CurrentType = MemberDecl->getType().getNonReferenceType();
6361 break;
6362 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006363
Douglas Gregor882211c2010-04-28 22:16:22 +00006364 case OffsetOfExpr::OffsetOfNode::Identifier:
6365 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006366
Douglas Gregord1702062010-04-29 00:18:15 +00006367 case OffsetOfExpr::OffsetOfNode::Base: {
6368 CXXBaseSpecifier *BaseSpec = ON.getBase();
6369 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006370 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006371
6372 // Find the layout of the class whose base we are looking into.
6373 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006374 if (!RT)
6375 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006376 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006377 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006378 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6379
6380 // Find the base class itself.
6381 CurrentType = BaseSpec->getType();
6382 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6383 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006384 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006385
6386 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006387 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006388 break;
6389 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006390 }
6391 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006392 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006393}
6394
Chris Lattnere13042c2008-07-11 19:10:17 +00006395bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006396 switch (E->getOpcode()) {
6397 default:
6398 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6399 // See C99 6.6p3.
6400 return Error(E);
6401 case UO_Extension:
6402 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6403 // If so, we could clear the diagnostic ID.
6404 return Visit(E->getSubExpr());
6405 case UO_Plus:
6406 // The result is just the value.
6407 return Visit(E->getSubExpr());
6408 case UO_Minus: {
6409 if (!Visit(E->getSubExpr()))
6410 return false;
6411 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006412 const APSInt &Value = Result.getInt();
6413 if (Value.isSigned() && Value.isMinSignedValue())
6414 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6415 E->getType());
6416 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006417 }
6418 case UO_Not: {
6419 if (!Visit(E->getSubExpr()))
6420 return false;
6421 if (!Result.isInt()) return Error(E);
6422 return Success(~Result.getInt(), E);
6423 }
6424 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006425 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006426 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006427 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006428 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006429 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006430 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006431}
Mike Stump11289f42009-09-09 15:08:12 +00006432
Chris Lattner477c4be2008-07-12 01:15:53 +00006433/// HandleCast - This is used to evaluate implicit or explicit casts where the
6434/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006435bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6436 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006437 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006438 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006439
Eli Friedmanc757de22011-03-25 00:43:55 +00006440 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006441 case CK_BaseToDerived:
6442 case CK_DerivedToBase:
6443 case CK_UncheckedDerivedToBase:
6444 case CK_Dynamic:
6445 case CK_ToUnion:
6446 case CK_ArrayToPointerDecay:
6447 case CK_FunctionToPointerDecay:
6448 case CK_NullToPointer:
6449 case CK_NullToMemberPointer:
6450 case CK_BaseToDerivedMemberPointer:
6451 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006452 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006453 case CK_ConstructorConversion:
6454 case CK_IntegralToPointer:
6455 case CK_ToVoid:
6456 case CK_VectorSplat:
6457 case CK_IntegralToFloating:
6458 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006459 case CK_CPointerToObjCPointerCast:
6460 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006461 case CK_AnyPointerToBlockPointerCast:
6462 case CK_ObjCObjectLValueCast:
6463 case CK_FloatingRealToComplex:
6464 case CK_FloatingComplexToReal:
6465 case CK_FloatingComplexCast:
6466 case CK_FloatingComplexToIntegralComplex:
6467 case CK_IntegralRealToComplex:
6468 case CK_IntegralComplexCast:
6469 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006470 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006471 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006472 llvm_unreachable("invalid cast kind for integral value");
6473
Eli Friedman9faf2f92011-03-25 19:07:11 +00006474 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006475 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006476 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006477 case CK_ARCProduceObject:
6478 case CK_ARCConsumeObject:
6479 case CK_ARCReclaimReturnedObject:
6480 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006481 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006482 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006483
Richard Smith4ef685b2012-01-17 21:17:26 +00006484 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006485 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006486 case CK_AtomicToNonAtomic:
6487 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006488 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006489 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006490
6491 case CK_MemberPointerToBoolean:
6492 case CK_PointerToBoolean:
6493 case CK_IntegralToBoolean:
6494 case CK_FloatingToBoolean:
6495 case CK_FloatingComplexToBoolean:
6496 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006497 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006498 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006499 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006500 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006501 }
6502
Eli Friedmanc757de22011-03-25 00:43:55 +00006503 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006504 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006505 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006506
Eli Friedman742421e2009-02-20 01:15:07 +00006507 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006508 // Allow casts of address-of-label differences if they are no-ops
6509 // or narrowing. (The narrowing case isn't actually guaranteed to
6510 // be constant-evaluatable except in some narrow cases which are hard
6511 // to detect here. We let it through on the assumption the user knows
6512 // what they are doing.)
6513 if (Result.isAddrLabelDiff())
6514 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006515 // Only allow casts of lvalues if they are lossless.
6516 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6517 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006518
Richard Smith911e1422012-01-30 22:27:01 +00006519 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6520 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006521 }
Mike Stump11289f42009-09-09 15:08:12 +00006522
Eli Friedmanc757de22011-03-25 00:43:55 +00006523 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006524 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6525
John McCall45d55e42010-05-07 21:00:08 +00006526 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006527 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006528 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006529
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006530 if (LV.getLValueBase()) {
6531 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006532 // FIXME: Allow a larger integer size than the pointer size, and allow
6533 // narrowing back down to pointer width in subsequent integral casts.
6534 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006535 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006536 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006537
Richard Smithcf74da72011-11-16 07:18:12 +00006538 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006539 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006540 return true;
6541 }
6542
Ken Dyck02990832010-01-15 12:37:54 +00006543 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6544 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006545 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006546 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006547
Eli Friedmanc757de22011-03-25 00:43:55 +00006548 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006549 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006550 if (!EvaluateComplex(SubExpr, C, Info))
6551 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006552 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006553 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006554
Eli Friedmanc757de22011-03-25 00:43:55 +00006555 case CK_FloatingToIntegral: {
6556 APFloat F(0.0);
6557 if (!EvaluateFloat(SubExpr, F, Info))
6558 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006559
Richard Smith357362d2011-12-13 06:39:58 +00006560 APSInt Value;
6561 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6562 return false;
6563 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006564 }
6565 }
Mike Stump11289f42009-09-09 15:08:12 +00006566
Eli Friedmanc757de22011-03-25 00:43:55 +00006567 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006568}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006569
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006570bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6571 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006572 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006573 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6574 return false;
6575 if (!LV.isComplexInt())
6576 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006577 return Success(LV.getComplexIntReal(), E);
6578 }
6579
6580 return Visit(E->getSubExpr());
6581}
6582
Eli Friedman4e7a2412009-02-27 04:45:43 +00006583bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006584 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006585 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006586 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6587 return false;
6588 if (!LV.isComplexInt())
6589 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006590 return Success(LV.getComplexIntImag(), E);
6591 }
6592
Richard Smith4a678122011-10-24 18:44:57 +00006593 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006594 return Success(0, E);
6595}
6596
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006597bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6598 return Success(E->getPackLength(), E);
6599}
6600
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006601bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6602 return Success(E->getValue(), E);
6603}
6604
Chris Lattner05706e882008-07-11 18:11:29 +00006605//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006606// Float Evaluation
6607//===----------------------------------------------------------------------===//
6608
6609namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006610class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006611 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006612 APFloat &Result;
6613public:
6614 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006615 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006616
Richard Smith2e312c82012-03-03 22:46:17 +00006617 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006618 Result = V.getFloat();
6619 return true;
6620 }
Eli Friedman24c01542008-08-22 00:06:13 +00006621
Richard Smithfddd3842011-12-30 21:15:51 +00006622 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006623 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6624 return true;
6625 }
6626
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006627 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006628
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006629 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006630 bool VisitBinaryOperator(const BinaryOperator *E);
6631 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006632 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006633
John McCallb1fb0d32010-05-07 22:08:54 +00006634 bool VisitUnaryReal(const UnaryOperator *E);
6635 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006636
Richard Smithfddd3842011-12-30 21:15:51 +00006637 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006638};
6639} // end anonymous namespace
6640
6641static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006642 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006643 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006644}
6645
Jay Foad39c79802011-01-12 09:06:06 +00006646static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006647 QualType ResultTy,
6648 const Expr *Arg,
6649 bool SNaN,
6650 llvm::APFloat &Result) {
6651 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6652 if (!S) return false;
6653
6654 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6655
6656 llvm::APInt fill;
6657
6658 // Treat empty strings as if they were zero.
6659 if (S->getString().empty())
6660 fill = llvm::APInt(32, 0);
6661 else if (S->getString().getAsInteger(0, fill))
6662 return false;
6663
6664 if (SNaN)
6665 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6666 else
6667 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6668 return true;
6669}
6670
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006671bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006672 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006673 default:
6674 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6675
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006676 case Builtin::BI__builtin_huge_val:
6677 case Builtin::BI__builtin_huge_valf:
6678 case Builtin::BI__builtin_huge_vall:
6679 case Builtin::BI__builtin_inf:
6680 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006681 case Builtin::BI__builtin_infl: {
6682 const llvm::fltSemantics &Sem =
6683 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006684 Result = llvm::APFloat::getInf(Sem);
6685 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006686 }
Mike Stump11289f42009-09-09 15:08:12 +00006687
John McCall16291492010-02-28 13:00:19 +00006688 case Builtin::BI__builtin_nans:
6689 case Builtin::BI__builtin_nansf:
6690 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006691 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6692 true, Result))
6693 return Error(E);
6694 return true;
John McCall16291492010-02-28 13:00:19 +00006695
Chris Lattner0b7282e2008-10-06 06:31:58 +00006696 case Builtin::BI__builtin_nan:
6697 case Builtin::BI__builtin_nanf:
6698 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006699 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006700 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006701 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6702 false, Result))
6703 return Error(E);
6704 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006705
6706 case Builtin::BI__builtin_fabs:
6707 case Builtin::BI__builtin_fabsf:
6708 case Builtin::BI__builtin_fabsl:
6709 if (!EvaluateFloat(E->getArg(0), Result, Info))
6710 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006711
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006712 if (Result.isNegative())
6713 Result.changeSign();
6714 return true;
6715
Mike Stump11289f42009-09-09 15:08:12 +00006716 case Builtin::BI__builtin_copysign:
6717 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006718 case Builtin::BI__builtin_copysignl: {
6719 APFloat RHS(0.);
6720 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6721 !EvaluateFloat(E->getArg(1), RHS, Info))
6722 return false;
6723 Result.copySign(RHS);
6724 return true;
6725 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006726 }
6727}
6728
John McCallb1fb0d32010-05-07 22:08:54 +00006729bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006730 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6731 ComplexValue CV;
6732 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6733 return false;
6734 Result = CV.FloatReal;
6735 return true;
6736 }
6737
6738 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006739}
6740
6741bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006742 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6743 ComplexValue CV;
6744 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6745 return false;
6746 Result = CV.FloatImag;
6747 return true;
6748 }
6749
Richard Smith4a678122011-10-24 18:44:57 +00006750 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006751 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6752 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006753 return true;
6754}
6755
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006756bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006757 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006758 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006759 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006760 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006761 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006762 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6763 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006764 Result.changeSign();
6765 return true;
6766 }
6767}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006768
Eli Friedman24c01542008-08-22 00:06:13 +00006769bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006770 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6771 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006772
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006773 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006774 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6775 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006776 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006777 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
6778 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00006779}
6780
6781bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6782 Result = E->getValue();
6783 return true;
6784}
6785
Peter Collingbournee9200682011-05-13 03:29:01 +00006786bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6787 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006788
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006789 switch (E->getCastKind()) {
6790 default:
Richard Smith11562c52011-10-28 17:51:58 +00006791 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006792
6793 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006794 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006795 return EvaluateInteger(SubExpr, IntResult, Info) &&
6796 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6797 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006798 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006799
6800 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006801 if (!Visit(SubExpr))
6802 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006803 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6804 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006805 }
John McCalld7646252010-11-14 08:17:51 +00006806
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006807 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006808 ComplexValue V;
6809 if (!EvaluateComplex(SubExpr, V, Info))
6810 return false;
6811 Result = V.getComplexFloatReal();
6812 return true;
6813 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006814 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006815}
6816
Eli Friedman24c01542008-08-22 00:06:13 +00006817//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006818// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006819//===----------------------------------------------------------------------===//
6820
6821namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006822class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006823 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006824 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006825
Anders Carlsson537969c2008-11-16 20:27:53 +00006826public:
John McCall93d91dc2010-05-07 17:22:02 +00006827 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006828 : ExprEvaluatorBaseTy(info), Result(Result) {}
6829
Richard Smith2e312c82012-03-03 22:46:17 +00006830 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006831 Result.setFrom(V);
6832 return true;
6833 }
Mike Stump11289f42009-09-09 15:08:12 +00006834
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006835 bool ZeroInitialization(const Expr *E);
6836
Anders Carlsson537969c2008-11-16 20:27:53 +00006837 //===--------------------------------------------------------------------===//
6838 // Visitor Methods
6839 //===--------------------------------------------------------------------===//
6840
Peter Collingbournee9200682011-05-13 03:29:01 +00006841 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006842 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006843 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006844 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006845 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006846};
6847} // end anonymous namespace
6848
John McCall93d91dc2010-05-07 17:22:02 +00006849static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6850 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006851 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006852 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006853}
6854
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006855bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006856 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006857 if (ElemTy->isRealFloatingType()) {
6858 Result.makeComplexFloat();
6859 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6860 Result.FloatReal = Zero;
6861 Result.FloatImag = Zero;
6862 } else {
6863 Result.makeComplexInt();
6864 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6865 Result.IntReal = Zero;
6866 Result.IntImag = Zero;
6867 }
6868 return true;
6869}
6870
Peter Collingbournee9200682011-05-13 03:29:01 +00006871bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6872 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006873
6874 if (SubExpr->getType()->isRealFloatingType()) {
6875 Result.makeComplexFloat();
6876 APFloat &Imag = Result.FloatImag;
6877 if (!EvaluateFloat(SubExpr, Imag, Info))
6878 return false;
6879
6880 Result.FloatReal = APFloat(Imag.getSemantics());
6881 return true;
6882 } else {
6883 assert(SubExpr->getType()->isIntegerType() &&
6884 "Unexpected imaginary literal.");
6885
6886 Result.makeComplexInt();
6887 APSInt &Imag = Result.IntImag;
6888 if (!EvaluateInteger(SubExpr, Imag, Info))
6889 return false;
6890
6891 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6892 return true;
6893 }
6894}
6895
Peter Collingbournee9200682011-05-13 03:29:01 +00006896bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006897
John McCallfcef3cf2010-12-14 17:51:41 +00006898 switch (E->getCastKind()) {
6899 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006900 case CK_BaseToDerived:
6901 case CK_DerivedToBase:
6902 case CK_UncheckedDerivedToBase:
6903 case CK_Dynamic:
6904 case CK_ToUnion:
6905 case CK_ArrayToPointerDecay:
6906 case CK_FunctionToPointerDecay:
6907 case CK_NullToPointer:
6908 case CK_NullToMemberPointer:
6909 case CK_BaseToDerivedMemberPointer:
6910 case CK_DerivedToBaseMemberPointer:
6911 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006912 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006913 case CK_ConstructorConversion:
6914 case CK_IntegralToPointer:
6915 case CK_PointerToIntegral:
6916 case CK_PointerToBoolean:
6917 case CK_ToVoid:
6918 case CK_VectorSplat:
6919 case CK_IntegralCast:
6920 case CK_IntegralToBoolean:
6921 case CK_IntegralToFloating:
6922 case CK_FloatingToIntegral:
6923 case CK_FloatingToBoolean:
6924 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006925 case CK_CPointerToObjCPointerCast:
6926 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006927 case CK_AnyPointerToBlockPointerCast:
6928 case CK_ObjCObjectLValueCast:
6929 case CK_FloatingComplexToReal:
6930 case CK_FloatingComplexToBoolean:
6931 case CK_IntegralComplexToReal:
6932 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006933 case CK_ARCProduceObject:
6934 case CK_ARCConsumeObject:
6935 case CK_ARCReclaimReturnedObject:
6936 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006937 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006938 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006939 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006940 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006941
John McCallfcef3cf2010-12-14 17:51:41 +00006942 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006943 case CK_AtomicToNonAtomic:
6944 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006945 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006946 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006947
6948 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006949 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006950 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006951 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006952
6953 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006954 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006955 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006956 return false;
6957
John McCallfcef3cf2010-12-14 17:51:41 +00006958 Result.makeComplexFloat();
6959 Result.FloatImag = APFloat(Real.getSemantics());
6960 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006961 }
6962
John McCallfcef3cf2010-12-14 17:51:41 +00006963 case CK_FloatingComplexCast: {
6964 if (!Visit(E->getSubExpr()))
6965 return false;
6966
6967 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6968 QualType From
6969 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6970
Richard Smith357362d2011-12-13 06:39:58 +00006971 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6972 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006973 }
6974
6975 case CK_FloatingComplexToIntegralComplex: {
6976 if (!Visit(E->getSubExpr()))
6977 return false;
6978
6979 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6980 QualType From
6981 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6982 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006983 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6984 To, Result.IntReal) &&
6985 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6986 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006987 }
6988
6989 case CK_IntegralRealToComplex: {
6990 APSInt &Real = Result.IntReal;
6991 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6992 return false;
6993
6994 Result.makeComplexInt();
6995 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6996 return true;
6997 }
6998
6999 case CK_IntegralComplexCast: {
7000 if (!Visit(E->getSubExpr()))
7001 return false;
7002
7003 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7004 QualType From
7005 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7006
Richard Smith911e1422012-01-30 22:27:01 +00007007 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7008 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007009 return true;
7010 }
7011
7012 case CK_IntegralComplexToFloatingComplex: {
7013 if (!Visit(E->getSubExpr()))
7014 return false;
7015
Ted Kremenek28831752012-08-23 20:46:57 +00007016 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007017 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007018 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007019 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007020 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7021 To, Result.FloatReal) &&
7022 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7023 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007024 }
7025 }
7026
7027 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007028}
7029
John McCall93d91dc2010-05-07 17:22:02 +00007030bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007031 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007032 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7033
Richard Smith253c2a32012-01-27 01:14:48 +00007034 bool LHSOK = Visit(E->getLHS());
7035 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007036 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007037
John McCall93d91dc2010-05-07 17:22:02 +00007038 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007039 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007040 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007041
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007042 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7043 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007044 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007045 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007046 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007047 if (Result.isComplexFloat()) {
7048 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7049 APFloat::rmNearestTiesToEven);
7050 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7051 APFloat::rmNearestTiesToEven);
7052 } else {
7053 Result.getComplexIntReal() += RHS.getComplexIntReal();
7054 Result.getComplexIntImag() += RHS.getComplexIntImag();
7055 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007056 break;
John McCalle3027922010-08-25 11:45:40 +00007057 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007058 if (Result.isComplexFloat()) {
7059 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7060 APFloat::rmNearestTiesToEven);
7061 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7062 APFloat::rmNearestTiesToEven);
7063 } else {
7064 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7065 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7066 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007067 break;
John McCalle3027922010-08-25 11:45:40 +00007068 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007069 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007070 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007071 APFloat &LHS_r = LHS.getComplexFloatReal();
7072 APFloat &LHS_i = LHS.getComplexFloatImag();
7073 APFloat &RHS_r = RHS.getComplexFloatReal();
7074 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007075
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007076 APFloat Tmp = LHS_r;
7077 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7078 Result.getComplexFloatReal() = Tmp;
7079 Tmp = LHS_i;
7080 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7081 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7082
7083 Tmp = LHS_r;
7084 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7085 Result.getComplexFloatImag() = Tmp;
7086 Tmp = LHS_i;
7087 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7088 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7089 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007090 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007091 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007092 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7093 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007094 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007095 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7096 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7097 }
7098 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007099 case BO_Div:
7100 if (Result.isComplexFloat()) {
7101 ComplexValue LHS = Result;
7102 APFloat &LHS_r = LHS.getComplexFloatReal();
7103 APFloat &LHS_i = LHS.getComplexFloatImag();
7104 APFloat &RHS_r = RHS.getComplexFloatReal();
7105 APFloat &RHS_i = RHS.getComplexFloatImag();
7106 APFloat &Res_r = Result.getComplexFloatReal();
7107 APFloat &Res_i = Result.getComplexFloatImag();
7108
7109 APFloat Den = RHS_r;
7110 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7111 APFloat Tmp = RHS_i;
7112 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7113 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7114
7115 Res_r = LHS_r;
7116 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7117 Tmp = LHS_i;
7118 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7119 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7120 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7121
7122 Res_i = LHS_i;
7123 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7124 Tmp = LHS_r;
7125 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7126 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7127 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7128 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007129 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7130 return Error(E, diag::note_expr_divide_by_zero);
7131
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007132 ComplexValue LHS = Result;
7133 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7134 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7135 Result.getComplexIntReal() =
7136 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7137 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7138 Result.getComplexIntImag() =
7139 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7140 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7141 }
7142 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007143 }
7144
John McCall93d91dc2010-05-07 17:22:02 +00007145 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007146}
7147
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007148bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7149 // Get the operand value into 'Result'.
7150 if (!Visit(E->getSubExpr()))
7151 return false;
7152
7153 switch (E->getOpcode()) {
7154 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007155 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007156 case UO_Extension:
7157 return true;
7158 case UO_Plus:
7159 // The result is always just the subexpr.
7160 return true;
7161 case UO_Minus:
7162 if (Result.isComplexFloat()) {
7163 Result.getComplexFloatReal().changeSign();
7164 Result.getComplexFloatImag().changeSign();
7165 }
7166 else {
7167 Result.getComplexIntReal() = -Result.getComplexIntReal();
7168 Result.getComplexIntImag() = -Result.getComplexIntImag();
7169 }
7170 return true;
7171 case UO_Not:
7172 if (Result.isComplexFloat())
7173 Result.getComplexFloatImag().changeSign();
7174 else
7175 Result.getComplexIntImag() = -Result.getComplexIntImag();
7176 return true;
7177 }
7178}
7179
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007180bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7181 if (E->getNumInits() == 2) {
7182 if (E->getType()->isComplexType()) {
7183 Result.makeComplexFloat();
7184 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7185 return false;
7186 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7187 return false;
7188 } else {
7189 Result.makeComplexInt();
7190 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7191 return false;
7192 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7193 return false;
7194 }
7195 return true;
7196 }
7197 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7198}
7199
Anders Carlsson537969c2008-11-16 20:27:53 +00007200//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007201// Void expression evaluation, primarily for a cast to void on the LHS of a
7202// comma operator
7203//===----------------------------------------------------------------------===//
7204
7205namespace {
7206class VoidExprEvaluator
7207 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7208public:
7209 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7210
Richard Smith2e312c82012-03-03 22:46:17 +00007211 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007212
7213 bool VisitCastExpr(const CastExpr *E) {
7214 switch (E->getCastKind()) {
7215 default:
7216 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7217 case CK_ToVoid:
7218 VisitIgnoredValue(E->getSubExpr());
7219 return true;
7220 }
7221 }
7222};
7223} // end anonymous namespace
7224
7225static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7226 assert(E->isRValue() && E->getType()->isVoidType());
7227 return VoidExprEvaluator(Info).Visit(E);
7228}
7229
7230//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007231// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007232//===----------------------------------------------------------------------===//
7233
Richard Smith2e312c82012-03-03 22:46:17 +00007234static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007235 // In C, function designators are not lvalues, but we evaluate them as if they
7236 // are.
7237 if (E->isGLValue() || E->getType()->isFunctionType()) {
7238 LValue LV;
7239 if (!EvaluateLValue(E, LV, Info))
7240 return false;
7241 LV.moveInto(Result);
7242 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007243 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007244 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007245 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007246 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007247 return false;
John McCall45d55e42010-05-07 21:00:08 +00007248 } else if (E->getType()->hasPointerRepresentation()) {
7249 LValue LV;
7250 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007251 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007252 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00007253 } else if (E->getType()->isRealFloatingType()) {
7254 llvm::APFloat F(0.0);
7255 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007256 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007257 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00007258 } else if (E->getType()->isAnyComplexType()) {
7259 ComplexValue C;
7260 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007261 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007262 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00007263 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007264 MemberPtr P;
7265 if (!EvaluateMemberPointer(E, P, Info))
7266 return false;
7267 P.moveInto(Result);
7268 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00007269 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007270 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007271 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007272 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007273 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007274 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00007275 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007276 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007277 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007278 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7279 return false;
7280 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00007281 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007282 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007283 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007284 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007285 if (!EvaluateVoid(E, Info))
7286 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007287 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007288 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007289 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007290 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007291 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007292 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007293 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007294
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007295 return true;
7296}
7297
Richard Smithb228a862012-02-15 02:18:13 +00007298/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7299/// cases, the in-place evaluation is essential, since later initializers for
7300/// an object can indirectly refer to subobjects which were initialized earlier.
7301static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007302 const Expr *E, bool AllowNonLiteralTypes) {
7303 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007304 return false;
7305
7306 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007307 // Evaluate arrays and record types in-place, so that later initializers can
7308 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007309 if (E->getType()->isArrayType())
7310 return EvaluateArray(E, This, Result, Info);
7311 else if (E->getType()->isRecordType())
7312 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007313 }
7314
7315 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007316 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007317}
7318
Richard Smithf57d8cb2011-12-09 22:58:01 +00007319/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7320/// lvalue-to-rvalue cast if it is an lvalue.
7321static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007322 if (!CheckLiteralType(Info, E))
7323 return false;
7324
Richard Smith2e312c82012-03-03 22:46:17 +00007325 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007326 return false;
7327
7328 if (E->isGLValue()) {
7329 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007330 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007331 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007332 return false;
7333 }
7334
Richard Smith2e312c82012-03-03 22:46:17 +00007335 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007336 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007337}
Richard Smith11562c52011-10-28 17:51:58 +00007338
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007339static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7340 const ASTContext &Ctx, bool &IsConst) {
7341 // Fast-path evaluations of integer literals, since we sometimes see files
7342 // containing vast quantities of these.
7343 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7344 Result.Val = APValue(APSInt(L->getValue(),
7345 L->getType()->isUnsignedIntegerType()));
7346 IsConst = true;
7347 return true;
7348 }
7349
7350 // FIXME: Evaluating values of large array and record types can cause
7351 // performance problems. Only do so in C++11 for now.
7352 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7353 Exp->getType()->isRecordType()) &&
7354 !Ctx.getLangOpts().CPlusPlus11) {
7355 IsConst = false;
7356 return true;
7357 }
7358 return false;
7359}
7360
7361
Richard Smith7b553f12011-10-29 00:50:52 +00007362/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007363/// any crazy technique (that has nothing to do with language standards) that
7364/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007365/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7366/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007367bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007368 bool IsConst;
7369 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7370 return IsConst;
7371
Richard Smithf57d8cb2011-12-09 22:58:01 +00007372 EvalInfo Info(Ctx, Result);
7373 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007374}
7375
Jay Foad39c79802011-01-12 09:06:06 +00007376bool Expr::EvaluateAsBooleanCondition(bool &Result,
7377 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007378 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007379 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007380 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007381}
7382
Richard Smith5fab0c92011-12-28 19:48:30 +00007383bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7384 SideEffectsKind AllowSideEffects) const {
7385 if (!getType()->isIntegralOrEnumerationType())
7386 return false;
7387
Richard Smith11562c52011-10-28 17:51:58 +00007388 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007389 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7390 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007391 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007392
Richard Smith11562c52011-10-28 17:51:58 +00007393 Result = ExprResult.Val.getInt();
7394 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007395}
7396
Jay Foad39c79802011-01-12 09:06:06 +00007397bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007398 EvalInfo Info(Ctx, Result);
7399
John McCall45d55e42010-05-07 21:00:08 +00007400 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007401 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7402 !CheckLValueConstantExpression(Info, getExprLoc(),
7403 Ctx.getLValueReferenceType(getType()), LV))
7404 return false;
7405
Richard Smith2e312c82012-03-03 22:46:17 +00007406 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007407 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007408}
7409
Richard Smithd0b4dd62011-12-19 06:19:21 +00007410bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7411 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007412 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007413 // FIXME: Evaluating initializers for large array and record types can cause
7414 // performance problems. Only do so in C++11 for now.
7415 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007416 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007417 return false;
7418
Richard Smithd0b4dd62011-12-19 06:19:21 +00007419 Expr::EvalStatus EStatus;
7420 EStatus.Diag = &Notes;
7421
7422 EvalInfo InitInfo(Ctx, EStatus);
7423 InitInfo.setEvaluatingDecl(VD, Value);
7424
7425 LValue LVal;
7426 LVal.set(VD);
7427
Richard Smithfddd3842011-12-30 21:15:51 +00007428 // C++11 [basic.start.init]p2:
7429 // Variables with static storage duration or thread storage duration shall be
7430 // zero-initialized before any other initialization takes place.
7431 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007432 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007433 !VD->getType()->isReferenceType()) {
7434 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007435 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007436 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007437 return false;
7438 }
7439
Richard Smith7525ff62013-05-09 07:14:00 +00007440 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7441 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007442 EStatus.HasSideEffects)
7443 return false;
7444
7445 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7446 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007447}
7448
Richard Smith7b553f12011-10-29 00:50:52 +00007449/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7450/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007451bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007452 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007453 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007454}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007455
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007456APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007457 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007458 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007459 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007460 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007461 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007462 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007463 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007464
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007465 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007466}
John McCall864e3962010-05-07 05:32:02 +00007467
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007468void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7469 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7470 bool IsConst;
7471 EvalResult EvalResult;
7472 EvalResult.Diag = Diags;
7473 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7474 EvalInfo Info(Ctx, EvalResult, true);
7475 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7476 }
7477}
7478
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007479 bool Expr::EvalResult::isGlobalLValue() const {
7480 assert(Val.isLValue());
7481 return IsGlobalLValue(Val.getLValueBase());
7482 }
7483
7484
John McCall864e3962010-05-07 05:32:02 +00007485/// isIntegerConstantExpr - this recursive routine will test if an expression is
7486/// an integer constant expression.
7487
7488/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7489/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007490
7491// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007492// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7493// and a (possibly null) SourceLocation indicating the location of the problem.
7494//
John McCall864e3962010-05-07 05:32:02 +00007495// Note that to reduce code duplication, this helper does no evaluation
7496// itself; the caller checks whether the expression is evaluatable, and
7497// in the rare cases where CheckICE actually cares about the evaluated
7498// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007499
Dan Gohman28ade552010-07-26 21:25:24 +00007500namespace {
7501
Richard Smith9e575da2012-12-28 13:25:52 +00007502enum ICEKind {
7503 /// This expression is an ICE.
7504 IK_ICE,
7505 /// This expression is not an ICE, but if it isn't evaluated, it's
7506 /// a legal subexpression for an ICE. This return value is used to handle
7507 /// the comma operator in C99 mode, and non-constant subexpressions.
7508 IK_ICEIfUnevaluated,
7509 /// This expression is not an ICE, and is not a legal subexpression for one.
7510 IK_NotICE
7511};
7512
John McCall864e3962010-05-07 05:32:02 +00007513struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007514 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007515 SourceLocation Loc;
7516
Richard Smith9e575da2012-12-28 13:25:52 +00007517 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007518};
7519
Dan Gohman28ade552010-07-26 21:25:24 +00007520}
7521
Richard Smith9e575da2012-12-28 13:25:52 +00007522static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7523
7524static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007525
7526static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7527 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007528 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007529 !EVResult.Val.isInt())
7530 return ICEDiag(IK_NotICE, E->getLocStart());
7531
John McCall864e3962010-05-07 05:32:02 +00007532 return NoDiag();
7533}
7534
7535static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7536 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007537 if (!E->getType()->isIntegralOrEnumerationType())
7538 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007539
7540 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007541#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007542#define STMT(Node, Base) case Expr::Node##Class:
7543#define EXPR(Node, Base)
7544#include "clang/AST/StmtNodes.inc"
7545 case Expr::PredefinedExprClass:
7546 case Expr::FloatingLiteralClass:
7547 case Expr::ImaginaryLiteralClass:
7548 case Expr::StringLiteralClass:
7549 case Expr::ArraySubscriptExprClass:
7550 case Expr::MemberExprClass:
7551 case Expr::CompoundAssignOperatorClass:
7552 case Expr::CompoundLiteralExprClass:
7553 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007554 case Expr::DesignatedInitExprClass:
7555 case Expr::ImplicitValueInitExprClass:
7556 case Expr::ParenListExprClass:
7557 case Expr::VAArgExprClass:
7558 case Expr::AddrLabelExprClass:
7559 case Expr::StmtExprClass:
7560 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007561 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007562 case Expr::CXXDynamicCastExprClass:
7563 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007564 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007565 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007566 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007567 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007568 case Expr::CXXThisExprClass:
7569 case Expr::CXXThrowExprClass:
7570 case Expr::CXXNewExprClass:
7571 case Expr::CXXDeleteExprClass:
7572 case Expr::CXXPseudoDestructorExprClass:
7573 case Expr::UnresolvedLookupExprClass:
7574 case Expr::DependentScopeDeclRefExprClass:
7575 case Expr::CXXConstructExprClass:
7576 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007577 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007578 case Expr::CXXTemporaryObjectExprClass:
7579 case Expr::CXXUnresolvedConstructExprClass:
7580 case Expr::CXXDependentScopeMemberExprClass:
7581 case Expr::UnresolvedMemberExprClass:
7582 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007583 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007584 case Expr::ObjCArrayLiteralClass:
7585 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007586 case Expr::ObjCEncodeExprClass:
7587 case Expr::ObjCMessageExprClass:
7588 case Expr::ObjCSelectorExprClass:
7589 case Expr::ObjCProtocolExprClass:
7590 case Expr::ObjCIvarRefExprClass:
7591 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007592 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007593 case Expr::ObjCIsaExprClass:
7594 case Expr::ShuffleVectorExprClass:
7595 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007596 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007597 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007598 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007599 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007600 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007601 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007602 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007603 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007604 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007605 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007606 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007607 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007608 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007609
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007610 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007611 case Expr::GNUNullExprClass:
7612 // GCC considers the GNU __null value to be an integral constant expression.
7613 return NoDiag();
7614
John McCall7c454bb2011-07-15 05:09:51 +00007615 case Expr::SubstNonTypeTemplateParmExprClass:
7616 return
7617 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7618
John McCall864e3962010-05-07 05:32:02 +00007619 case Expr::ParenExprClass:
7620 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007621 case Expr::GenericSelectionExprClass:
7622 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007623 case Expr::IntegerLiteralClass:
7624 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007625 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007626 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007627 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007628 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007629 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007630 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007631 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007632 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007633 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007634 return NoDiag();
7635 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007636 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007637 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7638 // constant expressions, but they can never be ICEs because an ICE cannot
7639 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007640 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007641 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007642 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007643 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007644 }
Richard Smith6365c912012-02-24 22:12:32 +00007645 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007646 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7647 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007648 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007649 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007650 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007651 // Parameter variables are never constants. Without this check,
7652 // getAnyInitializer() can find a default argument, which leads
7653 // to chaos.
7654 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007655 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007656
7657 // C++ 7.1.5.1p2
7658 // A variable of non-volatile const-qualified integral or enumeration
7659 // type initialized by an ICE can be used in ICEs.
7660 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007661 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007662 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007663
Richard Smithd0b4dd62011-12-19 06:19:21 +00007664 const VarDecl *VD;
7665 // Look for a declaration of this variable that has an initializer, and
7666 // check whether it is an ICE.
7667 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7668 return NoDiag();
7669 else
Richard Smith9e575da2012-12-28 13:25:52 +00007670 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007671 }
7672 }
Richard Smith9e575da2012-12-28 13:25:52 +00007673 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007674 }
John McCall864e3962010-05-07 05:32:02 +00007675 case Expr::UnaryOperatorClass: {
7676 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7677 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007678 case UO_PostInc:
7679 case UO_PostDec:
7680 case UO_PreInc:
7681 case UO_PreDec:
7682 case UO_AddrOf:
7683 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007684 // C99 6.6/3 allows increment and decrement within unevaluated
7685 // subexpressions of constant expressions, but they can never be ICEs
7686 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007687 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007688 case UO_Extension:
7689 case UO_LNot:
7690 case UO_Plus:
7691 case UO_Minus:
7692 case UO_Not:
7693 case UO_Real:
7694 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007695 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007696 }
Richard Smith9e575da2012-12-28 13:25:52 +00007697
John McCall864e3962010-05-07 05:32:02 +00007698 // OffsetOf falls through here.
7699 }
7700 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007701 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7702 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7703 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7704 // compliance: we should warn earlier for offsetof expressions with
7705 // array subscripts that aren't ICEs, and if the array subscripts
7706 // are ICEs, the value of the offsetof must be an integer constant.
7707 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007708 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007709 case Expr::UnaryExprOrTypeTraitExprClass: {
7710 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7711 if ((Exp->getKind() == UETT_SizeOf) &&
7712 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007713 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007714 return NoDiag();
7715 }
7716 case Expr::BinaryOperatorClass: {
7717 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7718 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007719 case BO_PtrMemD:
7720 case BO_PtrMemI:
7721 case BO_Assign:
7722 case BO_MulAssign:
7723 case BO_DivAssign:
7724 case BO_RemAssign:
7725 case BO_AddAssign:
7726 case BO_SubAssign:
7727 case BO_ShlAssign:
7728 case BO_ShrAssign:
7729 case BO_AndAssign:
7730 case BO_XorAssign:
7731 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007732 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7733 // constant expressions, but they can never be ICEs because an ICE cannot
7734 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007735 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007736
John McCalle3027922010-08-25 11:45:40 +00007737 case BO_Mul:
7738 case BO_Div:
7739 case BO_Rem:
7740 case BO_Add:
7741 case BO_Sub:
7742 case BO_Shl:
7743 case BO_Shr:
7744 case BO_LT:
7745 case BO_GT:
7746 case BO_LE:
7747 case BO_GE:
7748 case BO_EQ:
7749 case BO_NE:
7750 case BO_And:
7751 case BO_Xor:
7752 case BO_Or:
7753 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007754 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7755 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007756 if (Exp->getOpcode() == BO_Div ||
7757 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007758 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007759 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007760 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007761 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007762 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007763 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007764 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007765 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007766 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007767 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007768 }
7769 }
7770 }
John McCalle3027922010-08-25 11:45:40 +00007771 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007772 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007773 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7774 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007775 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7776 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007777 } else {
7778 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007779 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007780 }
7781 }
Richard Smith9e575da2012-12-28 13:25:52 +00007782 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007783 }
John McCalle3027922010-08-25 11:45:40 +00007784 case BO_LAnd:
7785 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007786 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7787 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007788 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007789 // Rare case where the RHS has a comma "side-effect"; we need
7790 // to actually check the condition to see whether the side
7791 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007792 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007793 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007794 return RHSResult;
7795 return NoDiag();
7796 }
7797
Richard Smith9e575da2012-12-28 13:25:52 +00007798 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007799 }
7800 }
7801 }
7802 case Expr::ImplicitCastExprClass:
7803 case Expr::CStyleCastExprClass:
7804 case Expr::CXXFunctionalCastExprClass:
7805 case Expr::CXXStaticCastExprClass:
7806 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007807 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007808 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007809 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007810 if (isa<ExplicitCastExpr>(E)) {
7811 if (const FloatingLiteral *FL
7812 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7813 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7814 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7815 APSInt IgnoredVal(DestWidth, !DestSigned);
7816 bool Ignored;
7817 // If the value does not fit in the destination type, the behavior is
7818 // undefined, so we are not required to treat it as a constant
7819 // expression.
7820 if (FL->getValue().convertToInteger(IgnoredVal,
7821 llvm::APFloat::rmTowardZero,
7822 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007823 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007824 return NoDiag();
7825 }
7826 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007827 switch (cast<CastExpr>(E)->getCastKind()) {
7828 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007829 case CK_AtomicToNonAtomic:
7830 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007831 case CK_NoOp:
7832 case CK_IntegralToBoolean:
7833 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007834 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007835 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007836 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007837 }
John McCall864e3962010-05-07 05:32:02 +00007838 }
John McCallc07a0c72011-02-17 10:25:35 +00007839 case Expr::BinaryConditionalOperatorClass: {
7840 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7841 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007842 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007843 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007844 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7845 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7846 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007847 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007848 return FalseResult;
7849 }
John McCall864e3962010-05-07 05:32:02 +00007850 case Expr::ConditionalOperatorClass: {
7851 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7852 // If the condition (ignoring parens) is a __builtin_constant_p call,
7853 // then only the true side is actually considered in an integer constant
7854 // expression, and it is fully evaluated. This is an important GNU
7855 // extension. See GCC PR38377 for discussion.
7856 if (const CallExpr *CallCE
7857 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007858 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7859 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007860 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007861 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007862 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007863
Richard Smithf57d8cb2011-12-09 22:58:01 +00007864 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7865 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007866
Richard Smith9e575da2012-12-28 13:25:52 +00007867 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007868 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007869 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007870 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007871 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007872 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007873 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007874 return NoDiag();
7875 // Rare case where the diagnostics depend on which side is evaluated
7876 // Note that if we get here, CondResult is 0, and at least one of
7877 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007878 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007879 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007880 return TrueResult;
7881 }
7882 case Expr::CXXDefaultArgExprClass:
7883 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007884 case Expr::CXXDefaultInitExprClass:
7885 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007886 case Expr::ChooseExprClass: {
7887 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7888 }
7889 }
7890
David Blaikiee4d798f2012-01-20 21:50:17 +00007891 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007892}
7893
Richard Smithf57d8cb2011-12-09 22:58:01 +00007894/// Evaluate an expression as a C++11 integral constant expression.
7895static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7896 const Expr *E,
7897 llvm::APSInt *Value,
7898 SourceLocation *Loc) {
7899 if (!E->getType()->isIntegralOrEnumerationType()) {
7900 if (Loc) *Loc = E->getExprLoc();
7901 return false;
7902 }
7903
Richard Smith66e05fe2012-01-18 05:21:49 +00007904 APValue Result;
7905 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007906 return false;
7907
Richard Smith66e05fe2012-01-18 05:21:49 +00007908 assert(Result.isInt() && "pointer cast to int is not an ICE");
7909 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007910 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007911}
7912
Richard Smith92b1ce02011-12-12 09:28:41 +00007913bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007914 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007915 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7916
Richard Smith9e575da2012-12-28 13:25:52 +00007917 ICEDiag D = CheckICE(this, Ctx);
7918 if (D.Kind != IK_ICE) {
7919 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007920 return false;
7921 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007922 return true;
7923}
7924
7925bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7926 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007927 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007928 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7929
7930 if (!isIntegerConstantExpr(Ctx, Loc))
7931 return false;
7932 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007933 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007934 return true;
7935}
Richard Smith66e05fe2012-01-18 05:21:49 +00007936
Richard Smith98a0a492012-02-14 21:38:30 +00007937bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007938 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007939}
7940
Richard Smith66e05fe2012-01-18 05:21:49 +00007941bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7942 SourceLocation *Loc) const {
7943 // We support this checking in C++98 mode in order to diagnose compatibility
7944 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007945 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007946
Richard Smith98a0a492012-02-14 21:38:30 +00007947 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007948 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007949 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007950 Status.Diag = &Diags;
7951 EvalInfo Info(Ctx, Status);
7952
7953 APValue Scratch;
7954 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7955
7956 if (!Diags.empty()) {
7957 IsConstExpr = false;
7958 if (Loc) *Loc = Diags[0].first;
7959 } else if (!IsConstExpr) {
7960 // FIXME: This shouldn't happen.
7961 if (Loc) *Loc = getExprLoc();
7962 }
7963
7964 return IsConstExpr;
7965}
Richard Smith253c2a32012-01-27 01:14:48 +00007966
7967bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007968 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007969 PartialDiagnosticAt> &Diags) {
7970 // FIXME: It would be useful to check constexpr function templates, but at the
7971 // moment the constant expression evaluator cannot cope with the non-rigorous
7972 // ASTs which we build for dependent expressions.
7973 if (FD->isDependentContext())
7974 return true;
7975
7976 Expr::EvalStatus Status;
7977 Status.Diag = &Diags;
7978
7979 EvalInfo Info(FD->getASTContext(), Status);
7980 Info.CheckingPotentialConstantExpression = true;
7981
7982 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7983 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7984
Richard Smith7525ff62013-05-09 07:14:00 +00007985 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00007986 // is a temporary being used as the 'this' pointer.
7987 LValue This;
7988 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007989 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007990
Richard Smith253c2a32012-01-27 01:14:48 +00007991 ArrayRef<const Expr*> Args;
7992
7993 SourceLocation Loc = FD->getLocation();
7994
Richard Smith2e312c82012-03-03 22:46:17 +00007995 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00007996 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
7997 // Evaluate the call as a constant initializer, to allow the construction
7998 // of objects of non-literal types.
7999 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008000 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008001 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008002 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8003 Args, FD->getBody(), Info, Scratch);
8004
8005 return Diags.empty();
8006}