blob: 2a3efb225bd647c0ed28352da372510c098cb4f0 [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 &&
1083 Info.EvaluatingDecl.getOpaqueValue() ==
1084 This->getLValueBase().getOpaqueValue())
1085 return true;
1086
Richard Smithfddd3842011-12-30 21:15:51 +00001087 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001088 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001089 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001090 << E->getType();
1091 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001092 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001093 return false;
1094}
1095
Richard Smith0b0a0b62011-10-29 20:57:55 +00001096/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001097/// constant expression. If not, report an appropriate diagnostic. Does not
1098/// check that the expression is of literal type.
1099static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1100 QualType Type, const APValue &Value) {
1101 // Core issue 1454: For a literal constant expression of array or class type,
1102 // each subobject of its value shall have been initialized by a constant
1103 // expression.
1104 if (Value.isArray()) {
1105 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1106 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1107 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1108 Value.getArrayInitializedElt(I)))
1109 return false;
1110 }
1111 if (!Value.hasArrayFiller())
1112 return true;
1113 return CheckConstantExpression(Info, DiagLoc, EltTy,
1114 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001115 }
Richard Smithb228a862012-02-15 02:18:13 +00001116 if (Value.isUnion() && Value.getUnionField()) {
1117 return CheckConstantExpression(Info, DiagLoc,
1118 Value.getUnionField()->getType(),
1119 Value.getUnionValue());
1120 }
1121 if (Value.isStruct()) {
1122 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1123 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1124 unsigned BaseIndex = 0;
1125 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1126 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1127 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1128 Value.getStructBase(BaseIndex)))
1129 return false;
1130 }
1131 }
1132 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1133 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001134 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1135 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001136 return false;
1137 }
1138 }
1139
1140 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001141 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001142 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001143 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1144 }
1145
1146 // Everything else is fine.
1147 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001148}
1149
Richard Smith83c68212011-10-31 05:11:32 +00001150const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001151 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001152}
1153
1154static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001155 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001156}
1157
Richard Smithcecf1842011-11-01 21:06:14 +00001158static bool IsWeakLValue(const LValue &Value) {
1159 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001160 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001161}
1162
Richard Smith2e312c82012-03-03 22:46:17 +00001163static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001164 // A null base expression indicates a null pointer. These are always
1165 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001166 if (!Value.getLValueBase()) {
1167 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001168 return true;
1169 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001170
Richard Smith027bf112011-11-17 22:56:20 +00001171 // We have a non-null base. These are generally known to be true, but if it's
1172 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001173 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001174 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001175 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001176}
1177
Richard Smith2e312c82012-03-03 22:46:17 +00001178static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001179 switch (Val.getKind()) {
1180 case APValue::Uninitialized:
1181 return false;
1182 case APValue::Int:
1183 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001184 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001185 case APValue::Float:
1186 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001187 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001188 case APValue::ComplexInt:
1189 Result = Val.getComplexIntReal().getBoolValue() ||
1190 Val.getComplexIntImag().getBoolValue();
1191 return true;
1192 case APValue::ComplexFloat:
1193 Result = !Val.getComplexFloatReal().isZero() ||
1194 !Val.getComplexFloatImag().isZero();
1195 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001196 case APValue::LValue:
1197 return EvalPointerValueAsBool(Val, Result);
1198 case APValue::MemberPointer:
1199 Result = Val.getMemberPointerDecl();
1200 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001201 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001202 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001203 case APValue::Struct:
1204 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001205 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001206 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001207 }
1208
Richard Smith11562c52011-10-28 17:51:58 +00001209 llvm_unreachable("unknown APValue kind");
1210}
1211
1212static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1213 EvalInfo &Info) {
1214 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001215 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001216 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001217 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001218 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001219}
1220
Richard Smith357362d2011-12-13 06:39:58 +00001221template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001222static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001223 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001224 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001225 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001226}
1227
1228static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1229 QualType SrcType, const APFloat &Value,
1230 QualType DestType, APSInt &Result) {
1231 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001232 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001233 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001234
Richard Smith357362d2011-12-13 06:39:58 +00001235 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001236 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001237 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1238 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001239 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001240 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001241}
1242
Richard Smith357362d2011-12-13 06:39:58 +00001243static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1244 QualType SrcType, QualType DestType,
1245 APFloat &Result) {
1246 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001247 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001248 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1249 APFloat::rmNearestTiesToEven, &ignored)
1250 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001251 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001252 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001253}
1254
Richard Smith911e1422012-01-30 22:27:01 +00001255static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1256 QualType DestType, QualType SrcType,
1257 APSInt &Value) {
1258 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001259 APSInt Result = Value;
1260 // Figure out if this is a truncate, extend or noop cast.
1261 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001262 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001263 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001264 return Result;
1265}
1266
Richard Smith357362d2011-12-13 06:39:58 +00001267static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1268 QualType SrcType, const APSInt &Value,
1269 QualType DestType, APFloat &Result) {
1270 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1271 if (Result.convertFromAPInt(Value, Value.isSigned(),
1272 APFloat::rmNearestTiesToEven)
1273 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001274 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001275 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001276}
1277
Eli Friedman803acb32011-12-22 03:51:45 +00001278static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1279 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001280 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001281 if (!Evaluate(SVal, Info, E))
1282 return false;
1283 if (SVal.isInt()) {
1284 Res = SVal.getInt();
1285 return true;
1286 }
1287 if (SVal.isFloat()) {
1288 Res = SVal.getFloat().bitcastToAPInt();
1289 return true;
1290 }
1291 if (SVal.isVector()) {
1292 QualType VecTy = E->getType();
1293 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1294 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1295 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1296 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1297 Res = llvm::APInt::getNullValue(VecSize);
1298 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1299 APValue &Elt = SVal.getVectorElt(i);
1300 llvm::APInt EltAsInt;
1301 if (Elt.isInt()) {
1302 EltAsInt = Elt.getInt();
1303 } else if (Elt.isFloat()) {
1304 EltAsInt = Elt.getFloat().bitcastToAPInt();
1305 } else {
1306 // Don't try to handle vectors of anything other than int or float
1307 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001308 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001309 return false;
1310 }
1311 unsigned BaseEltSize = EltAsInt.getBitWidth();
1312 if (BigEndian)
1313 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1314 else
1315 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1316 }
1317 return true;
1318 }
1319 // Give up if the input isn't an int, float, or vector. For example, we
1320 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001321 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001322 return false;
1323}
1324
Richard Smith43e77732013-05-07 04:50:00 +00001325/// Perform the given integer operation, which is known to need at most BitWidth
1326/// bits, and check for overflow in the original type (if that type was not an
1327/// unsigned type).
1328template<typename Operation>
1329static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1330 const APSInt &LHS, const APSInt &RHS,
1331 unsigned BitWidth, Operation Op) {
1332 if (LHS.isUnsigned())
1333 return Op(LHS, RHS);
1334
1335 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1336 APSInt Result = Value.trunc(LHS.getBitWidth());
1337 if (Result.extend(BitWidth) != Value) {
1338 if (Info.getIntOverflowCheckMode())
1339 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1340 diag::warn_integer_constant_overflow)
1341 << Result.toString(10) << E->getType();
1342 else
1343 HandleOverflow(Info, E, Value, E->getType());
1344 }
1345 return Result;
1346}
1347
1348/// Perform the given binary integer operation.
1349static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1350 BinaryOperatorKind Opcode, APSInt RHS,
1351 APSInt &Result) {
1352 switch (Opcode) {
1353 default:
1354 Info.Diag(E);
1355 return false;
1356 case BO_Mul:
1357 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1358 std::multiplies<APSInt>());
1359 return true;
1360 case BO_Add:
1361 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1362 std::plus<APSInt>());
1363 return true;
1364 case BO_Sub:
1365 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1366 std::minus<APSInt>());
1367 return true;
1368 case BO_And: Result = LHS & RHS; return true;
1369 case BO_Xor: Result = LHS ^ RHS; return true;
1370 case BO_Or: Result = LHS | RHS; return true;
1371 case BO_Div:
1372 case BO_Rem:
1373 if (RHS == 0) {
1374 Info.Diag(E, diag::note_expr_divide_by_zero);
1375 return false;
1376 }
1377 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1378 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1379 LHS.isSigned() && LHS.isMinSignedValue())
1380 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1381 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1382 return true;
1383 case BO_Shl: {
1384 if (Info.getLangOpts().OpenCL)
1385 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1386 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1387 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1388 RHS.isUnsigned());
1389 else if (RHS.isSigned() && RHS.isNegative()) {
1390 // During constant-folding, a negative shift is an opposite shift. Such
1391 // a shift is not a constant expression.
1392 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1393 RHS = -RHS;
1394 goto shift_right;
1395 }
1396 shift_left:
1397 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1398 // the shifted type.
1399 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1400 if (SA != RHS) {
1401 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1402 << RHS << E->getType() << LHS.getBitWidth();
1403 } else if (LHS.isSigned()) {
1404 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1405 // operand, and must not overflow the corresponding unsigned type.
1406 if (LHS.isNegative())
1407 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1408 else if (LHS.countLeadingZeros() < SA)
1409 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1410 }
1411 Result = LHS << SA;
1412 return true;
1413 }
1414 case BO_Shr: {
1415 if (Info.getLangOpts().OpenCL)
1416 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1417 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1418 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1419 RHS.isUnsigned());
1420 else if (RHS.isSigned() && RHS.isNegative()) {
1421 // During constant-folding, a negative shift is an opposite shift. Such a
1422 // shift is not a constant expression.
1423 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1424 RHS = -RHS;
1425 goto shift_left;
1426 }
1427 shift_right:
1428 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1429 // shifted type.
1430 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1431 if (SA != RHS)
1432 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1433 << RHS << E->getType() << LHS.getBitWidth();
1434 Result = LHS >> SA;
1435 return true;
1436 }
1437
1438 case BO_LT: Result = LHS < RHS; return true;
1439 case BO_GT: Result = LHS > RHS; return true;
1440 case BO_LE: Result = LHS <= RHS; return true;
1441 case BO_GE: Result = LHS >= RHS; return true;
1442 case BO_EQ: Result = LHS == RHS; return true;
1443 case BO_NE: Result = LHS != RHS; return true;
1444 }
1445}
1446
Richard Smith861b5b52013-05-07 23:34:45 +00001447/// Perform the given binary floating-point operation, in-place, on LHS.
1448static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1449 APFloat &LHS, BinaryOperatorKind Opcode,
1450 const APFloat &RHS) {
1451 switch (Opcode) {
1452 default:
1453 Info.Diag(E);
1454 return false;
1455 case BO_Mul:
1456 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1457 break;
1458 case BO_Add:
1459 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1460 break;
1461 case BO_Sub:
1462 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1463 break;
1464 case BO_Div:
1465 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1466 break;
1467 }
1468
1469 if (LHS.isInfinity() || LHS.isNaN())
1470 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1471 return true;
1472}
1473
Richard Smitha8105bc2012-01-06 16:39:00 +00001474/// Cast an lvalue referring to a base subobject to a derived class, by
1475/// truncating the lvalue's path to the given length.
1476static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1477 const RecordDecl *TruncatedType,
1478 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001479 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001480
1481 // Check we actually point to a derived class object.
1482 if (TruncatedElements == D.Entries.size())
1483 return true;
1484 assert(TruncatedElements >= D.MostDerivedPathLength &&
1485 "not casting to a derived class");
1486 if (!Result.checkSubobject(Info, E, CSK_Derived))
1487 return false;
1488
1489 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001490 const RecordDecl *RD = TruncatedType;
1491 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001492 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001493 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1494 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001495 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001496 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001497 else
Richard Smithd62306a2011-11-10 06:34:14 +00001498 Result.Offset -= Layout.getBaseClassOffset(Base);
1499 RD = Base;
1500 }
Richard Smith027bf112011-11-17 22:56:20 +00001501 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001502 return true;
1503}
1504
John McCalld7bca762012-05-01 00:38:49 +00001505static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001506 const CXXRecordDecl *Derived,
1507 const CXXRecordDecl *Base,
1508 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001509 if (!RL) {
1510 if (Derived->isInvalidDecl()) return false;
1511 RL = &Info.Ctx.getASTRecordLayout(Derived);
1512 }
1513
Richard Smithd62306a2011-11-10 06:34:14 +00001514 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001515 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001516 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001517}
1518
Richard Smitha8105bc2012-01-06 16:39:00 +00001519static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001520 const CXXRecordDecl *DerivedDecl,
1521 const CXXBaseSpecifier *Base) {
1522 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1523
John McCalld7bca762012-05-01 00:38:49 +00001524 if (!Base->isVirtual())
1525 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001526
Richard Smitha8105bc2012-01-06 16:39:00 +00001527 SubobjectDesignator &D = Obj.Designator;
1528 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001529 return false;
1530
Richard Smitha8105bc2012-01-06 16:39:00 +00001531 // Extract most-derived object and corresponding type.
1532 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1533 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1534 return false;
1535
1536 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001537 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001538 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1539 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001540 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001541 return true;
1542}
1543
1544/// Update LVal to refer to the given field, which must be a member of the type
1545/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001546static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001547 const FieldDecl *FD,
1548 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001549 if (!RL) {
1550 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001551 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001552 }
Richard Smithd62306a2011-11-10 06:34:14 +00001553
1554 unsigned I = FD->getFieldIndex();
1555 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001556 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001557 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001558}
1559
Richard Smith1b78b3d2012-01-25 22:15:11 +00001560/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001561static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001562 LValue &LVal,
1563 const IndirectFieldDecl *IFD) {
1564 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1565 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001566 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1567 return false;
1568 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001569}
1570
Richard Smithd62306a2011-11-10 06:34:14 +00001571/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001572static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1573 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001574 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1575 // extension.
1576 if (Type->isVoidType() || Type->isFunctionType()) {
1577 Size = CharUnits::One();
1578 return true;
1579 }
1580
1581 if (!Type->isConstantSizeType()) {
1582 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001583 // FIXME: Better diagnostic.
1584 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001585 return false;
1586 }
1587
1588 Size = Info.Ctx.getTypeSizeInChars(Type);
1589 return true;
1590}
1591
1592/// Update a pointer value to model pointer arithmetic.
1593/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001594/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001595/// \param LVal - The pointer value to be updated.
1596/// \param EltTy - The pointee type represented by LVal.
1597/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001598static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1599 LValue &LVal, QualType EltTy,
1600 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001601 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001602 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001603 return false;
1604
1605 // Compute the new offset in the appropriate width.
1606 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001607 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001608 return true;
1609}
1610
Richard Smith66c96992012-02-18 22:04:06 +00001611/// Update an lvalue to refer to a component of a complex number.
1612/// \param Info - Information about the ongoing evaluation.
1613/// \param LVal - The lvalue to be updated.
1614/// \param EltTy - The complex number's component type.
1615/// \param Imag - False for the real component, true for the imaginary.
1616static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1617 LValue &LVal, QualType EltTy,
1618 bool Imag) {
1619 if (Imag) {
1620 CharUnits SizeOfComponent;
1621 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1622 return false;
1623 LVal.Offset += SizeOfComponent;
1624 }
1625 LVal.addComplex(Info, E, EltTy, Imag);
1626 return true;
1627}
1628
Richard Smith27908702011-10-24 17:54:18 +00001629/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001630///
1631/// \param Info Information about the ongoing evaluation.
1632/// \param E An expression to be used when printing diagnostics.
1633/// \param VD The variable whose initializer should be obtained.
1634/// \param Frame The frame in which the variable was created. Must be null
1635/// if this variable is not local to the evaluation.
1636/// \param Result Filled in with a pointer to the value of the variable.
1637static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1638 const VarDecl *VD, CallStackFrame *Frame,
1639 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001640 // If this is a parameter to an active constexpr function call, perform
1641 // argument substitution.
1642 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001643 // Assume arguments of a potential constant expression are unknown
1644 // constant expressions.
1645 if (Info.CheckingPotentialConstantExpression)
1646 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001647 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001648 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001649 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001650 }
Richard Smith3229b742013-05-05 21:17:10 +00001651 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001652 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001653 }
Richard Smith27908702011-10-24 17:54:18 +00001654
Richard Smithd9f663b2013-04-22 15:31:51 +00001655 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001656 if (Frame) {
1657 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001658 // If we've carried on past an unevaluatable local variable initializer,
1659 // we can't go any further. This can happen during potential constant
1660 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001661 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001662 }
1663
Richard Smithd0b4dd62011-12-19 06:19:21 +00001664 // Dig out the initializer, and use the declaration which it's attached to.
1665 const Expr *Init = VD->getAnyInitializer(VD);
1666 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001667 // If we're checking a potential constant expression, the variable could be
1668 // initialized later.
1669 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001670 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001671 return false;
1672 }
1673
Richard Smithd62306a2011-11-10 06:34:14 +00001674 // If we're currently evaluating the initializer of this declaration, use that
1675 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001676 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001677 Result = Info.EvaluatingDeclValue;
1678 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001679 }
1680
Richard Smithcecf1842011-11-01 21:06:14 +00001681 // Never evaluate the initializer of a weak variable. We can't be sure that
1682 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001683 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001684 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001685 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001686 }
Richard Smithcecf1842011-11-01 21:06:14 +00001687
Richard Smithd0b4dd62011-12-19 06:19:21 +00001688 // Check that we can fold the initializer. In C++, we will have already done
1689 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001690 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001691 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001692 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001693 Notes.size() + 1) << VD;
1694 Info.Note(VD->getLocation(), diag::note_declared_at);
1695 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001696 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001697 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001698 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001699 Notes.size() + 1) << VD;
1700 Info.Note(VD->getLocation(), diag::note_declared_at);
1701 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001702 }
Richard Smith27908702011-10-24 17:54:18 +00001703
Richard Smith3229b742013-05-05 21:17:10 +00001704 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001705 return true;
Richard Smith27908702011-10-24 17:54:18 +00001706}
1707
Richard Smith11562c52011-10-28 17:51:58 +00001708static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001709 Qualifiers Quals = T.getQualifiers();
1710 return Quals.hasConst() && !Quals.hasVolatile();
1711}
1712
Richard Smithe97cbd72011-11-11 04:05:33 +00001713/// Get the base index of the given base class within an APValue representing
1714/// the given derived class.
1715static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1716 const CXXRecordDecl *Base) {
1717 Base = Base->getCanonicalDecl();
1718 unsigned Index = 0;
1719 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1720 E = Derived->bases_end(); I != E; ++I, ++Index) {
1721 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1722 return Index;
1723 }
1724
1725 llvm_unreachable("base class missing from derived class's bases list");
1726}
1727
Richard Smith3da88fa2013-04-26 14:36:30 +00001728/// Extract the value of a character from a string literal.
1729static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1730 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001731 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001732 const StringLiteral *S = cast<StringLiteral>(Lit);
1733 const ConstantArrayType *CAT =
1734 Info.Ctx.getAsConstantArrayType(S->getType());
1735 assert(CAT && "string literal isn't an array");
1736 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001737 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001738
1739 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001740 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001741 if (Index < S->getLength())
1742 Value = S->getCodeUnit(Index);
1743 return Value;
1744}
1745
Richard Smith3da88fa2013-04-26 14:36:30 +00001746// Expand a string literal into an array of characters.
1747static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1748 APValue &Result) {
1749 const StringLiteral *S = cast<StringLiteral>(Lit);
1750 const ConstantArrayType *CAT =
1751 Info.Ctx.getAsConstantArrayType(S->getType());
1752 assert(CAT && "string literal isn't an array");
1753 QualType CharType = CAT->getElementType();
1754 assert(CharType->isIntegerType() && "unexpected character type");
1755
1756 unsigned Elts = CAT->getSize().getZExtValue();
1757 Result = APValue(APValue::UninitArray(),
1758 std::min(S->getLength(), Elts), Elts);
1759 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1760 CharType->isUnsignedIntegerType());
1761 if (Result.hasArrayFiller())
1762 Result.getArrayFiller() = APValue(Value);
1763 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1764 Value = S->getCodeUnit(I);
1765 Result.getArrayInitializedElt(I) = APValue(Value);
1766 }
1767}
1768
1769// Expand an array so that it has more than Index filled elements.
1770static void expandArray(APValue &Array, unsigned Index) {
1771 unsigned Size = Array.getArraySize();
1772 assert(Index < Size);
1773
1774 // Always at least double the number of elements for which we store a value.
1775 unsigned OldElts = Array.getArrayInitializedElts();
1776 unsigned NewElts = std::max(Index+1, OldElts * 2);
1777 NewElts = std::min(Size, std::max(NewElts, 8u));
1778
1779 // Copy the data across.
1780 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1781 for (unsigned I = 0; I != OldElts; ++I)
1782 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1783 for (unsigned I = OldElts; I != NewElts; ++I)
1784 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1785 if (NewValue.hasArrayFiller())
1786 NewValue.getArrayFiller() = Array.getArrayFiller();
1787 Array.swap(NewValue);
1788}
1789
Richard Smith861b5b52013-05-07 23:34:45 +00001790/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001791enum AccessKinds {
1792 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001793 AK_Assign,
1794 AK_Increment,
1795 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001796};
1797
Richard Smith3229b742013-05-05 21:17:10 +00001798/// A handle to a complete object (an object that is not a subobject of
1799/// another object).
1800struct CompleteObject {
1801 /// The value of the complete object.
1802 APValue *Value;
1803 /// The type of the complete object.
1804 QualType Type;
1805
1806 CompleteObject() : Value(0) {}
1807 CompleteObject(APValue *Value, QualType Type)
1808 : Value(Value), Type(Type) {
1809 assert(Value && "missing value for complete object");
1810 }
1811
1812 operator bool() const { return Value; }
1813};
1814
Richard Smith3da88fa2013-04-26 14:36:30 +00001815/// Find the designated sub-object of an rvalue.
1816template<typename SubobjectHandler>
1817typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001818findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001819 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001820 if (Sub.Invalid)
1821 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001822 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001823 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001824 if (Info.getLangOpts().CPlusPlus11)
1825 Info.Diag(E, diag::note_constexpr_access_past_end)
1826 << handler.AccessKind;
1827 else
1828 Info.Diag(E);
1829 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001830 }
Richard Smith6804be52011-11-11 08:28:03 +00001831 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001832 return handler.found(*Obj.Value, Obj.Type);
1833 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001834 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001835 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001836
Richard Smith3229b742013-05-05 21:17:10 +00001837 APValue *O = Obj.Value;
1838 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001839 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001840 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001841 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001842 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001843 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001844 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001845 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001846 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001847 // Note, it should not be possible to form a pointer with a valid
1848 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001849 if (Info.getLangOpts().CPlusPlus11)
1850 Info.Diag(E, diag::note_constexpr_access_past_end)
1851 << handler.AccessKind;
1852 else
1853 Info.Diag(E);
1854 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001855 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001856
1857 ObjType = CAT->getElementType();
1858
Richard Smith14a94132012-02-17 03:35:37 +00001859 // An array object is represented as either an Array APValue or as an
1860 // LValue which refers to a string literal.
1861 if (O->isLValue()) {
1862 assert(I == N - 1 && "extracting subobject of character?");
1863 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001864 if (handler.AccessKind != AK_Read)
1865 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1866 *O);
1867 else
1868 return handler.foundString(*O, ObjType, Index);
1869 }
1870
1871 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001872 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001873 else if (handler.AccessKind != AK_Read) {
1874 expandArray(*O, Index);
1875 O = &O->getArrayInitializedElt(Index);
1876 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001877 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001878 } else if (ObjType->isAnyComplexType()) {
1879 // Next subobject is a complex number.
1880 uint64_t Index = Sub.Entries[I].ArrayIndex;
1881 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001882 if (Info.getLangOpts().CPlusPlus11)
1883 Info.Diag(E, diag::note_constexpr_access_past_end)
1884 << handler.AccessKind;
1885 else
1886 Info.Diag(E);
1887 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001888 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001889
1890 bool WasConstQualified = ObjType.isConstQualified();
1891 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1892 if (WasConstQualified)
1893 ObjType.addConst();
1894
Richard Smith66c96992012-02-18 22:04:06 +00001895 assert(I == N - 1 && "extracting subobject of scalar?");
1896 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001897 return handler.found(Index ? O->getComplexIntImag()
1898 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001899 } else {
1900 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001901 return handler.found(Index ? O->getComplexFloatImag()
1902 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001903 }
Richard Smithd62306a2011-11-10 06:34:14 +00001904 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001905 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001906 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001907 << Field;
1908 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001909 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001910 }
1911
Richard Smithd62306a2011-11-10 06:34:14 +00001912 // Next subobject is a class, struct or union field.
1913 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1914 if (RD->isUnion()) {
1915 const FieldDecl *UnionField = O->getUnionField();
1916 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001917 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001918 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1919 << handler.AccessKind << Field << !UnionField << UnionField;
1920 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001921 }
Richard Smithd62306a2011-11-10 06:34:14 +00001922 O = &O->getUnionValue();
1923 } else
1924 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001925
1926 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001927 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001928 if (WasConstQualified && !Field->isMutable())
1929 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001930
1931 if (ObjType.isVolatileQualified()) {
1932 if (Info.getLangOpts().CPlusPlus) {
1933 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001934 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1935 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001936 Info.Note(Field->getLocation(), diag::note_declared_at);
1937 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001938 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001939 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001940 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001941 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001942 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001943 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001944 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1945 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1946 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001947
1948 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001949 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001950 if (WasConstQualified)
1951 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001952 }
Richard Smithd62306a2011-11-10 06:34:14 +00001953
Richard Smithf57d8cb2011-12-09 22:58:01 +00001954 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001955 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001956 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1957 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001958 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001959 }
1960
Richard Smith3da88fa2013-04-26 14:36:30 +00001961 return handler.found(*O, ObjType);
1962}
1963
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001964namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001965struct ExtractSubobjectHandler {
1966 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001967 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001968
1969 static const AccessKinds AccessKind = AK_Read;
1970
1971 typedef bool result_type;
1972 bool failed() { return false; }
1973 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001974 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001975 return true;
1976 }
1977 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001978 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001979 return true;
1980 }
1981 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001982 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001983 return true;
1984 }
1985 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001986 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001987 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1988 return true;
1989 }
1990};
Richard Smith3229b742013-05-05 21:17:10 +00001991} // end anonymous namespace
1992
Richard Smith3da88fa2013-04-26 14:36:30 +00001993const AccessKinds ExtractSubobjectHandler::AccessKind;
1994
1995/// Extract the designated sub-object of an rvalue.
1996static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001997 const CompleteObject &Obj,
1998 const SubobjectDesignator &Sub,
1999 APValue &Result) {
2000 ExtractSubobjectHandler Handler = { Info, Result };
2001 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002002}
2003
Richard Smith3229b742013-05-05 21:17:10 +00002004namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002005struct ModifySubobjectHandler {
2006 EvalInfo &Info;
2007 APValue &NewVal;
2008 const Expr *E;
2009
2010 typedef bool result_type;
2011 static const AccessKinds AccessKind = AK_Assign;
2012
2013 bool checkConst(QualType QT) {
2014 // Assigning to a const object has undefined behavior.
2015 if (QT.isConstQualified()) {
2016 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2017 return false;
2018 }
2019 return true;
2020 }
2021
2022 bool failed() { return false; }
2023 bool found(APValue &Subobj, QualType SubobjType) {
2024 if (!checkConst(SubobjType))
2025 return false;
2026 // We've been given ownership of NewVal, so just swap it in.
2027 Subobj.swap(NewVal);
2028 return true;
2029 }
2030 bool found(APSInt &Value, QualType SubobjType) {
2031 if (!checkConst(SubobjType))
2032 return false;
2033 if (!NewVal.isInt()) {
2034 // Maybe trying to write a cast pointer value into a complex?
2035 Info.Diag(E);
2036 return false;
2037 }
2038 Value = NewVal.getInt();
2039 return true;
2040 }
2041 bool found(APFloat &Value, QualType SubobjType) {
2042 if (!checkConst(SubobjType))
2043 return false;
2044 Value = NewVal.getFloat();
2045 return true;
2046 }
2047 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2048 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2049 }
2050};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002051} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002052
Richard Smith3229b742013-05-05 21:17:10 +00002053const AccessKinds ModifySubobjectHandler::AccessKind;
2054
Richard Smith3da88fa2013-04-26 14:36:30 +00002055/// Update the designated sub-object of an rvalue to the given value.
2056static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002057 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002058 const SubobjectDesignator &Sub,
2059 APValue &NewVal) {
2060 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002061 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002062}
2063
Richard Smith84f6dcf2012-02-02 01:16:57 +00002064/// Find the position where two subobject designators diverge, or equivalently
2065/// the length of the common initial subsequence.
2066static unsigned FindDesignatorMismatch(QualType ObjType,
2067 const SubobjectDesignator &A,
2068 const SubobjectDesignator &B,
2069 bool &WasArrayIndex) {
2070 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2071 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002072 if (!ObjType.isNull() &&
2073 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002074 // Next subobject is an array element.
2075 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2076 WasArrayIndex = true;
2077 return I;
2078 }
Richard Smith66c96992012-02-18 22:04:06 +00002079 if (ObjType->isAnyComplexType())
2080 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2081 else
2082 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002083 } else {
2084 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2085 WasArrayIndex = false;
2086 return I;
2087 }
2088 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2089 // Next subobject is a field.
2090 ObjType = FD->getType();
2091 else
2092 // Next subobject is a base class.
2093 ObjType = QualType();
2094 }
2095 }
2096 WasArrayIndex = false;
2097 return I;
2098}
2099
2100/// Determine whether the given subobject designators refer to elements of the
2101/// same array object.
2102static bool AreElementsOfSameArray(QualType ObjType,
2103 const SubobjectDesignator &A,
2104 const SubobjectDesignator &B) {
2105 if (A.Entries.size() != B.Entries.size())
2106 return false;
2107
2108 bool IsArray = A.MostDerivedArraySize != 0;
2109 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2110 // A is a subobject of the array element.
2111 return false;
2112
2113 // If A (and B) designates an array element, the last entry will be the array
2114 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2115 // of length 1' case, and the entire path must match.
2116 bool WasArrayIndex;
2117 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2118 return CommonLength >= A.Entries.size() - IsArray;
2119}
2120
Richard Smith3229b742013-05-05 21:17:10 +00002121/// Find the complete object to which an LValue refers.
2122CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2123 const LValue &LVal, QualType LValType) {
2124 if (!LVal.Base) {
2125 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2126 return CompleteObject();
2127 }
2128
2129 CallStackFrame *Frame = 0;
2130 if (LVal.CallIndex) {
2131 Frame = Info.getCallFrame(LVal.CallIndex);
2132 if (!Frame) {
2133 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2134 << AK << LVal.Base.is<const ValueDecl*>();
2135 NoteLValueLocation(Info, LVal.Base);
2136 return CompleteObject();
2137 }
Richard Smith3229b742013-05-05 21:17:10 +00002138 }
2139
2140 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2141 // is not a constant expression (even if the object is non-volatile). We also
2142 // apply this rule to C++98, in order to conform to the expected 'volatile'
2143 // semantics.
2144 if (LValType.isVolatileQualified()) {
2145 if (Info.getLangOpts().CPlusPlus)
2146 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2147 << AK << LValType;
2148 else
2149 Info.Diag(E);
2150 return CompleteObject();
2151 }
2152
2153 // Compute value storage location and type of base object.
2154 APValue *BaseVal = 0;
2155 QualType BaseType;
2156
2157 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2158 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2159 // In C++11, constexpr, non-volatile variables initialized with constant
2160 // expressions are constant expressions too. Inside constexpr functions,
2161 // parameters are constant expressions even if they're non-const.
2162 // In C++1y, objects local to a constant expression (those with a Frame) are
2163 // both readable and writable inside constant expressions.
2164 // In C, such things can also be folded, although they are not ICEs.
2165 const VarDecl *VD = dyn_cast<VarDecl>(D);
2166 if (VD) {
2167 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2168 VD = VDef;
2169 }
2170 if (!VD || VD->isInvalidDecl()) {
2171 Info.Diag(E);
2172 return CompleteObject();
2173 }
2174
2175 // Accesses of volatile-qualified objects are not allowed.
2176 BaseType = VD->getType();
2177 if (BaseType.isVolatileQualified()) {
2178 if (Info.getLangOpts().CPlusPlus) {
2179 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2180 << AK << 1 << VD;
2181 Info.Note(VD->getLocation(), diag::note_declared_at);
2182 } else {
2183 Info.Diag(E);
2184 }
2185 return CompleteObject();
2186 }
2187
2188 // Unless we're looking at a local variable or argument in a constexpr call,
2189 // the variable we're reading must be const.
2190 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002191 if (Info.getLangOpts().CPlusPlus1y &&
2192 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2193 // OK, we can read and modify an object if we're in the process of
2194 // evaluating its initializer, because its lifetime began in this
2195 // evaluation.
2196 } else if (AK != AK_Read) {
2197 // All the remaining cases only permit reading.
2198 Info.Diag(E, diag::note_constexpr_modify_global);
2199 return CompleteObject();
2200 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002201 // OK, we can read this variable.
2202 } else if (BaseType->isIntegralOrEnumerationType()) {
2203 if (!BaseType.isConstQualified()) {
2204 if (Info.getLangOpts().CPlusPlus) {
2205 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2206 Info.Note(VD->getLocation(), diag::note_declared_at);
2207 } else {
2208 Info.Diag(E);
2209 }
2210 return CompleteObject();
2211 }
2212 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2213 // We support folding of const floating-point types, in order to make
2214 // static const data members of such types (supported as an extension)
2215 // more useful.
2216 if (Info.getLangOpts().CPlusPlus11) {
2217 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2218 Info.Note(VD->getLocation(), diag::note_declared_at);
2219 } else {
2220 Info.CCEDiag(E);
2221 }
2222 } else {
2223 // FIXME: Allow folding of values of any literal type in all languages.
2224 if (Info.getLangOpts().CPlusPlus11) {
2225 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2226 Info.Note(VD->getLocation(), diag::note_declared_at);
2227 } else {
2228 Info.Diag(E);
2229 }
2230 return CompleteObject();
2231 }
2232 }
2233
2234 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2235 return CompleteObject();
2236 } else {
2237 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2238
2239 if (!Frame) {
2240 Info.Diag(E);
2241 return CompleteObject();
2242 }
2243
2244 BaseType = Base->getType();
2245 BaseVal = &Frame->Temporaries[Base];
2246
2247 // Volatile temporary objects cannot be accessed in constant expressions.
2248 if (BaseType.isVolatileQualified()) {
2249 if (Info.getLangOpts().CPlusPlus) {
2250 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2251 << AK << 0;
2252 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2253 } else {
2254 Info.Diag(E);
2255 }
2256 return CompleteObject();
2257 }
2258 }
2259
Richard Smith7525ff62013-05-09 07:14:00 +00002260 // During the construction of an object, it is not yet 'const'.
2261 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2262 // and this doesn't do quite the right thing for const subobjects of the
2263 // object under construction.
2264 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2265 BaseType = Info.Ctx.getCanonicalType(BaseType);
2266 BaseType.removeLocalConst();
2267 }
2268
Richard Smith3229b742013-05-05 21:17:10 +00002269 // In C++1y, we can't safely access any mutable state when checking a
2270 // potential constant expression.
2271 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2272 Info.CheckingPotentialConstantExpression)
2273 return CompleteObject();
2274
2275 return CompleteObject(BaseVal, BaseType);
2276}
2277
Richard Smith243ef902013-05-05 23:31:59 +00002278/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2279/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2280/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002281///
2282/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002283/// \param Conv - The expression for which we are performing the conversion.
2284/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002285/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2286/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002287/// \param LVal - The glvalue on which we are attempting to perform this action.
2288/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002289static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002290 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002291 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002292 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002293 return false;
2294
Richard Smith3229b742013-05-05 21:17:10 +00002295 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002296 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002297 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2298 !Type.isVolatileQualified()) {
2299 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2300 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2301 // initializer until now for such expressions. Such an expression can't be
2302 // an ICE in C, so this only matters for fold.
2303 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2304 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002305 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002306 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002307 }
Richard Smith3229b742013-05-05 21:17:10 +00002308 APValue Lit;
2309 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2310 return false;
2311 CompleteObject LitObj(&Lit, Base->getType());
2312 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2313 } else if (isa<StringLiteral>(Base)) {
2314 // We represent a string literal array as an lvalue pointing at the
2315 // corresponding expression, rather than building an array of chars.
2316 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2317 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2318 CompleteObject StrObj(&Str, Base->getType());
2319 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002320 }
Richard Smith11562c52011-10-28 17:51:58 +00002321 }
2322
Richard Smith3229b742013-05-05 21:17:10 +00002323 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2324 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002325}
2326
2327/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002328static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002329 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002330 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002331 return false;
2332
Richard Smith3229b742013-05-05 21:17:10 +00002333 if (!Info.getLangOpts().CPlusPlus1y) {
2334 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002335 return false;
2336 }
2337
Richard Smith3229b742013-05-05 21:17:10 +00002338 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2339 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002340}
2341
Richard Smith243ef902013-05-05 23:31:59 +00002342static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2343 return T->isSignedIntegerType() &&
2344 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2345}
2346
2347namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002348struct CompoundAssignSubobjectHandler {
2349 EvalInfo &Info;
2350 const Expr *E;
2351 QualType PromotedLHSType;
2352 BinaryOperatorKind Opcode;
2353 const APValue &RHS;
2354
2355 static const AccessKinds AccessKind = AK_Assign;
2356
2357 typedef bool result_type;
2358
2359 bool checkConst(QualType QT) {
2360 // Assigning to a const object has undefined behavior.
2361 if (QT.isConstQualified()) {
2362 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2363 return false;
2364 }
2365 return true;
2366 }
2367
2368 bool failed() { return false; }
2369 bool found(APValue &Subobj, QualType SubobjType) {
2370 switch (Subobj.getKind()) {
2371 case APValue::Int:
2372 return found(Subobj.getInt(), SubobjType);
2373 case APValue::Float:
2374 return found(Subobj.getFloat(), SubobjType);
2375 case APValue::ComplexInt:
2376 case APValue::ComplexFloat:
2377 // FIXME: Implement complex compound assignment.
2378 Info.Diag(E);
2379 return false;
2380 case APValue::LValue:
2381 return foundPointer(Subobj, SubobjType);
2382 default:
2383 // FIXME: can this happen?
2384 Info.Diag(E);
2385 return false;
2386 }
2387 }
2388 bool found(APSInt &Value, QualType SubobjType) {
2389 if (!checkConst(SubobjType))
2390 return false;
2391
2392 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2393 // We don't support compound assignment on integer-cast-to-pointer
2394 // values.
2395 Info.Diag(E);
2396 return false;
2397 }
2398
2399 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2400 SubobjType, Value);
2401 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2402 return false;
2403 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2404 return true;
2405 }
2406 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002407 return checkConst(SubobjType) &&
2408 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2409 Value) &&
2410 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2411 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002412 }
2413 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2414 if (!checkConst(SubobjType))
2415 return false;
2416
2417 QualType PointeeType;
2418 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2419 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002420
2421 if (PointeeType.isNull() || !RHS.isInt() ||
2422 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002423 Info.Diag(E);
2424 return false;
2425 }
2426
Richard Smith861b5b52013-05-07 23:34:45 +00002427 int64_t Offset = getExtValue(RHS.getInt());
2428 if (Opcode == BO_Sub)
2429 Offset = -Offset;
2430
2431 LValue LVal;
2432 LVal.setFrom(Info.Ctx, Subobj);
2433 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2434 return false;
2435 LVal.moveInto(Subobj);
2436 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002437 }
2438 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2439 llvm_unreachable("shouldn't encounter string elements here");
2440 }
2441};
2442} // end anonymous namespace
2443
2444const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2445
2446/// Perform a compound assignment of LVal <op>= RVal.
2447static bool handleCompoundAssignment(
2448 EvalInfo &Info, const Expr *E,
2449 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2450 BinaryOperatorKind Opcode, const APValue &RVal) {
2451 if (LVal.Designator.Invalid)
2452 return false;
2453
2454 if (!Info.getLangOpts().CPlusPlus1y) {
2455 Info.Diag(E);
2456 return false;
2457 }
2458
2459 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2460 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2461 RVal };
2462 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2463}
2464
2465namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002466struct IncDecSubobjectHandler {
2467 EvalInfo &Info;
2468 const Expr *E;
2469 AccessKinds AccessKind;
2470 APValue *Old;
2471
2472 typedef bool result_type;
2473
2474 bool checkConst(QualType QT) {
2475 // Assigning to a const object has undefined behavior.
2476 if (QT.isConstQualified()) {
2477 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2478 return false;
2479 }
2480 return true;
2481 }
2482
2483 bool failed() { return false; }
2484 bool found(APValue &Subobj, QualType SubobjType) {
2485 // Stash the old value. Also clear Old, so we don't clobber it later
2486 // if we're post-incrementing a complex.
2487 if (Old) {
2488 *Old = Subobj;
2489 Old = 0;
2490 }
2491
2492 switch (Subobj.getKind()) {
2493 case APValue::Int:
2494 return found(Subobj.getInt(), SubobjType);
2495 case APValue::Float:
2496 return found(Subobj.getFloat(), SubobjType);
2497 case APValue::ComplexInt:
2498 return found(Subobj.getComplexIntReal(),
2499 SubobjType->castAs<ComplexType>()->getElementType()
2500 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2501 case APValue::ComplexFloat:
2502 return found(Subobj.getComplexFloatReal(),
2503 SubobjType->castAs<ComplexType>()->getElementType()
2504 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2505 case APValue::LValue:
2506 return foundPointer(Subobj, SubobjType);
2507 default:
2508 // FIXME: can this happen?
2509 Info.Diag(E);
2510 return false;
2511 }
2512 }
2513 bool found(APSInt &Value, QualType SubobjType) {
2514 if (!checkConst(SubobjType))
2515 return false;
2516
2517 if (!SubobjType->isIntegerType()) {
2518 // We don't support increment / decrement on integer-cast-to-pointer
2519 // values.
2520 Info.Diag(E);
2521 return false;
2522 }
2523
2524 if (Old) *Old = APValue(Value);
2525
2526 // bool arithmetic promotes to int, and the conversion back to bool
2527 // doesn't reduce mod 2^n, so special-case it.
2528 if (SubobjType->isBooleanType()) {
2529 if (AccessKind == AK_Increment)
2530 Value = 1;
2531 else
2532 Value = !Value;
2533 return true;
2534 }
2535
2536 bool WasNegative = Value.isNegative();
2537 if (AccessKind == AK_Increment) {
2538 ++Value;
2539
2540 if (!WasNegative && Value.isNegative() &&
2541 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2542 APSInt ActualValue(Value, /*IsUnsigned*/true);
2543 HandleOverflow(Info, E, ActualValue, SubobjType);
2544 }
2545 } else {
2546 --Value;
2547
2548 if (WasNegative && !Value.isNegative() &&
2549 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2550 unsigned BitWidth = Value.getBitWidth();
2551 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2552 ActualValue.setBit(BitWidth);
2553 HandleOverflow(Info, E, ActualValue, SubobjType);
2554 }
2555 }
2556 return true;
2557 }
2558 bool found(APFloat &Value, QualType SubobjType) {
2559 if (!checkConst(SubobjType))
2560 return false;
2561
2562 if (Old) *Old = APValue(Value);
2563
2564 APFloat One(Value.getSemantics(), 1);
2565 if (AccessKind == AK_Increment)
2566 Value.add(One, APFloat::rmNearestTiesToEven);
2567 else
2568 Value.subtract(One, APFloat::rmNearestTiesToEven);
2569 return true;
2570 }
2571 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2572 if (!checkConst(SubobjType))
2573 return false;
2574
2575 QualType PointeeType;
2576 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2577 PointeeType = PT->getPointeeType();
2578 else {
2579 Info.Diag(E);
2580 return false;
2581 }
2582
2583 LValue LVal;
2584 LVal.setFrom(Info.Ctx, Subobj);
2585 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2586 AccessKind == AK_Increment ? 1 : -1))
2587 return false;
2588 LVal.moveInto(Subobj);
2589 return true;
2590 }
2591 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2592 llvm_unreachable("shouldn't encounter string elements here");
2593 }
2594};
2595} // end anonymous namespace
2596
2597/// Perform an increment or decrement on LVal.
2598static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2599 QualType LValType, bool IsIncrement, APValue *Old) {
2600 if (LVal.Designator.Invalid)
2601 return false;
2602
2603 if (!Info.getLangOpts().CPlusPlus1y) {
2604 Info.Diag(E);
2605 return false;
2606 }
2607
2608 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2609 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2610 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2611 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2612}
2613
Richard Smithe97cbd72011-11-11 04:05:33 +00002614/// Build an lvalue for the object argument of a member function call.
2615static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2616 LValue &This) {
2617 if (Object->getType()->isPointerType())
2618 return EvaluatePointer(Object, This, Info);
2619
2620 if (Object->isGLValue())
2621 return EvaluateLValue(Object, This, Info);
2622
Richard Smithd9f663b2013-04-22 15:31:51 +00002623 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002624 return EvaluateTemporary(Object, This, Info);
2625
2626 return false;
2627}
2628
2629/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2630/// lvalue referring to the result.
2631///
2632/// \param Info - Information about the ongoing evaluation.
2633/// \param BO - The member pointer access operation.
2634/// \param LV - Filled in with a reference to the resulting object.
2635/// \param IncludeMember - Specifies whether the member itself is included in
2636/// the resulting LValue subobject designator. This is not possible when
2637/// creating a bound member function.
2638/// \return The field or method declaration to which the member pointer refers,
2639/// or 0 if evaluation fails.
2640static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2641 const BinaryOperator *BO,
2642 LValue &LV,
2643 bool IncludeMember = true) {
2644 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2645
Richard Smith253c2a32012-01-27 01:14:48 +00002646 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2647 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002648 return 0;
2649
2650 MemberPtr MemPtr;
2651 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2652 return 0;
2653
2654 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2655 // member value, the behavior is undefined.
2656 if (!MemPtr.getDecl())
2657 return 0;
2658
Richard Smith253c2a32012-01-27 01:14:48 +00002659 if (!EvalObjOK)
2660 return 0;
2661
Richard Smith027bf112011-11-17 22:56:20 +00002662 if (MemPtr.isDerivedMember()) {
2663 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002664 // The end of the derived-to-base path for the base object must match the
2665 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002666 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002667 LV.Designator.Entries.size())
2668 return 0;
2669 unsigned PathLengthToMember =
2670 LV.Designator.Entries.size() - MemPtr.Path.size();
2671 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2672 const CXXRecordDecl *LVDecl = getAsBaseClass(
2673 LV.Designator.Entries[PathLengthToMember + I]);
2674 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2675 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2676 return 0;
2677 }
2678
2679 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002680 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2681 PathLengthToMember))
2682 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002683 } else if (!MemPtr.Path.empty()) {
2684 // Extend the LValue path with the member pointer's path.
2685 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2686 MemPtr.Path.size() + IncludeMember);
2687
2688 // Walk down to the appropriate base class.
2689 QualType LVType = BO->getLHS()->getType();
2690 if (const PointerType *PT = LVType->getAs<PointerType>())
2691 LVType = PT->getPointeeType();
2692 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2693 assert(RD && "member pointer access on non-class-type expression");
2694 // The first class in the path is that of the lvalue.
2695 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2696 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002697 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2698 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002699 RD = Base;
2700 }
2701 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002702 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2703 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002704 }
2705
2706 // Add the member. Note that we cannot build bound member functions here.
2707 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002708 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2709 if (!HandleLValueMember(Info, BO, LV, FD))
2710 return 0;
2711 } else if (const IndirectFieldDecl *IFD =
2712 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2713 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2714 return 0;
2715 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002716 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002717 }
Richard Smith027bf112011-11-17 22:56:20 +00002718 }
2719
2720 return MemPtr.getDecl();
2721}
2722
2723/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2724/// the provided lvalue, which currently refers to the base object.
2725static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2726 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002727 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002728 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002729 return false;
2730
Richard Smitha8105bc2012-01-06 16:39:00 +00002731 QualType TargetQT = E->getType();
2732 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2733 TargetQT = PT->getPointeeType();
2734
2735 // Check this cast lands within the final derived-to-base subobject path.
2736 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002737 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002738 << D.MostDerivedType << TargetQT;
2739 return false;
2740 }
2741
Richard Smith027bf112011-11-17 22:56:20 +00002742 // Check the type of the final cast. We don't need to check the path,
2743 // since a cast can only be formed if the path is unique.
2744 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002745 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2746 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002747 if (NewEntriesSize == D.MostDerivedPathLength)
2748 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2749 else
Richard Smith027bf112011-11-17 22:56:20 +00002750 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002751 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002752 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002753 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002754 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002755 }
Richard Smith027bf112011-11-17 22:56:20 +00002756
2757 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002758 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002759}
2760
Mike Stump876387b2009-10-27 22:09:17 +00002761namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002762enum EvalStmtResult {
2763 /// Evaluation failed.
2764 ESR_Failed,
2765 /// Hit a 'return' statement.
2766 ESR_Returned,
2767 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002768 ESR_Succeeded,
2769 /// Hit a 'continue' statement.
2770 ESR_Continue,
2771 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00002772 ESR_Break,
2773 /// Still scanning for 'case' or 'default' statement.
2774 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00002775};
2776}
2777
Richard Smithd9f663b2013-04-22 15:31:51 +00002778static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2779 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2780 // We don't need to evaluate the initializer for a static local.
2781 if (!VD->hasLocalStorage())
2782 return true;
2783
2784 LValue Result;
2785 Result.set(VD, Info.CurrentCall->Index);
2786 APValue &Val = Info.CurrentCall->Temporaries[VD];
2787
2788 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2789 // Wipe out any partially-computed value, to allow tracking that this
2790 // evaluation failed.
2791 Val = APValue();
2792 return false;
2793 }
2794 }
2795
2796 return true;
2797}
2798
Richard Smith4e18ca52013-05-06 05:56:11 +00002799/// Evaluate a condition (either a variable declaration or an expression).
2800static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2801 const Expr *Cond, bool &Result) {
2802 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2803 return false;
2804 return EvaluateAsBooleanCondition(Cond, Result, Info);
2805}
2806
2807static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002808 const Stmt *S, const SwitchCase *SC = 0);
Richard Smith4e18ca52013-05-06 05:56:11 +00002809
2810/// Evaluate the body of a loop, and translate the result as appropriate.
2811static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002812 const Stmt *Body,
2813 const SwitchCase *Case = 0) {
2814 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00002815 case ESR_Break:
2816 return ESR_Succeeded;
2817 case ESR_Succeeded:
2818 case ESR_Continue:
2819 return ESR_Continue;
2820 case ESR_Failed:
2821 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00002822 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00002823 return ESR;
2824 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002825 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002826}
2827
Richard Smith496ddcf2013-05-12 17:32:42 +00002828/// Evaluate a switch statement.
2829static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
2830 const SwitchStmt *SS) {
2831 // Evaluate the switch condition.
2832 if (SS->getConditionVariable() &&
2833 !EvaluateDecl(Info, SS->getConditionVariable()))
2834 return ESR_Failed;
2835 APSInt Value;
2836 if (!EvaluateInteger(SS->getCond(), Value, Info))
2837 return ESR_Failed;
2838
2839 // Find the switch case corresponding to the value of the condition.
2840 // FIXME: Cache this lookup.
2841 const SwitchCase *Found = 0;
2842 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
2843 SC = SC->getNextSwitchCase()) {
2844 if (isa<DefaultStmt>(SC)) {
2845 Found = SC;
2846 continue;
2847 }
2848
2849 const CaseStmt *CS = cast<CaseStmt>(SC);
2850 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
2851 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
2852 : LHS;
2853 if (LHS <= Value && Value <= RHS) {
2854 Found = SC;
2855 break;
2856 }
2857 }
2858
2859 if (!Found)
2860 return ESR_Succeeded;
2861
2862 // Search the switch body for the switch case and evaluate it from there.
2863 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
2864 case ESR_Break:
2865 return ESR_Succeeded;
2866 case ESR_Succeeded:
2867 case ESR_Continue:
2868 case ESR_Failed:
2869 case ESR_Returned:
2870 return ESR;
2871 case ESR_CaseNotFound:
Richard Smith496ddcf2013-05-12 17:32:42 +00002872 llvm_unreachable("couldn't find switch case");
2873 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00002874 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00002875}
2876
Richard Smith254a73d2011-10-28 22:34:42 +00002877// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002878static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00002879 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00002880 if (!Info.nextStep(S))
2881 return ESR_Failed;
2882
Richard Smith496ddcf2013-05-12 17:32:42 +00002883 // If we're hunting down a 'case' or 'default' label, recurse through
2884 // substatements until we hit the label.
2885 if (Case) {
2886 // FIXME: We don't start the lifetime of objects whose initialization we
2887 // jump over. However, such objects must be of class type with a trivial
2888 // default constructor that initialize all subobjects, so must be empty,
2889 // so this almost never matters.
2890 switch (S->getStmtClass()) {
2891 case Stmt::CompoundStmtClass:
2892 // FIXME: Precompute which substatement of a compound statement we
2893 // would jump to, and go straight there rather than performing a
2894 // linear scan each time.
2895 case Stmt::LabelStmtClass:
2896 case Stmt::AttributedStmtClass:
2897 case Stmt::DoStmtClass:
2898 break;
2899
2900 case Stmt::CaseStmtClass:
2901 case Stmt::DefaultStmtClass:
2902 if (Case == S)
2903 Case = 0;
2904 break;
2905
2906 case Stmt::IfStmtClass: {
2907 // FIXME: Precompute which side of an 'if' we would jump to, and go
2908 // straight there rather than scanning both sides.
2909 const IfStmt *IS = cast<IfStmt>(S);
2910 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
2911 if (ESR != ESR_CaseNotFound || !IS->getElse())
2912 return ESR;
2913 return EvaluateStmt(Result, Info, IS->getElse(), Case);
2914 }
2915
2916 case Stmt::WhileStmtClass: {
2917 EvalStmtResult ESR =
2918 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
2919 if (ESR != ESR_Continue)
2920 return ESR;
2921 break;
2922 }
2923
2924 case Stmt::ForStmtClass: {
2925 const ForStmt *FS = cast<ForStmt>(S);
2926 EvalStmtResult ESR =
2927 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
2928 if (ESR != ESR_Continue)
2929 return ESR;
2930 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2931 return ESR_Failed;
2932 break;
2933 }
2934
2935 case Stmt::DeclStmtClass:
2936 // FIXME: If the variable has initialization that can't be jumped over,
2937 // bail out of any immediately-surrounding compound-statement too.
2938 default:
2939 return ESR_CaseNotFound;
2940 }
2941 }
2942
Richard Smithd9f663b2013-04-22 15:31:51 +00002943 // FIXME: Mark all temporaries in the current frame as destroyed at
2944 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002945 switch (S->getStmtClass()) {
2946 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002947 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002948 // Don't bother evaluating beyond an expression-statement which couldn't
2949 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00002950 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00002951 return ESR_Failed;
2952 return ESR_Succeeded;
2953 }
2954
2955 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002956 return ESR_Failed;
2957
2958 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002959 return ESR_Succeeded;
2960
Richard Smithd9f663b2013-04-22 15:31:51 +00002961 case Stmt::DeclStmtClass: {
2962 const DeclStmt *DS = cast<DeclStmt>(S);
2963 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2964 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2965 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2966 return ESR_Failed;
2967 return ESR_Succeeded;
2968 }
2969
Richard Smith357362d2011-12-13 06:39:58 +00002970 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002971 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002972 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002973 return ESR_Failed;
2974 return ESR_Returned;
2975 }
Richard Smith254a73d2011-10-28 22:34:42 +00002976
2977 case Stmt::CompoundStmtClass: {
2978 const CompoundStmt *CS = cast<CompoundStmt>(S);
2979 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2980 BE = CS->body_end(); BI != BE; ++BI) {
Richard Smith496ddcf2013-05-12 17:32:42 +00002981 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
2982 if (ESR == ESR_Succeeded)
2983 Case = 0;
2984 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00002985 return ESR;
2986 }
Richard Smith496ddcf2013-05-12 17:32:42 +00002987 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00002988 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002989
2990 case Stmt::IfStmtClass: {
2991 const IfStmt *IS = cast<IfStmt>(S);
2992
2993 // Evaluate the condition, as either a var decl or as an expression.
2994 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00002995 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00002996 return ESR_Failed;
2997
2998 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2999 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3000 if (ESR != ESR_Succeeded)
3001 return ESR;
3002 }
3003 return ESR_Succeeded;
3004 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003005
3006 case Stmt::WhileStmtClass: {
3007 const WhileStmt *WS = cast<WhileStmt>(S);
3008 while (true) {
3009 bool Continue;
3010 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3011 Continue))
3012 return ESR_Failed;
3013 if (!Continue)
3014 break;
3015
3016 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3017 if (ESR != ESR_Continue)
3018 return ESR;
3019 }
3020 return ESR_Succeeded;
3021 }
3022
3023 case Stmt::DoStmtClass: {
3024 const DoStmt *DS = cast<DoStmt>(S);
3025 bool Continue;
3026 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003027 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003028 if (ESR != ESR_Continue)
3029 return ESR;
Richard Smith496ddcf2013-05-12 17:32:42 +00003030 Case = 0;
Richard Smith4e18ca52013-05-06 05:56:11 +00003031
3032 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3033 return ESR_Failed;
3034 } while (Continue);
3035 return ESR_Succeeded;
3036 }
3037
3038 case Stmt::ForStmtClass: {
3039 const ForStmt *FS = cast<ForStmt>(S);
3040 if (FS->getInit()) {
3041 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3042 if (ESR != ESR_Succeeded)
3043 return ESR;
3044 }
3045 while (true) {
3046 bool Continue = true;
3047 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3048 FS->getCond(), Continue))
3049 return ESR_Failed;
3050 if (!Continue)
3051 break;
3052
3053 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3054 if (ESR != ESR_Continue)
3055 return ESR;
3056
3057 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
3058 return ESR_Failed;
3059 }
3060 return ESR_Succeeded;
3061 }
3062
Richard Smith896e0d72013-05-06 06:51:17 +00003063 case Stmt::CXXForRangeStmtClass: {
3064 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3065
3066 // Initialize the __range variable.
3067 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3068 if (ESR != ESR_Succeeded)
3069 return ESR;
3070
3071 // Create the __begin and __end iterators.
3072 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3073 if (ESR != ESR_Succeeded)
3074 return ESR;
3075
3076 while (true) {
3077 // Condition: __begin != __end.
3078 bool Continue = true;
3079 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3080 return ESR_Failed;
3081 if (!Continue)
3082 break;
3083
3084 // User's variable declaration, initialized by *__begin.
3085 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3086 if (ESR != ESR_Succeeded)
3087 return ESR;
3088
3089 // Loop body.
3090 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3091 if (ESR != ESR_Continue)
3092 return ESR;
3093
3094 // Increment: ++__begin
3095 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3096 return ESR_Failed;
3097 }
3098
3099 return ESR_Succeeded;
3100 }
3101
Richard Smith496ddcf2013-05-12 17:32:42 +00003102 case Stmt::SwitchStmtClass:
3103 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3104
Richard Smith4e18ca52013-05-06 05:56:11 +00003105 case Stmt::ContinueStmtClass:
3106 return ESR_Continue;
3107
3108 case Stmt::BreakStmtClass:
3109 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003110
3111 case Stmt::LabelStmtClass:
3112 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3113
3114 case Stmt::AttributedStmtClass:
3115 // As a general principle, C++11 attributes can be ignored without
3116 // any semantic impact.
3117 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3118 Case);
3119
3120 case Stmt::CaseStmtClass:
3121 case Stmt::DefaultStmtClass:
3122 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003123 }
3124}
3125
Richard Smithcc36f692011-12-22 02:22:31 +00003126/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3127/// default constructor. If so, we'll fold it whether or not it's marked as
3128/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3129/// so we need special handling.
3130static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003131 const CXXConstructorDecl *CD,
3132 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003133 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3134 return false;
3135
Richard Smith66e05fe2012-01-18 05:21:49 +00003136 // Value-initialization does not call a trivial default constructor, so such a
3137 // call is a core constant expression whether or not the constructor is
3138 // constexpr.
3139 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003140 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003141 // FIXME: If DiagDecl is an implicitly-declared special member function,
3142 // we should be much more explicit about why it's not constexpr.
3143 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3144 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3145 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003146 } else {
3147 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3148 }
3149 }
3150 return true;
3151}
3152
Richard Smith357362d2011-12-13 06:39:58 +00003153/// CheckConstexprFunction - Check that a function can be called in a constant
3154/// expression.
3155static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3156 const FunctionDecl *Declaration,
3157 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003158 // Potential constant expressions can contain calls to declared, but not yet
3159 // defined, constexpr functions.
3160 if (Info.CheckingPotentialConstantExpression && !Definition &&
3161 Declaration->isConstexpr())
3162 return false;
3163
Richard Smith0838f3a2013-05-14 05:18:44 +00003164 // Bail out with no diagnostic if the function declaration itself is invalid.
3165 // We will have produced a relevant diagnostic while parsing it.
3166 if (Declaration->isInvalidDecl())
3167 return false;
3168
Richard Smith357362d2011-12-13 06:39:58 +00003169 // Can we evaluate this function call?
3170 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3171 return true;
3172
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003173 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003174 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003175 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3176 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003177 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3178 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3179 << DiagDecl;
3180 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3181 } else {
3182 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3183 }
3184 return false;
3185}
3186
Richard Smithd62306a2011-11-10 06:34:14 +00003187namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003188typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003189}
3190
3191/// EvaluateArgs - Evaluate the arguments to a function call.
3192static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3193 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003194 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003195 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003196 I != E; ++I) {
3197 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3198 // If we're checking for a potential constant expression, evaluate all
3199 // initializers even if some of them fail.
3200 if (!Info.keepEvaluatingAfterFailure())
3201 return false;
3202 Success = false;
3203 }
3204 }
3205 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003206}
3207
Richard Smith254a73d2011-10-28 22:34:42 +00003208/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003209static bool HandleFunctionCall(SourceLocation CallLoc,
3210 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003211 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003212 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003213 ArgVector ArgValues(Args.size());
3214 if (!EvaluateArgs(Args, ArgValues, Info))
3215 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003216
Richard Smith253c2a32012-01-27 01:14:48 +00003217 if (!Info.CheckCallLimit(CallLoc))
3218 return false;
3219
3220 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003221
3222 // For a trivial copy or move assignment, perform an APValue copy. This is
3223 // essential for unions, where the operations performed by the assignment
3224 // operator cannot be represented as statements.
3225 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3226 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3227 assert(This &&
3228 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3229 LValue RHS;
3230 RHS.setFrom(Info.Ctx, ArgValues[0]);
3231 APValue RHSValue;
3232 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3233 RHS, RHSValue))
3234 return false;
3235 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3236 RHSValue))
3237 return false;
3238 This->moveInto(Result);
3239 return true;
3240 }
3241
Richard Smithd9f663b2013-04-22 15:31:51 +00003242 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003243 if (ESR == ESR_Succeeded) {
3244 if (Callee->getResultType()->isVoidType())
3245 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003246 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003247 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003248 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003249}
3250
Richard Smithd62306a2011-11-10 06:34:14 +00003251/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003252static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003253 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003254 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003255 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003256 ArgVector ArgValues(Args.size());
3257 if (!EvaluateArgs(Args, ArgValues, Info))
3258 return false;
3259
Richard Smith253c2a32012-01-27 01:14:48 +00003260 if (!Info.CheckCallLimit(CallLoc))
3261 return false;
3262
Richard Smith3607ffe2012-02-13 03:54:03 +00003263 const CXXRecordDecl *RD = Definition->getParent();
3264 if (RD->getNumVBases()) {
3265 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3266 return false;
3267 }
3268
Richard Smith253c2a32012-01-27 01:14:48 +00003269 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003270
3271 // If it's a delegating constructor, just delegate.
3272 if (Definition->isDelegatingConstructor()) {
3273 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003274 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3275 return false;
3276 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003277 }
3278
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003279 // For a trivial copy or move constructor, perform an APValue copy. This is
3280 // essential for unions, where the operations performed by the constructor
3281 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003282 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003283 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3284 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003285 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003286 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003287 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003288 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003289 }
3290
3291 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003292 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003293 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3294 std::distance(RD->field_begin(), RD->field_end()));
3295
John McCalld7bca762012-05-01 00:38:49 +00003296 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003297 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3298
Richard Smith253c2a32012-01-27 01:14:48 +00003299 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003300 unsigned BasesSeen = 0;
3301#ifndef NDEBUG
3302 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3303#endif
3304 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3305 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003306 LValue Subobject = This;
3307 APValue *Value = &Result;
3308
3309 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003310 if ((*I)->isBaseInitializer()) {
3311 QualType BaseType((*I)->getBaseClass(), 0);
3312#ifndef NDEBUG
3313 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003314 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003315 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3316 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3317 "base class initializers not in expected order");
3318 ++BaseIt;
3319#endif
John McCalld7bca762012-05-01 00:38:49 +00003320 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3321 BaseType->getAsCXXRecordDecl(), &Layout))
3322 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003323 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003324 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003325 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3326 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003327 if (RD->isUnion()) {
3328 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003329 Value = &Result.getUnionValue();
3330 } else {
3331 Value = &Result.getStructField(FD->getFieldIndex());
3332 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003333 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003334 // Walk the indirect field decl's chain to find the object to initialize,
3335 // and make sure we've initialized every step along it.
3336 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3337 CE = IFD->chain_end();
3338 C != CE; ++C) {
3339 FieldDecl *FD = cast<FieldDecl>(*C);
3340 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3341 // Switch the union field if it differs. This happens if we had
3342 // preceding zero-initialization, and we're now initializing a union
3343 // subobject other than the first.
3344 // FIXME: In this case, the values of the other subobjects are
3345 // specified, since zero-initialization sets all padding bits to zero.
3346 if (Value->isUninit() ||
3347 (Value->isUnion() && Value->getUnionField() != FD)) {
3348 if (CD->isUnion())
3349 *Value = APValue(FD);
3350 else
3351 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3352 std::distance(CD->field_begin(), CD->field_end()));
3353 }
John McCalld7bca762012-05-01 00:38:49 +00003354 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3355 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003356 if (CD->isUnion())
3357 Value = &Value->getUnionValue();
3358 else
3359 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003360 }
Richard Smithd62306a2011-11-10 06:34:14 +00003361 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003362 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003363 }
Richard Smith253c2a32012-01-27 01:14:48 +00003364
Richard Smith7525ff62013-05-09 07:14:00 +00003365 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003366 // If we're checking for a potential constant expression, evaluate all
3367 // initializers even if some of them fail.
3368 if (!Info.keepEvaluatingAfterFailure())
3369 return false;
3370 Success = false;
3371 }
Richard Smithd62306a2011-11-10 06:34:14 +00003372 }
3373
Richard Smithd9f663b2013-04-22 15:31:51 +00003374 return Success &&
3375 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003376}
3377
Eli Friedman9a156e52008-11-12 09:44:48 +00003378//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003379// Generic Evaluation
3380//===----------------------------------------------------------------------===//
3381namespace {
3382
Richard Smithf57d8cb2011-12-09 22:58:01 +00003383// FIXME: RetTy is always bool. Remove it.
3384template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003385class ExprEvaluatorBase
3386 : public ConstStmtVisitor<Derived, RetTy> {
3387private:
Richard Smith2e312c82012-03-03 22:46:17 +00003388 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003389 return static_cast<Derived*>(this)->Success(V, E);
3390 }
Richard Smithfddd3842011-12-30 21:15:51 +00003391 RetTy DerivedZeroInitialization(const Expr *E) {
3392 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003393 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003394
Richard Smith17100ba2012-02-16 02:46:34 +00003395 // Check whether a conditional operator with a non-constant condition is a
3396 // potential constant expression. If neither arm is a potential constant
3397 // expression, then the conditional operator is not either.
3398 template<typename ConditionalOperator>
3399 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3400 assert(Info.CheckingPotentialConstantExpression);
3401
3402 // Speculatively evaluate both arms.
3403 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003404 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003405 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3406
3407 StmtVisitorTy::Visit(E->getFalseExpr());
3408 if (Diag.empty())
3409 return;
3410
3411 Diag.clear();
3412 StmtVisitorTy::Visit(E->getTrueExpr());
3413 if (Diag.empty())
3414 return;
3415 }
3416
3417 Error(E, diag::note_constexpr_conditional_never_const);
3418 }
3419
3420
3421 template<typename ConditionalOperator>
3422 bool HandleConditionalOperator(const ConditionalOperator *E) {
3423 bool BoolResult;
3424 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3425 if (Info.CheckingPotentialConstantExpression)
3426 CheckPotentialConstantConditional(E);
3427 return false;
3428 }
3429
3430 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3431 return StmtVisitorTy::Visit(EvalExpr);
3432 }
3433
Peter Collingbournee9200682011-05-13 03:29:01 +00003434protected:
3435 EvalInfo &Info;
3436 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3437 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3438
Richard Smith92b1ce02011-12-12 09:28:41 +00003439 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003440 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003441 }
3442
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003443 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3444
3445public:
3446 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3447
3448 EvalInfo &getEvalInfo() { return Info; }
3449
Richard Smithf57d8cb2011-12-09 22:58:01 +00003450 /// Report an evaluation error. This should only be called when an error is
3451 /// first discovered. When propagating an error, just return false.
3452 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003453 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003454 return false;
3455 }
3456 bool Error(const Expr *E) {
3457 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3458 }
3459
Peter Collingbournee9200682011-05-13 03:29:01 +00003460 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003461 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003462 }
3463 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003464 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003465 }
3466
3467 RetTy VisitParenExpr(const ParenExpr *E)
3468 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3469 RetTy VisitUnaryExtension(const UnaryOperator *E)
3470 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3471 RetTy VisitUnaryPlus(const UnaryOperator *E)
3472 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3473 RetTy VisitChooseExpr(const ChooseExpr *E)
3474 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3475 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3476 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003477 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3478 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003479 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3480 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003481 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3482 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003483 // We cannot create any objects for which cleanups are required, so there is
3484 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3485 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3486 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003487
Richard Smith6d6ecc32011-12-12 12:46:16 +00003488 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3489 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3490 return static_cast<Derived*>(this)->VisitCastExpr(E);
3491 }
3492 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3493 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3494 return static_cast<Derived*>(this)->VisitCastExpr(E);
3495 }
3496
Richard Smith027bf112011-11-17 22:56:20 +00003497 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3498 switch (E->getOpcode()) {
3499 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003500 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003501
3502 case BO_Comma:
3503 VisitIgnoredValue(E->getLHS());
3504 return StmtVisitorTy::Visit(E->getRHS());
3505
3506 case BO_PtrMemD:
3507 case BO_PtrMemI: {
3508 LValue Obj;
3509 if (!HandleMemberPointerAccess(Info, E, Obj))
3510 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003511 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003512 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003513 return false;
3514 return DerivedSuccess(Result, E);
3515 }
3516 }
3517 }
3518
Peter Collingbournee9200682011-05-13 03:29:01 +00003519 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003520 // Evaluate and cache the common expression. We treat it as a temporary,
3521 // even though it's not quite the same thing.
3522 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3523 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003524 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003525
Richard Smith17100ba2012-02-16 02:46:34 +00003526 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003527 }
3528
3529 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003530 bool IsBcpCall = false;
3531 // If the condition (ignoring parens) is a __builtin_constant_p call,
3532 // the result is a constant expression if it can be folded without
3533 // side-effects. This is an important GNU extension. See GCC PR38377
3534 // for discussion.
3535 if (const CallExpr *CallCE =
3536 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3537 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3538 IsBcpCall = true;
3539
3540 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3541 // constant expression; we can't check whether it's potentially foldable.
3542 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3543 return false;
3544
3545 FoldConstant Fold(Info);
3546
Richard Smith17100ba2012-02-16 02:46:34 +00003547 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003548 return false;
3549
3550 if (IsBcpCall)
3551 Fold.Fold(Info);
3552
3553 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003554 }
3555
3556 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003557 APValue &Value = Info.CurrentCall->Temporaries[E];
3558 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003559 const Expr *Source = E->getSourceExpr();
3560 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003561 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003562 if (Source == E) { // sanity checking.
3563 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003564 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003565 }
3566 return StmtVisitorTy::Visit(Source);
3567 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003568 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003569 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003570
Richard Smith254a73d2011-10-28 22:34:42 +00003571 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003572 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003573 QualType CalleeType = Callee->getType();
3574
Richard Smith254a73d2011-10-28 22:34:42 +00003575 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003576 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003577 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003578 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003579
Richard Smithe97cbd72011-11-11 04:05:33 +00003580 // Extract function decl and 'this' pointer from the callee.
3581 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003582 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003583 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3584 // Explicit bound member calls, such as x.f() or p->g();
3585 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003586 return false;
3587 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003588 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003589 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003590 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3591 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003592 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3593 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003594 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003595 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003596 return Error(Callee);
3597
3598 FD = dyn_cast<FunctionDecl>(Member);
3599 if (!FD)
3600 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003601 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003602 LValue Call;
3603 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003604 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003605
Richard Smitha8105bc2012-01-06 16:39:00 +00003606 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003607 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003608 FD = dyn_cast_or_null<FunctionDecl>(
3609 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003610 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003611 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003612
3613 // Overloaded operator calls to member functions are represented as normal
3614 // calls with '*this' as the first argument.
3615 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3616 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003617 // FIXME: When selecting an implicit conversion for an overloaded
3618 // operator delete, we sometimes try to evaluate calls to conversion
3619 // operators without a 'this' parameter!
3620 if (Args.empty())
3621 return Error(E);
3622
Richard Smithe97cbd72011-11-11 04:05:33 +00003623 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3624 return false;
3625 This = &ThisVal;
3626 Args = Args.slice(1);
3627 }
3628
3629 // Don't call function pointers which have been cast to some other type.
3630 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003631 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003632 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003633 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003634
Richard Smith47b34932012-02-01 02:39:43 +00003635 if (This && !This->checkSubobject(Info, E, CSK_This))
3636 return false;
3637
Richard Smith3607ffe2012-02-13 03:54:03 +00003638 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3639 // calls to such functions in constant expressions.
3640 if (This && !HasQualifier &&
3641 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3642 return Error(E, diag::note_constexpr_virtual_call);
3643
Richard Smith357362d2011-12-13 06:39:58 +00003644 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003645 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003646 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003647
Richard Smith357362d2011-12-13 06:39:58 +00003648 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003649 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3650 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003651 return false;
3652
Richard Smithb228a862012-02-15 02:18:13 +00003653 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003654 }
3655
Richard Smith11562c52011-10-28 17:51:58 +00003656 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3657 return StmtVisitorTy::Visit(E->getInitializer());
3658 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003659 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003660 if (E->getNumInits() == 0)
3661 return DerivedZeroInitialization(E);
3662 if (E->getNumInits() == 1)
3663 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003664 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003665 }
3666 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003667 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003668 }
3669 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003670 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003671 }
Richard Smith027bf112011-11-17 22:56:20 +00003672 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003673 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003674 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003675
Richard Smithd62306a2011-11-10 06:34:14 +00003676 /// A member expression where the object is a prvalue is itself a prvalue.
3677 RetTy VisitMemberExpr(const MemberExpr *E) {
3678 assert(!E->isArrow() && "missing call to bound member function?");
3679
Richard Smith2e312c82012-03-03 22:46:17 +00003680 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003681 if (!Evaluate(Val, Info, E->getBase()))
3682 return false;
3683
3684 QualType BaseTy = E->getBase()->getType();
3685
3686 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003687 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003688 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003689 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003690 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3691
Richard Smith3229b742013-05-05 21:17:10 +00003692 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003693 SubobjectDesignator Designator(BaseTy);
3694 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003695
Richard Smith3229b742013-05-05 21:17:10 +00003696 APValue Result;
3697 return extractSubobject(Info, E, Obj, Designator, Result) &&
3698 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003699 }
3700
Richard Smith11562c52011-10-28 17:51:58 +00003701 RetTy VisitCastExpr(const CastExpr *E) {
3702 switch (E->getCastKind()) {
3703 default:
3704 break;
3705
David Chisnallfa35df62012-01-16 17:27:18 +00003706 case CK_AtomicToNonAtomic:
3707 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003708 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003709 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003710 return StmtVisitorTy::Visit(E->getSubExpr());
3711
3712 case CK_LValueToRValue: {
3713 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003714 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3715 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003716 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003717 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003718 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003719 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003720 return false;
3721 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003722 }
3723 }
3724
Richard Smithf57d8cb2011-12-09 22:58:01 +00003725 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003726 }
3727
Richard Smith243ef902013-05-05 23:31:59 +00003728 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3729 return VisitUnaryPostIncDec(UO);
3730 }
3731 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3732 return VisitUnaryPostIncDec(UO);
3733 }
3734 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3735 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3736 return Error(UO);
3737
3738 LValue LVal;
3739 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3740 return false;
3741 APValue RVal;
3742 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3743 UO->isIncrementOp(), &RVal))
3744 return false;
3745 return DerivedSuccess(RVal, UO);
3746 }
3747
Richard Smith4a678122011-10-24 18:44:57 +00003748 /// Visit a value which is evaluated, but whose value is ignored.
3749 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003750 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003751 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003752};
3753
3754}
3755
3756//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003757// Common base class for lvalue and temporary evaluation.
3758//===----------------------------------------------------------------------===//
3759namespace {
3760template<class Derived>
3761class LValueExprEvaluatorBase
3762 : public ExprEvaluatorBase<Derived, bool> {
3763protected:
3764 LValue &Result;
3765 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3766 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3767
3768 bool Success(APValue::LValueBase B) {
3769 Result.set(B);
3770 return true;
3771 }
3772
3773public:
3774 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3775 ExprEvaluatorBaseTy(Info), Result(Result) {}
3776
Richard Smith2e312c82012-03-03 22:46:17 +00003777 bool Success(const APValue &V, const Expr *E) {
3778 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003779 return true;
3780 }
Richard Smith027bf112011-11-17 22:56:20 +00003781
Richard Smith027bf112011-11-17 22:56:20 +00003782 bool VisitMemberExpr(const MemberExpr *E) {
3783 // Handle non-static data members.
3784 QualType BaseTy;
3785 if (E->isArrow()) {
3786 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3787 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003788 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003789 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003790 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003791 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3792 return false;
3793 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003794 } else {
3795 if (!this->Visit(E->getBase()))
3796 return false;
3797 BaseTy = E->getBase()->getType();
3798 }
Richard Smith027bf112011-11-17 22:56:20 +00003799
Richard Smith1b78b3d2012-01-25 22:15:11 +00003800 const ValueDecl *MD = E->getMemberDecl();
3801 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3802 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3803 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3804 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003805 if (!HandleLValueMember(this->Info, E, Result, FD))
3806 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003807 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003808 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3809 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003810 } else
3811 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003812
Richard Smith1b78b3d2012-01-25 22:15:11 +00003813 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003814 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003815 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003816 RefValue))
3817 return false;
3818 return Success(RefValue, E);
3819 }
3820 return true;
3821 }
3822
3823 bool VisitBinaryOperator(const BinaryOperator *E) {
3824 switch (E->getOpcode()) {
3825 default:
3826 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3827
3828 case BO_PtrMemD:
3829 case BO_PtrMemI:
3830 return HandleMemberPointerAccess(this->Info, E, Result);
3831 }
3832 }
3833
3834 bool VisitCastExpr(const CastExpr *E) {
3835 switch (E->getCastKind()) {
3836 default:
3837 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3838
3839 case CK_DerivedToBase:
3840 case CK_UncheckedDerivedToBase: {
3841 if (!this->Visit(E->getSubExpr()))
3842 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003843
3844 // Now figure out the necessary offset to add to the base LV to get from
3845 // the derived class to the base class.
3846 QualType Type = E->getSubExpr()->getType();
3847
3848 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3849 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003850 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003851 *PathI))
3852 return false;
3853 Type = (*PathI)->getType();
3854 }
3855
3856 return true;
3857 }
3858 }
3859 }
3860};
3861}
3862
3863//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003864// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003865//
3866// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3867// function designators (in C), decl references to void objects (in C), and
3868// temporaries (if building with -Wno-address-of-temporary).
3869//
3870// LValue evaluation produces values comprising a base expression of one of the
3871// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003872// - Declarations
3873// * VarDecl
3874// * FunctionDecl
3875// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003876// * CompoundLiteralExpr in C
3877// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003878// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003879// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003880// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003881// * ObjCEncodeExpr
3882// * AddrLabelExpr
3883// * BlockExpr
3884// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003885// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003886// * Any Expr, with a CallIndex indicating the function in which the temporary
3887// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003888// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003889//===----------------------------------------------------------------------===//
3890namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003891class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003892 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003893public:
Richard Smith027bf112011-11-17 22:56:20 +00003894 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3895 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003896
Richard Smith11562c52011-10-28 17:51:58 +00003897 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003898 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003899
Peter Collingbournee9200682011-05-13 03:29:01 +00003900 bool VisitDeclRefExpr(const DeclRefExpr *E);
3901 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003902 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003903 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3904 bool VisitMemberExpr(const MemberExpr *E);
3905 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3906 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003907 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003908 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003909 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3910 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003911 bool VisitUnaryReal(const UnaryOperator *E);
3912 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003913 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3914 return VisitUnaryPreIncDec(UO);
3915 }
3916 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3917 return VisitUnaryPreIncDec(UO);
3918 }
Richard Smith3229b742013-05-05 21:17:10 +00003919 bool VisitBinAssign(const BinaryOperator *BO);
3920 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003921
Peter Collingbournee9200682011-05-13 03:29:01 +00003922 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003923 switch (E->getCastKind()) {
3924 default:
Richard Smith027bf112011-11-17 22:56:20 +00003925 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003926
Eli Friedmance3e02a2011-10-11 00:13:24 +00003927 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003928 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003929 if (!Visit(E->getSubExpr()))
3930 return false;
3931 Result.Designator.setInvalid();
3932 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003933
Richard Smith027bf112011-11-17 22:56:20 +00003934 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003935 if (!Visit(E->getSubExpr()))
3936 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003937 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003938 }
3939 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003940};
3941} // end anonymous namespace
3942
Richard Smith11562c52011-10-28 17:51:58 +00003943/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003944/// expressions which are not glvalues, in two cases:
3945/// * function designators in C, and
3946/// * "extern void" objects
3947static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3948 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3949 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003950 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003951}
3952
Peter Collingbournee9200682011-05-13 03:29:01 +00003953bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003954 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3955 return Success(FD);
3956 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003957 return VisitVarDecl(E, VD);
3958 return Error(E);
3959}
Richard Smith733237d2011-10-24 23:14:33 +00003960
Richard Smith11562c52011-10-28 17:51:58 +00003961bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003962 CallStackFrame *Frame = 0;
3963 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3964 Frame = Info.CurrentCall;
3965
Richard Smithfec09922011-11-01 16:57:24 +00003966 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003967 if (Frame) {
3968 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003969 return true;
3970 }
Richard Smithce40ad62011-11-12 22:28:03 +00003971 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003972 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003973
Richard Smith3229b742013-05-05 21:17:10 +00003974 APValue *V;
3975 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003976 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003977 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003978}
3979
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003980bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3981 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003982 if (E->getType()->isRecordType())
3983 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003984
Richard Smithb228a862012-02-15 02:18:13 +00003985 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003986 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3987 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003988}
3989
Peter Collingbournee9200682011-05-13 03:29:01 +00003990bool
3991LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003992 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3993 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3994 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003995 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003996}
3997
Richard Smith6e525142011-12-27 12:18:28 +00003998bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003999 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004000 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004001
4002 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4003 << E->getExprOperand()->getType()
4004 << E->getExprOperand()->getSourceRange();
4005 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004006}
4007
Francois Pichet0066db92012-04-16 04:08:35 +00004008bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4009 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004010}
Francois Pichet0066db92012-04-16 04:08:35 +00004011
Peter Collingbournee9200682011-05-13 03:29:01 +00004012bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004013 // Handle static data members.
4014 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4015 VisitIgnoredValue(E->getBase());
4016 return VisitVarDecl(E, VD);
4017 }
4018
Richard Smith254a73d2011-10-28 22:34:42 +00004019 // Handle static member functions.
4020 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4021 if (MD->isStatic()) {
4022 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004023 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004024 }
4025 }
4026
Richard Smithd62306a2011-11-10 06:34:14 +00004027 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004028 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004029}
4030
Peter Collingbournee9200682011-05-13 03:29:01 +00004031bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004032 // FIXME: Deal with vectors as array subscript bases.
4033 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004034 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004035
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004036 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004037 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004038
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004039 APSInt Index;
4040 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004041 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004042
Richard Smith861b5b52013-05-07 23:34:45 +00004043 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4044 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004045}
Eli Friedman9a156e52008-11-12 09:44:48 +00004046
Peter Collingbournee9200682011-05-13 03:29:01 +00004047bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004048 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004049}
4050
Richard Smith66c96992012-02-18 22:04:06 +00004051bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4052 if (!Visit(E->getSubExpr()))
4053 return false;
4054 // __real is a no-op on scalar lvalues.
4055 if (E->getSubExpr()->getType()->isAnyComplexType())
4056 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4057 return true;
4058}
4059
4060bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4061 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4062 "lvalue __imag__ on scalar?");
4063 if (!Visit(E->getSubExpr()))
4064 return false;
4065 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4066 return true;
4067}
4068
Richard Smith243ef902013-05-05 23:31:59 +00004069bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4070 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004071 return Error(UO);
4072
4073 if (!this->Visit(UO->getSubExpr()))
4074 return false;
4075
Richard Smith243ef902013-05-05 23:31:59 +00004076 return handleIncDec(
4077 this->Info, UO, Result, UO->getSubExpr()->getType(),
4078 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00004079}
4080
4081bool LValueExprEvaluator::VisitCompoundAssignOperator(
4082 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00004083 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004084 return Error(CAO);
4085
Richard Smith3229b742013-05-05 21:17:10 +00004086 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004087
4088 // The overall lvalue result is the result of evaluating the LHS.
4089 if (!this->Visit(CAO->getLHS())) {
4090 if (Info.keepEvaluatingAfterFailure())
4091 Evaluate(RHS, this->Info, CAO->getRHS());
4092 return false;
4093 }
4094
Richard Smith3229b742013-05-05 21:17:10 +00004095 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4096 return false;
4097
Richard Smith43e77732013-05-07 04:50:00 +00004098 return handleCompoundAssignment(
4099 this->Info, CAO,
4100 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4101 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004102}
4103
4104bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00004105 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4106 return Error(E);
4107
Richard Smith3229b742013-05-05 21:17:10 +00004108 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004109
4110 if (!this->Visit(E->getLHS())) {
4111 if (Info.keepEvaluatingAfterFailure())
4112 Evaluate(NewVal, this->Info, E->getRHS());
4113 return false;
4114 }
4115
Richard Smith3229b742013-05-05 21:17:10 +00004116 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4117 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004118
4119 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004120 NewVal);
4121}
4122
Eli Friedman9a156e52008-11-12 09:44:48 +00004123//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004124// Pointer Evaluation
4125//===----------------------------------------------------------------------===//
4126
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004127namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004128class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004129 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00004130 LValue &Result;
4131
Peter Collingbournee9200682011-05-13 03:29:01 +00004132 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004133 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004134 return true;
4135 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004136public:
Mike Stump11289f42009-09-09 15:08:12 +00004137
John McCall45d55e42010-05-07 21:00:08 +00004138 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004139 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004140
Richard Smith2e312c82012-03-03 22:46:17 +00004141 bool Success(const APValue &V, const Expr *E) {
4142 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004143 return true;
4144 }
Richard Smithfddd3842011-12-30 21:15:51 +00004145 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004146 return Success((Expr*)0);
4147 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004148
John McCall45d55e42010-05-07 21:00:08 +00004149 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004150 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004151 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004152 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004153 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004154 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004155 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004156 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004157 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004158 bool VisitCallExpr(const CallExpr *E);
4159 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004160 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004161 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004162 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004163 }
Richard Smithd62306a2011-11-10 06:34:14 +00004164 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4165 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004166 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004167 Result = *Info.CurrentCall->This;
4168 return true;
4169 }
John McCallc07a0c72011-02-17 10:25:35 +00004170
Eli Friedman449fe542009-03-23 04:56:01 +00004171 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004172};
Chris Lattner05706e882008-07-11 18:11:29 +00004173} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004174
John McCall45d55e42010-05-07 21:00:08 +00004175static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004176 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004177 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004178}
4179
John McCall45d55e42010-05-07 21:00:08 +00004180bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004181 if (E->getOpcode() != BO_Add &&
4182 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004183 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004184
Chris Lattner05706e882008-07-11 18:11:29 +00004185 const Expr *PExp = E->getLHS();
4186 const Expr *IExp = E->getRHS();
4187 if (IExp->getType()->isPointerType())
4188 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004189
Richard Smith253c2a32012-01-27 01:14:48 +00004190 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4191 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004192 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004193
John McCall45d55e42010-05-07 21:00:08 +00004194 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004195 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004196 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004197
4198 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004199 if (E->getOpcode() == BO_Sub)
4200 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004201
Ted Kremenek28831752012-08-23 20:46:57 +00004202 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004203 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4204 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004205}
Eli Friedman9a156e52008-11-12 09:44:48 +00004206
John McCall45d55e42010-05-07 21:00:08 +00004207bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4208 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004209}
Mike Stump11289f42009-09-09 15:08:12 +00004210
Peter Collingbournee9200682011-05-13 03:29:01 +00004211bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4212 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004213
Eli Friedman847a2bc2009-12-27 05:43:15 +00004214 switch (E->getCastKind()) {
4215 default:
4216 break;
4217
John McCalle3027922010-08-25 11:45:40 +00004218 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004219 case CK_CPointerToObjCPointerCast:
4220 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004221 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004222 if (!Visit(SubExpr))
4223 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004224 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4225 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4226 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004227 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004228 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004229 if (SubExpr->getType()->isVoidPointerType())
4230 CCEDiag(E, diag::note_constexpr_invalid_cast)
4231 << 3 << SubExpr->getType();
4232 else
4233 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4234 }
Richard Smith96e0c102011-11-04 02:25:55 +00004235 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004236
Anders Carlsson18275092010-10-31 20:41:46 +00004237 case CK_DerivedToBase:
4238 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004239 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004240 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004241 if (!Result.Base && Result.Offset.isZero())
4242 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004243
Richard Smithd62306a2011-11-10 06:34:14 +00004244 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004245 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00004246 QualType Type =
4247 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00004248
Richard Smithd62306a2011-11-10 06:34:14 +00004249 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00004250 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004251 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
4252 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00004253 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004254 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00004255 }
4256
Anders Carlsson18275092010-10-31 20:41:46 +00004257 return true;
4258 }
4259
Richard Smith027bf112011-11-17 22:56:20 +00004260 case CK_BaseToDerived:
4261 if (!Visit(E->getSubExpr()))
4262 return false;
4263 if (!Result.Base && Result.Offset.isZero())
4264 return true;
4265 return HandleBaseToDerivedCast(Info, E, Result);
4266
Richard Smith0b0a0b62011-10-29 20:57:55 +00004267 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004268 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004269 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004270
John McCalle3027922010-08-25 11:45:40 +00004271 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004272 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4273
Richard Smith2e312c82012-03-03 22:46:17 +00004274 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004275 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004276 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004277
John McCall45d55e42010-05-07 21:00:08 +00004278 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004279 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4280 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004281 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004282 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004283 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004284 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004285 return true;
4286 } else {
4287 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004288 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004289 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004290 }
4291 }
John McCalle3027922010-08-25 11:45:40 +00004292 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004293 if (SubExpr->isGLValue()) {
4294 if (!EvaluateLValue(SubExpr, Result, Info))
4295 return false;
4296 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004297 Result.set(SubExpr, Info.CurrentCall->Index);
4298 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4299 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004300 return false;
4301 }
Richard Smith96e0c102011-11-04 02:25:55 +00004302 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004303 if (const ConstantArrayType *CAT
4304 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4305 Result.addArray(Info, E, CAT);
4306 else
4307 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004308 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004309
John McCalle3027922010-08-25 11:45:40 +00004310 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004311 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004312 }
4313
Richard Smith11562c52011-10-28 17:51:58 +00004314 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004315}
Chris Lattner05706e882008-07-11 18:11:29 +00004316
Peter Collingbournee9200682011-05-13 03:29:01 +00004317bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004318 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004319 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004320
Peter Collingbournee9200682011-05-13 03:29:01 +00004321 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004322}
Chris Lattner05706e882008-07-11 18:11:29 +00004323
4324//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004325// Member Pointer Evaluation
4326//===----------------------------------------------------------------------===//
4327
4328namespace {
4329class MemberPointerExprEvaluator
4330 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4331 MemberPtr &Result;
4332
4333 bool Success(const ValueDecl *D) {
4334 Result = MemberPtr(D);
4335 return true;
4336 }
4337public:
4338
4339 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4340 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4341
Richard Smith2e312c82012-03-03 22:46:17 +00004342 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004343 Result.setFrom(V);
4344 return true;
4345 }
Richard Smithfddd3842011-12-30 21:15:51 +00004346 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004347 return Success((const ValueDecl*)0);
4348 }
4349
4350 bool VisitCastExpr(const CastExpr *E);
4351 bool VisitUnaryAddrOf(const UnaryOperator *E);
4352};
4353} // end anonymous namespace
4354
4355static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4356 EvalInfo &Info) {
4357 assert(E->isRValue() && E->getType()->isMemberPointerType());
4358 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4359}
4360
4361bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4362 switch (E->getCastKind()) {
4363 default:
4364 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4365
4366 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004367 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004368 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004369
4370 case CK_BaseToDerivedMemberPointer: {
4371 if (!Visit(E->getSubExpr()))
4372 return false;
4373 if (E->path_empty())
4374 return true;
4375 // Base-to-derived member pointer casts store the path in derived-to-base
4376 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4377 // the wrong end of the derived->base arc, so stagger the path by one class.
4378 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4379 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4380 PathI != PathE; ++PathI) {
4381 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4382 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4383 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004384 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004385 }
4386 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4387 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004388 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004389 return true;
4390 }
4391
4392 case CK_DerivedToBaseMemberPointer:
4393 if (!Visit(E->getSubExpr()))
4394 return false;
4395 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4396 PathE = E->path_end(); PathI != PathE; ++PathI) {
4397 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4398 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4399 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004400 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004401 }
4402 return true;
4403 }
4404}
4405
4406bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4407 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4408 // member can be formed.
4409 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4410}
4411
4412//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004413// Record Evaluation
4414//===----------------------------------------------------------------------===//
4415
4416namespace {
4417 class RecordExprEvaluator
4418 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4419 const LValue &This;
4420 APValue &Result;
4421 public:
4422
4423 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4424 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4425
Richard Smith2e312c82012-03-03 22:46:17 +00004426 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004427 Result = V;
4428 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004429 }
Richard Smithfddd3842011-12-30 21:15:51 +00004430 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004431
Richard Smithe97cbd72011-11-11 04:05:33 +00004432 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004433 bool VisitInitListExpr(const InitListExpr *E);
4434 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4435 };
4436}
4437
Richard Smithfddd3842011-12-30 21:15:51 +00004438/// Perform zero-initialization on an object of non-union class type.
4439/// C++11 [dcl.init]p5:
4440/// To zero-initialize an object or reference of type T means:
4441/// [...]
4442/// -- if T is a (possibly cv-qualified) non-union class type,
4443/// each non-static data member and each base-class subobject is
4444/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004445static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4446 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004447 const LValue &This, APValue &Result) {
4448 assert(!RD->isUnion() && "Expected non-union class type");
4449 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4450 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4451 std::distance(RD->field_begin(), RD->field_end()));
4452
John McCalld7bca762012-05-01 00:38:49 +00004453 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004454 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4455
4456 if (CD) {
4457 unsigned Index = 0;
4458 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004459 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004460 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4461 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004462 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4463 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004464 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004465 Result.getStructBase(Index)))
4466 return false;
4467 }
4468 }
4469
Richard Smitha8105bc2012-01-06 16:39:00 +00004470 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4471 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004472 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004473 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004474 continue;
4475
4476 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004477 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004478 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004479
David Blaikie2d7c57e2012-04-30 02:36:29 +00004480 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004481 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004482 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004483 return false;
4484 }
4485
4486 return true;
4487}
4488
4489bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4490 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004491 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004492 if (RD->isUnion()) {
4493 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4494 // object's first non-static named data member is zero-initialized
4495 RecordDecl::field_iterator I = RD->field_begin();
4496 if (I == RD->field_end()) {
4497 Result = APValue((const FieldDecl*)0);
4498 return true;
4499 }
4500
4501 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004502 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004503 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004504 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004505 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004506 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004507 }
4508
Richard Smith5d108602012-02-17 00:44:16 +00004509 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004510 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004511 return false;
4512 }
4513
Richard Smitha8105bc2012-01-06 16:39:00 +00004514 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004515}
4516
Richard Smithe97cbd72011-11-11 04:05:33 +00004517bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4518 switch (E->getCastKind()) {
4519 default:
4520 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4521
4522 case CK_ConstructorConversion:
4523 return Visit(E->getSubExpr());
4524
4525 case CK_DerivedToBase:
4526 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004527 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004528 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004529 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004530 if (!DerivedObject.isStruct())
4531 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004532
4533 // Derived-to-base rvalue conversion: just slice off the derived part.
4534 APValue *Value = &DerivedObject;
4535 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4536 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4537 PathE = E->path_end(); PathI != PathE; ++PathI) {
4538 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4539 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4540 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4541 RD = Base;
4542 }
4543 Result = *Value;
4544 return true;
4545 }
4546 }
4547}
4548
Richard Smithd62306a2011-11-10 06:34:14 +00004549bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004550 // Cannot constant-evaluate std::initializer_list inits.
4551 if (E->initializesStdInitializerList())
4552 return false;
4553
Richard Smithd62306a2011-11-10 06:34:14 +00004554 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004555 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004556 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4557
4558 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004559 const FieldDecl *Field = E->getInitializedFieldInUnion();
4560 Result = APValue(Field);
4561 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004562 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004563
4564 // If the initializer list for a union does not contain any elements, the
4565 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004566 // FIXME: The element should be initialized from an initializer list.
4567 // Is this difference ever observable for initializer lists which
4568 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004569 ImplicitValueInitExpr VIE(Field->getType());
4570 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4571
Richard Smithd62306a2011-11-10 06:34:14 +00004572 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004573 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4574 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004575
4576 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4577 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4578 isa<CXXDefaultInitExpr>(InitExpr));
4579
Richard Smithb228a862012-02-15 02:18:13 +00004580 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004581 }
4582
4583 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4584 "initializer list for class with base classes");
4585 Result = APValue(APValue::UninitStruct(), 0,
4586 std::distance(RD->field_begin(), RD->field_end()));
4587 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004588 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004589 for (RecordDecl::field_iterator Field = RD->field_begin(),
4590 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4591 // Anonymous bit-fields are not considered members of the class for
4592 // purposes of aggregate initialization.
4593 if (Field->isUnnamedBitfield())
4594 continue;
4595
4596 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004597
Richard Smith253c2a32012-01-27 01:14:48 +00004598 bool HaveInit = ElementNo < E->getNumInits();
4599
4600 // FIXME: Diagnostics here should point to the end of the initializer
4601 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004602 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004603 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004604 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004605
4606 // Perform an implicit value-initialization for members beyond the end of
4607 // the initializer list.
4608 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004609 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004610
Richard Smith852c9db2013-04-20 22:23:05 +00004611 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4612 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4613 isa<CXXDefaultInitExpr>(Init));
4614
4615 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4616 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004617 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004618 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004619 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004620 }
4621 }
4622
Richard Smith253c2a32012-01-27 01:14:48 +00004623 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004624}
4625
4626bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4627 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004628 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4629
Richard Smithfddd3842011-12-30 21:15:51 +00004630 bool ZeroInit = E->requiresZeroInitialization();
4631 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004632 // If we've already performed zero-initialization, we're already done.
4633 if (!Result.isUninit())
4634 return true;
4635
Richard Smithfddd3842011-12-30 21:15:51 +00004636 if (ZeroInit)
4637 return ZeroInitialization(E);
4638
Richard Smithcc36f692011-12-22 02:22:31 +00004639 const CXXRecordDecl *RD = FD->getParent();
4640 if (RD->isUnion())
4641 Result = APValue((FieldDecl*)0);
4642 else
4643 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4644 std::distance(RD->field_begin(), RD->field_end()));
4645 return true;
4646 }
4647
Richard Smithd62306a2011-11-10 06:34:14 +00004648 const FunctionDecl *Definition = 0;
4649 FD->getBody(Definition);
4650
Richard Smith357362d2011-12-13 06:39:58 +00004651 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4652 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004653
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004654 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004655 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004656 if (const MaterializeTemporaryExpr *ME
4657 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4658 return Visit(ME->GetTemporaryExpr());
4659
Richard Smithfddd3842011-12-30 21:15:51 +00004660 if (ZeroInit && !ZeroInitialization(E))
4661 return false;
4662
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004663 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004664 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004665 cast<CXXConstructorDecl>(Definition), Info,
4666 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004667}
4668
4669static bool EvaluateRecord(const Expr *E, const LValue &This,
4670 APValue &Result, EvalInfo &Info) {
4671 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004672 "can't evaluate expression as a record rvalue");
4673 return RecordExprEvaluator(Info, This, Result).Visit(E);
4674}
4675
4676//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004677// Temporary Evaluation
4678//
4679// Temporaries are represented in the AST as rvalues, but generally behave like
4680// lvalues. The full-object of which the temporary is a subobject is implicitly
4681// materialized so that a reference can bind to it.
4682//===----------------------------------------------------------------------===//
4683namespace {
4684class TemporaryExprEvaluator
4685 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4686public:
4687 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4688 LValueExprEvaluatorBaseTy(Info, Result) {}
4689
4690 /// Visit an expression which constructs the value of this temporary.
4691 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004692 Result.set(E, Info.CurrentCall->Index);
4693 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004694 }
4695
4696 bool VisitCastExpr(const CastExpr *E) {
4697 switch (E->getCastKind()) {
4698 default:
4699 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4700
4701 case CK_ConstructorConversion:
4702 return VisitConstructExpr(E->getSubExpr());
4703 }
4704 }
4705 bool VisitInitListExpr(const InitListExpr *E) {
4706 return VisitConstructExpr(E);
4707 }
4708 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4709 return VisitConstructExpr(E);
4710 }
4711 bool VisitCallExpr(const CallExpr *E) {
4712 return VisitConstructExpr(E);
4713 }
4714};
4715} // end anonymous namespace
4716
4717/// Evaluate an expression of record type as a temporary.
4718static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004719 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004720 return TemporaryExprEvaluator(Info, Result).Visit(E);
4721}
4722
4723//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004724// Vector Evaluation
4725//===----------------------------------------------------------------------===//
4726
4727namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004728 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004729 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4730 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004731 public:
Mike Stump11289f42009-09-09 15:08:12 +00004732
Richard Smith2d406342011-10-22 21:10:00 +00004733 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4734 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004735
Richard Smith2d406342011-10-22 21:10:00 +00004736 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4737 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4738 // FIXME: remove this APValue copy.
4739 Result = APValue(V.data(), V.size());
4740 return true;
4741 }
Richard Smith2e312c82012-03-03 22:46:17 +00004742 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004743 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004744 Result = V;
4745 return true;
4746 }
Richard Smithfddd3842011-12-30 21:15:51 +00004747 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004748
Richard Smith2d406342011-10-22 21:10:00 +00004749 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004750 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004751 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004752 bool VisitInitListExpr(const InitListExpr *E);
4753 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004754 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004755 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004756 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004757 };
4758} // end anonymous namespace
4759
4760static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004761 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004762 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004763}
4764
Richard Smith2d406342011-10-22 21:10:00 +00004765bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4766 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004767 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004768
Richard Smith161f09a2011-12-06 22:44:34 +00004769 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004770 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004771
Eli Friedmanc757de22011-03-25 00:43:55 +00004772 switch (E->getCastKind()) {
4773 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004774 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004775 if (SETy->isIntegerType()) {
4776 APSInt IntResult;
4777 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004778 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004779 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004780 } else if (SETy->isRealFloatingType()) {
4781 APFloat F(0.0);
4782 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004783 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004784 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004785 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004786 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004787 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004788
4789 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004790 SmallVector<APValue, 4> Elts(NElts, Val);
4791 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004792 }
Eli Friedman803acb32011-12-22 03:51:45 +00004793 case CK_BitCast: {
4794 // Evaluate the operand into an APInt we can extract from.
4795 llvm::APInt SValInt;
4796 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4797 return false;
4798 // Extract the elements
4799 QualType EltTy = VTy->getElementType();
4800 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4801 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4802 SmallVector<APValue, 4> Elts;
4803 if (EltTy->isRealFloatingType()) {
4804 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004805 unsigned FloatEltSize = EltSize;
4806 if (&Sem == &APFloat::x87DoubleExtended)
4807 FloatEltSize = 80;
4808 for (unsigned i = 0; i < NElts; i++) {
4809 llvm::APInt Elt;
4810 if (BigEndian)
4811 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4812 else
4813 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004814 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004815 }
4816 } else if (EltTy->isIntegerType()) {
4817 for (unsigned i = 0; i < NElts; i++) {
4818 llvm::APInt Elt;
4819 if (BigEndian)
4820 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4821 else
4822 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4823 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4824 }
4825 } else {
4826 return Error(E);
4827 }
4828 return Success(Elts, E);
4829 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004830 default:
Richard Smith11562c52011-10-28 17:51:58 +00004831 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004832 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004833}
4834
Richard Smith2d406342011-10-22 21:10:00 +00004835bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004836VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004837 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004838 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004839 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004840
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004841 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004842 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004843
Eli Friedmanb9c71292012-01-03 23:24:20 +00004844 // The number of initializers can be less than the number of
4845 // vector elements. For OpenCL, this can be due to nested vector
4846 // initialization. For GCC compatibility, missing trailing elements
4847 // should be initialized with zeroes.
4848 unsigned CountInits = 0, CountElts = 0;
4849 while (CountElts < NumElements) {
4850 // Handle nested vector initialization.
4851 if (CountInits < NumInits
4852 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4853 APValue v;
4854 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4855 return Error(E);
4856 unsigned vlen = v.getVectorLength();
4857 for (unsigned j = 0; j < vlen; j++)
4858 Elements.push_back(v.getVectorElt(j));
4859 CountElts += vlen;
4860 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004861 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004862 if (CountInits < NumInits) {
4863 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004864 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004865 } else // trailing integer zero.
4866 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4867 Elements.push_back(APValue(sInt));
4868 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004869 } else {
4870 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004871 if (CountInits < NumInits) {
4872 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004873 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004874 } else // trailing float zero.
4875 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4876 Elements.push_back(APValue(f));
4877 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004878 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004879 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004880 }
Richard Smith2d406342011-10-22 21:10:00 +00004881 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004882}
4883
Richard Smith2d406342011-10-22 21:10:00 +00004884bool
Richard Smithfddd3842011-12-30 21:15:51 +00004885VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004886 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004887 QualType EltTy = VT->getElementType();
4888 APValue ZeroElement;
4889 if (EltTy->isIntegerType())
4890 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4891 else
4892 ZeroElement =
4893 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4894
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004895 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004896 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004897}
4898
Richard Smith2d406342011-10-22 21:10:00 +00004899bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004900 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004901 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004902}
4903
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004904//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004905// Array Evaluation
4906//===----------------------------------------------------------------------===//
4907
4908namespace {
4909 class ArrayExprEvaluator
4910 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004911 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004912 APValue &Result;
4913 public:
4914
Richard Smithd62306a2011-11-10 06:34:14 +00004915 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4916 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004917
4918 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004919 assert((V.isArray() || V.isLValue()) &&
4920 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004921 Result = V;
4922 return true;
4923 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004924
Richard Smithfddd3842011-12-30 21:15:51 +00004925 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004926 const ConstantArrayType *CAT =
4927 Info.Ctx.getAsConstantArrayType(E->getType());
4928 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004929 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004930
4931 Result = APValue(APValue::UninitArray(), 0,
4932 CAT->getSize().getZExtValue());
4933 if (!Result.hasArrayFiller()) return true;
4934
Richard Smithfddd3842011-12-30 21:15:51 +00004935 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004936 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004937 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004938 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004939 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004940 }
4941
Richard Smithf3e9e432011-11-07 09:22:26 +00004942 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004943 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004944 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4945 const LValue &Subobject,
4946 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004947 };
4948} // end anonymous namespace
4949
Richard Smithd62306a2011-11-10 06:34:14 +00004950static bool EvaluateArray(const Expr *E, const LValue &This,
4951 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004952 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004953 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004954}
4955
4956bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4957 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4958 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004959 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004960
Richard Smithca2cfbf2011-12-22 01:07:19 +00004961 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4962 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004963 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004964 LValue LV;
4965 if (!EvaluateLValue(E->getInit(0), LV, Info))
4966 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004967 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004968 LV.moveInto(Val);
4969 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004970 }
4971
Richard Smith253c2a32012-01-27 01:14:48 +00004972 bool Success = true;
4973
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004974 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4975 "zero-initialized array shouldn't have any initialized elts");
4976 APValue Filler;
4977 if (Result.isArray() && Result.hasArrayFiller())
4978 Filler = Result.getArrayFiller();
4979
Richard Smith9543c5e2013-04-22 14:44:29 +00004980 unsigned NumEltsToInit = E->getNumInits();
4981 unsigned NumElts = CAT->getSize().getZExtValue();
4982 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4983
4984 // If the initializer might depend on the array index, run it for each
4985 // array element. For now, just whitelist non-class value-initialization.
4986 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4987 NumEltsToInit = NumElts;
4988
4989 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004990
4991 // If the array was previously zero-initialized, preserve the
4992 // zero-initialized values.
4993 if (!Filler.isUninit()) {
4994 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4995 Result.getArrayInitializedElt(I) = Filler;
4996 if (Result.hasArrayFiller())
4997 Result.getArrayFiller() = Filler;
4998 }
4999
Richard Smithd62306a2011-11-10 06:34:14 +00005000 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005001 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005002 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5003 const Expr *Init =
5004 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005005 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005006 Info, Subobject, Init) ||
5007 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005008 CAT->getElementType(), 1)) {
5009 if (!Info.keepEvaluatingAfterFailure())
5010 return false;
5011 Success = false;
5012 }
Richard Smithd62306a2011-11-10 06:34:14 +00005013 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005014
Richard Smith9543c5e2013-04-22 14:44:29 +00005015 if (!Result.hasArrayFiller())
5016 return Success;
5017
5018 // If we get here, we have a trivial filler, which we can just evaluate
5019 // once and splat over the rest of the array elements.
5020 assert(FillerExpr && "no array filler for incomplete init list");
5021 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5022 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005023}
5024
Richard Smith027bf112011-11-17 22:56:20 +00005025bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005026 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5027}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005028
Richard Smith9543c5e2013-04-22 14:44:29 +00005029bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5030 const LValue &Subobject,
5031 APValue *Value,
5032 QualType Type) {
5033 bool HadZeroInit = !Value->isUninit();
5034
5035 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5036 unsigned N = CAT->getSize().getZExtValue();
5037
5038 // Preserve the array filler if we had prior zero-initialization.
5039 APValue Filler =
5040 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5041 : APValue();
5042
5043 *Value = APValue(APValue::UninitArray(), N, N);
5044
5045 if (HadZeroInit)
5046 for (unsigned I = 0; I != N; ++I)
5047 Value->getArrayInitializedElt(I) = Filler;
5048
5049 // Initialize the elements.
5050 LValue ArrayElt = Subobject;
5051 ArrayElt.addArray(Info, E, CAT);
5052 for (unsigned I = 0; I != N; ++I)
5053 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5054 CAT->getElementType()) ||
5055 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5056 CAT->getElementType(), 1))
5057 return false;
5058
5059 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005060 }
Richard Smith027bf112011-11-17 22:56:20 +00005061
Richard Smith9543c5e2013-04-22 14:44:29 +00005062 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005063 return Error(E);
5064
Richard Smith027bf112011-11-17 22:56:20 +00005065 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005066
Richard Smithfddd3842011-12-30 21:15:51 +00005067 bool ZeroInit = E->requiresZeroInitialization();
5068 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005069 if (HadZeroInit)
5070 return true;
5071
Richard Smithfddd3842011-12-30 21:15:51 +00005072 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005073 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005074 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005075 }
5076
Richard Smithcc36f692011-12-22 02:22:31 +00005077 const CXXRecordDecl *RD = FD->getParent();
5078 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005079 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00005080 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005081 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00005082 APValue(APValue::UninitStruct(), RD->getNumBases(),
5083 std::distance(RD->field_begin(), RD->field_end()));
5084 return true;
5085 }
5086
Richard Smith027bf112011-11-17 22:56:20 +00005087 const FunctionDecl *Definition = 0;
5088 FD->getBody(Definition);
5089
Richard Smith357362d2011-12-13 06:39:58 +00005090 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5091 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005092
Richard Smith9eae7232012-01-12 18:54:33 +00005093 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005094 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005095 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005096 return false;
5097 }
5098
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005099 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005100 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005101 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005102 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005103}
5104
Richard Smithf3e9e432011-11-07 09:22:26 +00005105//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005106// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005107//
5108// As a GNU extension, we support casting pointers to sufficiently-wide integer
5109// types and back in constant folding. Integer values are thus represented
5110// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005111//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005112
5113namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005114class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005115 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00005116 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005117public:
Richard Smith2e312c82012-03-03 22:46:17 +00005118 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005119 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005120
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005121 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005122 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005123 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005124 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005125 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005126 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005127 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005128 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005129 return true;
5130 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005131 bool Success(const llvm::APSInt &SI, const Expr *E) {
5132 return Success(SI, E, Result);
5133 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005134
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005135 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005136 assert(E->getType()->isIntegralOrEnumerationType() &&
5137 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005138 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005139 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005140 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005141 Result.getInt().setIsUnsigned(
5142 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005143 return true;
5144 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005145 bool Success(const llvm::APInt &I, const Expr *E) {
5146 return Success(I, E, Result);
5147 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005148
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005149 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005150 assert(E->getType()->isIntegralOrEnumerationType() &&
5151 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005152 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005153 return true;
5154 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005155 bool Success(uint64_t Value, const Expr *E) {
5156 return Success(Value, E, Result);
5157 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005158
Ken Dyckdbc01912011-03-11 02:13:43 +00005159 bool Success(CharUnits Size, const Expr *E) {
5160 return Success(Size.getQuantity(), E);
5161 }
5162
Richard Smith2e312c82012-03-03 22:46:17 +00005163 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005164 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005165 Result = V;
5166 return true;
5167 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005168 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005169 }
Mike Stump11289f42009-09-09 15:08:12 +00005170
Richard Smithfddd3842011-12-30 21:15:51 +00005171 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005172
Peter Collingbournee9200682011-05-13 03:29:01 +00005173 //===--------------------------------------------------------------------===//
5174 // Visitor Methods
5175 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005176
Chris Lattner7174bf32008-07-12 00:38:25 +00005177 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005178 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005179 }
5180 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005181 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005182 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005183
5184 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5185 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005186 if (CheckReferencedDecl(E, E->getDecl()))
5187 return true;
5188
5189 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005190 }
5191 bool VisitMemberExpr(const MemberExpr *E) {
5192 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005193 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005194 return true;
5195 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005196
5197 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005198 }
5199
Peter Collingbournee9200682011-05-13 03:29:01 +00005200 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005201 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005202 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005203 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005204
Peter Collingbournee9200682011-05-13 03:29:01 +00005205 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005206 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005207
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005208 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005209 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005210 }
Mike Stump11289f42009-09-09 15:08:12 +00005211
Ted Kremeneke65b0862012-03-06 20:05:56 +00005212 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5213 return Success(E->getValue(), E);
5214 }
5215
Richard Smith4ce706a2011-10-11 21:43:33 +00005216 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005217 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005218 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005219 }
5220
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005221 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005222 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005223 }
5224
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005225 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5226 return Success(E->getValue(), E);
5227 }
5228
Douglas Gregor29c42f22012-02-24 07:38:34 +00005229 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5230 return Success(E->getValue(), E);
5231 }
5232
John Wiegley6242b6a2011-04-28 00:16:57 +00005233 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5234 return Success(E->getValue(), E);
5235 }
5236
John Wiegleyf9f65842011-04-25 06:54:41 +00005237 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5238 return Success(E->getValue(), E);
5239 }
5240
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005241 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005242 bool VisitUnaryImag(const UnaryOperator *E);
5243
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005244 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005245 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005246
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005247private:
Ken Dyck160146e2010-01-27 17:10:57 +00005248 CharUnits GetAlignOfExpr(const Expr *E);
5249 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005250 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005251 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005252 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005253};
Chris Lattner05706e882008-07-11 18:11:29 +00005254} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005255
Richard Smith11562c52011-10-28 17:51:58 +00005256/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5257/// produce either the integer value or a pointer.
5258///
5259/// GCC has a heinous extension which folds casts between pointer types and
5260/// pointer-sized integral types. We support this by allowing the evaluation of
5261/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5262/// Some simple arithmetic on such values is supported (they are treated much
5263/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005264static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005265 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005266 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005267 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005268}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005269
Richard Smithf57d8cb2011-12-09 22:58:01 +00005270static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005271 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005272 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005273 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005274 if (!Val.isInt()) {
5275 // FIXME: It would be better to produce the diagnostic for casting
5276 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005277 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005278 return false;
5279 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005280 Result = Val.getInt();
5281 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005282}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005283
Richard Smithf57d8cb2011-12-09 22:58:01 +00005284/// Check whether the given declaration can be directly converted to an integral
5285/// rvalue. If not, no diagnostic is produced; there are other things we can
5286/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005287bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005288 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005289 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005290 // Check for signedness/width mismatches between E type and ECD value.
5291 bool SameSign = (ECD->getInitVal().isSigned()
5292 == E->getType()->isSignedIntegerOrEnumerationType());
5293 bool SameWidth = (ECD->getInitVal().getBitWidth()
5294 == Info.Ctx.getIntWidth(E->getType()));
5295 if (SameSign && SameWidth)
5296 return Success(ECD->getInitVal(), E);
5297 else {
5298 // Get rid of mismatch (otherwise Success assertions will fail)
5299 // by computing a new value matching the type of E.
5300 llvm::APSInt Val = ECD->getInitVal();
5301 if (!SameSign)
5302 Val.setIsSigned(!ECD->getInitVal().isSigned());
5303 if (!SameWidth)
5304 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5305 return Success(Val, E);
5306 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005307 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005308 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005309}
5310
Chris Lattner86ee2862008-10-06 06:40:35 +00005311/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5312/// as GCC.
5313static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5314 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005315 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005316 enum gcc_type_class {
5317 no_type_class = -1,
5318 void_type_class, integer_type_class, char_type_class,
5319 enumeral_type_class, boolean_type_class,
5320 pointer_type_class, reference_type_class, offset_type_class,
5321 real_type_class, complex_type_class,
5322 function_type_class, method_type_class,
5323 record_type_class, union_type_class,
5324 array_type_class, string_type_class,
5325 lang_type_class
5326 };
Mike Stump11289f42009-09-09 15:08:12 +00005327
5328 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005329 // ideal, however it is what gcc does.
5330 if (E->getNumArgs() == 0)
5331 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005332
Chris Lattner86ee2862008-10-06 06:40:35 +00005333 QualType ArgTy = E->getArg(0)->getType();
5334 if (ArgTy->isVoidType())
5335 return void_type_class;
5336 else if (ArgTy->isEnumeralType())
5337 return enumeral_type_class;
5338 else if (ArgTy->isBooleanType())
5339 return boolean_type_class;
5340 else if (ArgTy->isCharType())
5341 return string_type_class; // gcc doesn't appear to use char_type_class
5342 else if (ArgTy->isIntegerType())
5343 return integer_type_class;
5344 else if (ArgTy->isPointerType())
5345 return pointer_type_class;
5346 else if (ArgTy->isReferenceType())
5347 return reference_type_class;
5348 else if (ArgTy->isRealType())
5349 return real_type_class;
5350 else if (ArgTy->isComplexType())
5351 return complex_type_class;
5352 else if (ArgTy->isFunctionType())
5353 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005354 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005355 return record_type_class;
5356 else if (ArgTy->isUnionType())
5357 return union_type_class;
5358 else if (ArgTy->isArrayType())
5359 return array_type_class;
5360 else if (ArgTy->isUnionType())
5361 return union_type_class;
5362 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005363 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005364}
5365
Richard Smith5fab0c92011-12-28 19:48:30 +00005366/// EvaluateBuiltinConstantPForLValue - Determine the result of
5367/// __builtin_constant_p when applied to the given lvalue.
5368///
5369/// An lvalue is only "constant" if it is a pointer or reference to the first
5370/// character of a string literal.
5371template<typename LValue>
5372static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005373 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005374 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5375}
5376
5377/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5378/// GCC as we can manage.
5379static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5380 QualType ArgType = Arg->getType();
5381
5382 // __builtin_constant_p always has one operand. The rules which gcc follows
5383 // are not precisely documented, but are as follows:
5384 //
5385 // - If the operand is of integral, floating, complex or enumeration type,
5386 // and can be folded to a known value of that type, it returns 1.
5387 // - If the operand and can be folded to a pointer to the first character
5388 // of a string literal (or such a pointer cast to an integral type), it
5389 // returns 1.
5390 //
5391 // Otherwise, it returns 0.
5392 //
5393 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5394 // its support for this does not currently work.
5395 if (ArgType->isIntegralOrEnumerationType()) {
5396 Expr::EvalResult Result;
5397 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5398 return false;
5399
5400 APValue &V = Result.Val;
5401 if (V.getKind() == APValue::Int)
5402 return true;
5403
5404 return EvaluateBuiltinConstantPForLValue(V);
5405 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5406 return Arg->isEvaluatable(Ctx);
5407 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5408 LValue LV;
5409 Expr::EvalStatus Status;
5410 EvalInfo Info(Ctx, Status);
5411 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5412 : EvaluatePointer(Arg, LV, Info)) &&
5413 !Status.HasSideEffects)
5414 return EvaluateBuiltinConstantPForLValue(LV);
5415 }
5416
5417 // Anything else isn't considered to be sufficiently constant.
5418 return false;
5419}
5420
John McCall95007602010-05-10 23:27:23 +00005421/// Retrieves the "underlying object type" of the given expression,
5422/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005423QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5424 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5425 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005426 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005427 } else if (const Expr *E = B.get<const Expr*>()) {
5428 if (isa<CompoundLiteralExpr>(E))
5429 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005430 }
5431
5432 return QualType();
5433}
5434
Peter Collingbournee9200682011-05-13 03:29:01 +00005435bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005436 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005437
5438 {
5439 // The operand of __builtin_object_size is never evaluated for side-effects.
5440 // If there are any, but we can determine the pointed-to object anyway, then
5441 // ignore the side-effects.
5442 SpeculativeEvaluationRAII SpeculativeEval(Info);
5443 if (!EvaluatePointer(E->getArg(0), Base, Info))
5444 return false;
5445 }
John McCall95007602010-05-10 23:27:23 +00005446
5447 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005448 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005449
Richard Smithce40ad62011-11-12 22:28:03 +00005450 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005451 if (T.isNull() ||
5452 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005453 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005454 T->isVariablyModifiedType() ||
5455 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005456 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005457
5458 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5459 CharUnits Offset = Base.getLValueOffset();
5460
5461 if (!Offset.isNegative() && Offset <= Size)
5462 Size -= Offset;
5463 else
5464 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005465 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005466}
5467
Peter Collingbournee9200682011-05-13 03:29:01 +00005468bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005469 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005470 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005471 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005472
5473 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005474 if (TryEvaluateBuiltinObjectSize(E))
5475 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005476
Richard Smith0421ce72012-08-07 04:16:51 +00005477 // If evaluating the argument has side-effects, we can't determine the size
5478 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5479 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005480 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005481 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005482 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005483 return Success(0, E);
5484 }
Mike Stump876387b2009-10-27 22:09:17 +00005485
Richard Smith01ade172012-05-23 04:13:20 +00005486 // Expression had no side effects, but we couldn't statically determine the
5487 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005488 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005489 }
5490
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005491 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005492 case Builtin::BI__builtin_bswap32:
5493 case Builtin::BI__builtin_bswap64: {
5494 APSInt Val;
5495 if (!EvaluateInteger(E->getArg(0), Val, Info))
5496 return false;
5497
5498 return Success(Val.byteSwap(), E);
5499 }
5500
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005501 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005502 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005503
Richard Smith5fab0c92011-12-28 19:48:30 +00005504 case Builtin::BI__builtin_constant_p:
5505 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005506
Chris Lattnerd545ad12009-09-23 06:06:36 +00005507 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005508 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005509 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005510 return Success(Operand, E);
5511 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005512
5513 case Builtin::BI__builtin_expect:
5514 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005515
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005516 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005517 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005518 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005519 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005520 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5521 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005522 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005523 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005524 case Builtin::BI__builtin_strlen:
5525 // As an extension, we support strlen() and __builtin_strlen() as constant
5526 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005527 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005528 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5529 // The string literal may have embedded null characters. Find the first
5530 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005531 StringRef Str = S->getString();
5532 StringRef::size_type Pos = Str.find(0);
5533 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005534 Str = Str.substr(0, Pos);
5535
5536 return Success(Str.size(), E);
5537 }
5538
Richard Smithf57d8cb2011-12-09 22:58:01 +00005539 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005540
Richard Smith01ba47d2012-04-13 00:45:38 +00005541 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005542 case Builtin::BI__atomic_is_lock_free:
5543 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005544 APSInt SizeVal;
5545 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5546 return false;
5547
5548 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5549 // of two less than the maximum inline atomic width, we know it is
5550 // lock-free. If the size isn't a power of two, or greater than the
5551 // maximum alignment where we promote atomics, we know it is not lock-free
5552 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5553 // the answer can only be determined at runtime; for example, 16-byte
5554 // atomics have lock-free implementations on some, but not all,
5555 // x86-64 processors.
5556
5557 // Check power-of-two.
5558 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005559 if (Size.isPowerOfTwo()) {
5560 // Check against inlining width.
5561 unsigned InlineWidthBits =
5562 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5563 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5564 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5565 Size == CharUnits::One() ||
5566 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5567 Expr::NPC_NeverValueDependent))
5568 // OK, we will inline appropriately-aligned operations of this size,
5569 // and _Atomic(T) is appropriately-aligned.
5570 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005571
Richard Smith01ba47d2012-04-13 00:45:38 +00005572 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5573 castAs<PointerType>()->getPointeeType();
5574 if (!PointeeType->isIncompleteType() &&
5575 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5576 // OK, we will inline operations on this object.
5577 return Success(1, E);
5578 }
5579 }
5580 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005581
Richard Smith01ba47d2012-04-13 00:45:38 +00005582 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5583 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005584 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005585 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005586}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005587
Richard Smith8b3497e2011-10-31 01:37:14 +00005588static bool HasSameBase(const LValue &A, const LValue &B) {
5589 if (!A.getLValueBase())
5590 return !B.getLValueBase();
5591 if (!B.getLValueBase())
5592 return false;
5593
Richard Smithce40ad62011-11-12 22:28:03 +00005594 if (A.getLValueBase().getOpaqueValue() !=
5595 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005596 const Decl *ADecl = GetLValueBaseDecl(A);
5597 if (!ADecl)
5598 return false;
5599 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005600 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005601 return false;
5602 }
5603
5604 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005605 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005606}
5607
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005608namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005609
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005610/// \brief Data recursive integer evaluator of certain binary operators.
5611///
5612/// We use a data recursive algorithm for binary operators so that we are able
5613/// to handle extreme cases of chained binary operators without causing stack
5614/// overflow.
5615class DataRecursiveIntBinOpEvaluator {
5616 struct EvalResult {
5617 APValue Val;
5618 bool Failed;
5619
5620 EvalResult() : Failed(false) { }
5621
5622 void swap(EvalResult &RHS) {
5623 Val.swap(RHS.Val);
5624 Failed = RHS.Failed;
5625 RHS.Failed = false;
5626 }
5627 };
5628
5629 struct Job {
5630 const Expr *E;
5631 EvalResult LHSResult; // meaningful only for binary operator expression.
5632 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5633
5634 Job() : StoredInfo(0) { }
5635 void startSpeculativeEval(EvalInfo &Info) {
5636 OldEvalStatus = Info.EvalStatus;
5637 Info.EvalStatus.Diag = 0;
5638 StoredInfo = &Info;
5639 }
5640 ~Job() {
5641 if (StoredInfo) {
5642 StoredInfo->EvalStatus = OldEvalStatus;
5643 }
5644 }
5645 private:
5646 EvalInfo *StoredInfo; // non-null if status changed.
5647 Expr::EvalStatus OldEvalStatus;
5648 };
5649
5650 SmallVector<Job, 16> Queue;
5651
5652 IntExprEvaluator &IntEval;
5653 EvalInfo &Info;
5654 APValue &FinalResult;
5655
5656public:
5657 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5658 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5659
5660 /// \brief True if \param E is a binary operator that we are going to handle
5661 /// data recursively.
5662 /// We handle binary operators that are comma, logical, or that have operands
5663 /// with integral or enumeration type.
5664 static bool shouldEnqueue(const BinaryOperator *E) {
5665 return E->getOpcode() == BO_Comma ||
5666 E->isLogicalOp() ||
5667 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5668 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005669 }
5670
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005671 bool Traverse(const BinaryOperator *E) {
5672 enqueue(E);
5673 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005674 while (!Queue.empty())
5675 process(PrevResult);
5676
5677 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005678
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005679 FinalResult.swap(PrevResult.Val);
5680 return true;
5681 }
5682
5683private:
5684 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5685 return IntEval.Success(Value, E, Result);
5686 }
5687 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5688 return IntEval.Success(Value, E, Result);
5689 }
5690 bool Error(const Expr *E) {
5691 return IntEval.Error(E);
5692 }
5693 bool Error(const Expr *E, diag::kind D) {
5694 return IntEval.Error(E, D);
5695 }
5696
5697 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5698 return Info.CCEDiag(E, D);
5699 }
5700
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005701 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5702 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005703 bool &SuppressRHSDiags);
5704
5705 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5706 const BinaryOperator *E, APValue &Result);
5707
5708 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5709 Result.Failed = !Evaluate(Result.Val, Info, E);
5710 if (Result.Failed)
5711 Result.Val = APValue();
5712 }
5713
Richard Trieuba4d0872012-03-21 23:30:30 +00005714 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005715
5716 void enqueue(const Expr *E) {
5717 E = E->IgnoreParens();
5718 Queue.resize(Queue.size()+1);
5719 Queue.back().E = E;
5720 Queue.back().Kind = Job::AnyExprKind;
5721 }
5722};
5723
5724}
5725
5726bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005727 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005728 bool &SuppressRHSDiags) {
5729 if (E->getOpcode() == BO_Comma) {
5730 // Ignore LHS but note if we could not evaluate it.
5731 if (LHSResult.Failed)
5732 Info.EvalStatus.HasSideEffects = true;
5733 return true;
5734 }
5735
5736 if (E->isLogicalOp()) {
5737 bool lhsResult;
5738 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005739 // We were able to evaluate the LHS, see if we can get away with not
5740 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005741 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005742 Success(lhsResult, E, LHSResult.Val);
5743 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005744 }
5745 } else {
5746 // Since we weren't able to evaluate the left hand side, it
5747 // must have had side effects.
5748 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005749
5750 // We can't evaluate the LHS; however, sometimes the result
5751 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5752 // Don't ignore RHS and suppress diagnostics from this arm.
5753 SuppressRHSDiags = true;
5754 }
5755
5756 return true;
5757 }
5758
5759 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5760 E->getRHS()->getType()->isIntegralOrEnumerationType());
5761
5762 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005763 return false; // Ignore RHS;
5764
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005765 return true;
5766}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005767
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005768bool DataRecursiveIntBinOpEvaluator::
5769 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5770 const BinaryOperator *E, APValue &Result) {
5771 if (E->getOpcode() == BO_Comma) {
5772 if (RHSResult.Failed)
5773 return false;
5774 Result = RHSResult.Val;
5775 return true;
5776 }
5777
5778 if (E->isLogicalOp()) {
5779 bool lhsResult, rhsResult;
5780 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5781 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5782
5783 if (LHSIsOK) {
5784 if (RHSIsOK) {
5785 if (E->getOpcode() == BO_LOr)
5786 return Success(lhsResult || rhsResult, E, Result);
5787 else
5788 return Success(lhsResult && rhsResult, E, Result);
5789 }
5790 } else {
5791 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005792 // We can't evaluate the LHS; however, sometimes the result
5793 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5794 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005795 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005796 }
5797 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005798
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005799 return false;
5800 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005801
5802 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5803 E->getRHS()->getType()->isIntegralOrEnumerationType());
5804
5805 if (LHSResult.Failed || RHSResult.Failed)
5806 return false;
5807
5808 const APValue &LHSVal = LHSResult.Val;
5809 const APValue &RHSVal = RHSResult.Val;
5810
5811 // Handle cases like (unsigned long)&a + 4.
5812 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5813 Result = LHSVal;
5814 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5815 RHSVal.getInt().getZExtValue());
5816 if (E->getOpcode() == BO_Add)
5817 Result.getLValueOffset() += AdditionalOffset;
5818 else
5819 Result.getLValueOffset() -= AdditionalOffset;
5820 return true;
5821 }
5822
5823 // Handle cases like 4 + (unsigned long)&a
5824 if (E->getOpcode() == BO_Add &&
5825 RHSVal.isLValue() && LHSVal.isInt()) {
5826 Result = RHSVal;
5827 Result.getLValueOffset() += CharUnits::fromQuantity(
5828 LHSVal.getInt().getZExtValue());
5829 return true;
5830 }
5831
5832 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5833 // Handle (intptr_t)&&A - (intptr_t)&&B.
5834 if (!LHSVal.getLValueOffset().isZero() ||
5835 !RHSVal.getLValueOffset().isZero())
5836 return false;
5837 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5838 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5839 if (!LHSExpr || !RHSExpr)
5840 return false;
5841 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5842 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5843 if (!LHSAddrExpr || !RHSAddrExpr)
5844 return false;
5845 // Make sure both labels come from the same function.
5846 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5847 RHSAddrExpr->getLabel()->getDeclContext())
5848 return false;
5849 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5850 return true;
5851 }
Richard Smith43e77732013-05-07 04:50:00 +00005852
5853 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005854 if (!LHSVal.isInt() || !RHSVal.isInt())
5855 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00005856
5857 // Set up the width and signedness manually, in case it can't be deduced
5858 // from the operation we're performing.
5859 // FIXME: Don't do this in the cases where we can deduce it.
5860 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
5861 E->getType()->isUnsignedIntegerOrEnumerationType());
5862 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
5863 RHSVal.getInt(), Value))
5864 return false;
5865 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005866}
5867
Richard Trieuba4d0872012-03-21 23:30:30 +00005868void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005869 Job &job = Queue.back();
5870
5871 switch (job.Kind) {
5872 case Job::AnyExprKind: {
5873 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5874 if (shouldEnqueue(Bop)) {
5875 job.Kind = Job::BinOpKind;
5876 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005877 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005878 }
5879 }
5880
5881 EvaluateExpr(job.E, Result);
5882 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005883 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005884 }
5885
5886 case Job::BinOpKind: {
5887 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005888 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005889 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005890 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005891 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005892 }
5893 if (SuppressRHSDiags)
5894 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005895 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005896 job.Kind = Job::BinOpVisitedLHSKind;
5897 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005898 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005899 }
5900
5901 case Job::BinOpVisitedLHSKind: {
5902 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5903 EvalResult RHS;
5904 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005905 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005906 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005907 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005908 }
5909 }
5910
5911 llvm_unreachable("Invalid Job::Kind!");
5912}
5913
5914bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5915 if (E->isAssignmentOp())
5916 return Error(E);
5917
5918 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5919 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005920
Anders Carlssonacc79812008-11-16 07:17:21 +00005921 QualType LHSTy = E->getLHS()->getType();
5922 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005923
5924 if (LHSTy->isAnyComplexType()) {
5925 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005926 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005927
Richard Smith253c2a32012-01-27 01:14:48 +00005928 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5929 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005930 return false;
5931
Richard Smith253c2a32012-01-27 01:14:48 +00005932 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005933 return false;
5934
5935 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005936 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005937 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005938 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005939 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5940
John McCalle3027922010-08-25 11:45:40 +00005941 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005942 return Success((CR_r == APFloat::cmpEqual &&
5943 CR_i == APFloat::cmpEqual), E);
5944 else {
John McCalle3027922010-08-25 11:45:40 +00005945 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005946 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005947 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005948 CR_r == APFloat::cmpLessThan ||
5949 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005950 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005951 CR_i == APFloat::cmpLessThan ||
5952 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005953 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005954 } else {
John McCalle3027922010-08-25 11:45:40 +00005955 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005956 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5957 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5958 else {
John McCalle3027922010-08-25 11:45:40 +00005959 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005960 "Invalid compex comparison.");
5961 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5962 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5963 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005964 }
5965 }
Mike Stump11289f42009-09-09 15:08:12 +00005966
Anders Carlssonacc79812008-11-16 07:17:21 +00005967 if (LHSTy->isRealFloatingType() &&
5968 RHSTy->isRealFloatingType()) {
5969 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005970
Richard Smith253c2a32012-01-27 01:14:48 +00005971 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5972 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005973 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005974
Richard Smith253c2a32012-01-27 01:14:48 +00005975 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005976 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005977
Anders Carlssonacc79812008-11-16 07:17:21 +00005978 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005979
Anders Carlssonacc79812008-11-16 07:17:21 +00005980 switch (E->getOpcode()) {
5981 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005982 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005983 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005984 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005985 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005986 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005987 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005988 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005989 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005990 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005991 E);
John McCalle3027922010-08-25 11:45:40 +00005992 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005993 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005994 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005995 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005996 || CR == APFloat::cmpLessThan
5997 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005998 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005999 }
Mike Stump11289f42009-09-09 15:08:12 +00006000
Eli Friedmana38da572009-04-28 19:17:36 +00006001 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006002 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006003 LValue LHSValue, RHSValue;
6004
6005 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6006 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006007 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006008
Richard Smith253c2a32012-01-27 01:14:48 +00006009 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006010 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006011
Richard Smith8b3497e2011-10-31 01:37:14 +00006012 // Reject differing bases from the normal codepath; we special-case
6013 // comparisons to null.
6014 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006015 if (E->getOpcode() == BO_Sub) {
6016 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006017 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6018 return false;
6019 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006020 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006021 if (!LHSExpr || !RHSExpr)
6022 return false;
6023 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6024 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6025 if (!LHSAddrExpr || !RHSAddrExpr)
6026 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006027 // Make sure both labels come from the same function.
6028 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6029 RHSAddrExpr->getLabel()->getDeclContext())
6030 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006031 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006032 return true;
6033 }
Richard Smith83c68212011-10-31 05:11:32 +00006034 // Inequalities and subtractions between unrelated pointers have
6035 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006036 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006037 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006038 // A constant address may compare equal to the address of a symbol.
6039 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006040 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006041 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6042 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006043 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006044 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006045 // distinct addresses. In clang, the result of such a comparison is
6046 // unspecified, so it is not a constant expression. However, we do know
6047 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006048 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6049 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006050 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006051 // We can't tell whether weak symbols will end up pointing to the same
6052 // object.
6053 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006054 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006055 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006056 // (Note that clang defaults to -fmerge-all-constants, which can
6057 // lead to inconsistent results for comparisons involving the address
6058 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006059 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006060 }
Eli Friedman64004332009-03-23 04:38:34 +00006061
Richard Smith1b470412012-02-01 08:10:20 +00006062 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6063 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6064
Richard Smith84f6dcf2012-02-02 01:16:57 +00006065 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6066 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6067
John McCalle3027922010-08-25 11:45:40 +00006068 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006069 // C++11 [expr.add]p6:
6070 // Unless both pointers point to elements of the same array object, or
6071 // one past the last element of the array object, the behavior is
6072 // undefined.
6073 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6074 !AreElementsOfSameArray(getType(LHSValue.Base),
6075 LHSDesignator, RHSDesignator))
6076 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6077
Chris Lattner882bdf22010-04-20 17:13:14 +00006078 QualType Type = E->getLHS()->getType();
6079 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006080
Richard Smithd62306a2011-11-10 06:34:14 +00006081 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006082 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006083 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006084
Richard Smith1b470412012-02-01 08:10:20 +00006085 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6086 // and produce incorrect results when it overflows. Such behavior
6087 // appears to be non-conforming, but is common, so perhaps we should
6088 // assume the standard intended for such cases to be undefined behavior
6089 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006090
Richard Smith1b470412012-02-01 08:10:20 +00006091 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6092 // overflow in the final conversion to ptrdiff_t.
6093 APSInt LHS(
6094 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6095 APSInt RHS(
6096 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6097 APSInt ElemSize(
6098 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6099 APSInt TrueResult = (LHS - RHS) / ElemSize;
6100 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6101
6102 if (Result.extend(65) != TrueResult)
6103 HandleOverflow(Info, E, TrueResult, E->getType());
6104 return Success(Result, E);
6105 }
Richard Smithde21b242012-01-31 06:41:30 +00006106
6107 // C++11 [expr.rel]p3:
6108 // Pointers to void (after pointer conversions) can be compared, with a
6109 // result defined as follows: If both pointers represent the same
6110 // address or are both the null pointer value, the result is true if the
6111 // operator is <= or >= and false otherwise; otherwise the result is
6112 // unspecified.
6113 // We interpret this as applying to pointers to *cv* void.
6114 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006115 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006116 CCEDiag(E, diag::note_constexpr_void_comparison);
6117
Richard Smith84f6dcf2012-02-02 01:16:57 +00006118 // C++11 [expr.rel]p2:
6119 // - If two pointers point to non-static data members of the same object,
6120 // or to subobjects or array elements fo such members, recursively, the
6121 // pointer to the later declared member compares greater provided the
6122 // two members have the same access control and provided their class is
6123 // not a union.
6124 // [...]
6125 // - Otherwise pointer comparisons are unspecified.
6126 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6127 E->isRelationalOp()) {
6128 bool WasArrayIndex;
6129 unsigned Mismatch =
6130 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6131 RHSDesignator, WasArrayIndex);
6132 // At the point where the designators diverge, the comparison has a
6133 // specified value if:
6134 // - we are comparing array indices
6135 // - we are comparing fields of a union, or fields with the same access
6136 // Otherwise, the result is unspecified and thus the comparison is not a
6137 // constant expression.
6138 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6139 Mismatch < RHSDesignator.Entries.size()) {
6140 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6141 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6142 if (!LF && !RF)
6143 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6144 else if (!LF)
6145 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6146 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6147 << RF->getParent() << RF;
6148 else if (!RF)
6149 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6150 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6151 << LF->getParent() << LF;
6152 else if (!LF->getParent()->isUnion() &&
6153 LF->getAccess() != RF->getAccess())
6154 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6155 << LF << LF->getAccess() << RF << RF->getAccess()
6156 << LF->getParent();
6157 }
6158 }
6159
Eli Friedman6c31cb42012-04-16 04:30:08 +00006160 // The comparison here must be unsigned, and performed with the same
6161 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006162 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6163 uint64_t CompareLHS = LHSOffset.getQuantity();
6164 uint64_t CompareRHS = RHSOffset.getQuantity();
6165 assert(PtrSize <= 64 && "Unexpected pointer width");
6166 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6167 CompareLHS &= Mask;
6168 CompareRHS &= Mask;
6169
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006170 // If there is a base and this is a relational operator, we can only
6171 // compare pointers within the object in question; otherwise, the result
6172 // depends on where the object is located in memory.
6173 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6174 QualType BaseTy = getType(LHSValue.Base);
6175 if (BaseTy->isIncompleteType())
6176 return Error(E);
6177 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6178 uint64_t OffsetLimit = Size.getQuantity();
6179 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6180 return Error(E);
6181 }
6182
Richard Smith8b3497e2011-10-31 01:37:14 +00006183 switch (E->getOpcode()) {
6184 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006185 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6186 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6187 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6188 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6189 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6190 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006191 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006192 }
6193 }
Richard Smith7bb00672012-02-01 01:42:44 +00006194
6195 if (LHSTy->isMemberPointerType()) {
6196 assert(E->isEqualityOp() && "unexpected member pointer operation");
6197 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6198
6199 MemberPtr LHSValue, RHSValue;
6200
6201 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6202 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6203 return false;
6204
6205 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6206 return false;
6207
6208 // C++11 [expr.eq]p2:
6209 // If both operands are null, they compare equal. Otherwise if only one is
6210 // null, they compare unequal.
6211 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6212 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6213 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6214 }
6215
6216 // Otherwise if either is a pointer to a virtual member function, the
6217 // result is unspecified.
6218 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6219 if (MD->isVirtual())
6220 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6221 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6222 if (MD->isVirtual())
6223 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6224
6225 // Otherwise they compare equal if and only if they would refer to the
6226 // same member of the same most derived object or the same subobject if
6227 // they were dereferenced with a hypothetical object of the associated
6228 // class type.
6229 bool Equal = LHSValue == RHSValue;
6230 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6231 }
6232
Richard Smithab44d9b2012-02-14 22:35:28 +00006233 if (LHSTy->isNullPtrType()) {
6234 assert(E->isComparisonOp() && "unexpected nullptr operation");
6235 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6236 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6237 // are compared, the result is true of the operator is <=, >= or ==, and
6238 // false otherwise.
6239 BinaryOperator::Opcode Opcode = E->getOpcode();
6240 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6241 }
6242
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006243 assert((!LHSTy->isIntegralOrEnumerationType() ||
6244 !RHSTy->isIntegralOrEnumerationType()) &&
6245 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6246 // We can't continue from here for non-integral types.
6247 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006248}
6249
Ken Dyck160146e2010-01-27 17:10:57 +00006250CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006251 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6252 // result shall be the alignment of the referenced type."
6253 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6254 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006255
6256 // __alignof is defined to return the preferred alignment.
6257 return Info.Ctx.toCharUnitsFromBits(
6258 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006259}
6260
Ken Dyck160146e2010-01-27 17:10:57 +00006261CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006262 E = E->IgnoreParens();
6263
John McCall768439e2013-05-06 07:40:34 +00006264 // The kinds of expressions that we have special-case logic here for
6265 // should be kept up to date with the special checks for those
6266 // expressions in Sema.
6267
Chris Lattner68061312009-01-24 21:53:27 +00006268 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006269 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006270 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006271 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6272 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006273
Chris Lattner68061312009-01-24 21:53:27 +00006274 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006275 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6276 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006277
Chris Lattner24aeeab2009-01-24 21:09:06 +00006278 return GetAlignOfType(E->getType());
6279}
6280
6281
Peter Collingbournee190dee2011-03-11 19:24:49 +00006282/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6283/// a result as the expression's type.
6284bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6285 const UnaryExprOrTypeTraitExpr *E) {
6286 switch(E->getKind()) {
6287 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006288 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006289 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006290 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006291 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006292 }
Eli Friedman64004332009-03-23 04:38:34 +00006293
Peter Collingbournee190dee2011-03-11 19:24:49 +00006294 case UETT_VecStep: {
6295 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006296
Peter Collingbournee190dee2011-03-11 19:24:49 +00006297 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006298 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006299
Peter Collingbournee190dee2011-03-11 19:24:49 +00006300 // The vec_step built-in functions that take a 3-component
6301 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6302 if (n == 3)
6303 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006304
Peter Collingbournee190dee2011-03-11 19:24:49 +00006305 return Success(n, E);
6306 } else
6307 return Success(1, E);
6308 }
6309
6310 case UETT_SizeOf: {
6311 QualType SrcTy = E->getTypeOfArgument();
6312 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6313 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006314 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6315 SrcTy = Ref->getPointeeType();
6316
Richard Smithd62306a2011-11-10 06:34:14 +00006317 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006318 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006319 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006320 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006321 }
6322 }
6323
6324 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006325}
6326
Peter Collingbournee9200682011-05-13 03:29:01 +00006327bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006328 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006329 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006330 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006331 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006332 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006333 for (unsigned i = 0; i != n; ++i) {
6334 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6335 switch (ON.getKind()) {
6336 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006337 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006338 APSInt IdxResult;
6339 if (!EvaluateInteger(Idx, IdxResult, Info))
6340 return false;
6341 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6342 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006343 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006344 CurrentType = AT->getElementType();
6345 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6346 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006347 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006348 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006349
Douglas Gregor882211c2010-04-28 22:16:22 +00006350 case OffsetOfExpr::OffsetOfNode::Field: {
6351 FieldDecl *MemberDecl = ON.getField();
6352 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006353 if (!RT)
6354 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006355 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006356 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006357 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006358 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006359 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006360 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006361 CurrentType = MemberDecl->getType().getNonReferenceType();
6362 break;
6363 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006364
Douglas Gregor882211c2010-04-28 22:16:22 +00006365 case OffsetOfExpr::OffsetOfNode::Identifier:
6366 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006367
Douglas Gregord1702062010-04-29 00:18:15 +00006368 case OffsetOfExpr::OffsetOfNode::Base: {
6369 CXXBaseSpecifier *BaseSpec = ON.getBase();
6370 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006371 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006372
6373 // Find the layout of the class whose base we are looking into.
6374 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006375 if (!RT)
6376 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006377 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006378 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006379 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6380
6381 // Find the base class itself.
6382 CurrentType = BaseSpec->getType();
6383 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6384 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006385 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006386
6387 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006388 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006389 break;
6390 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006391 }
6392 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006393 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006394}
6395
Chris Lattnere13042c2008-07-11 19:10:17 +00006396bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006397 switch (E->getOpcode()) {
6398 default:
6399 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6400 // See C99 6.6p3.
6401 return Error(E);
6402 case UO_Extension:
6403 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6404 // If so, we could clear the diagnostic ID.
6405 return Visit(E->getSubExpr());
6406 case UO_Plus:
6407 // The result is just the value.
6408 return Visit(E->getSubExpr());
6409 case UO_Minus: {
6410 if (!Visit(E->getSubExpr()))
6411 return false;
6412 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006413 const APSInt &Value = Result.getInt();
6414 if (Value.isSigned() && Value.isMinSignedValue())
6415 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6416 E->getType());
6417 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006418 }
6419 case UO_Not: {
6420 if (!Visit(E->getSubExpr()))
6421 return false;
6422 if (!Result.isInt()) return Error(E);
6423 return Success(~Result.getInt(), E);
6424 }
6425 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006426 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006427 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006428 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006429 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006430 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006431 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006432}
Mike Stump11289f42009-09-09 15:08:12 +00006433
Chris Lattner477c4be2008-07-12 01:15:53 +00006434/// HandleCast - This is used to evaluate implicit or explicit casts where the
6435/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006436bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6437 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006438 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006439 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006440
Eli Friedmanc757de22011-03-25 00:43:55 +00006441 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006442 case CK_BaseToDerived:
6443 case CK_DerivedToBase:
6444 case CK_UncheckedDerivedToBase:
6445 case CK_Dynamic:
6446 case CK_ToUnion:
6447 case CK_ArrayToPointerDecay:
6448 case CK_FunctionToPointerDecay:
6449 case CK_NullToPointer:
6450 case CK_NullToMemberPointer:
6451 case CK_BaseToDerivedMemberPointer:
6452 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006453 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006454 case CK_ConstructorConversion:
6455 case CK_IntegralToPointer:
6456 case CK_ToVoid:
6457 case CK_VectorSplat:
6458 case CK_IntegralToFloating:
6459 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006460 case CK_CPointerToObjCPointerCast:
6461 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006462 case CK_AnyPointerToBlockPointerCast:
6463 case CK_ObjCObjectLValueCast:
6464 case CK_FloatingRealToComplex:
6465 case CK_FloatingComplexToReal:
6466 case CK_FloatingComplexCast:
6467 case CK_FloatingComplexToIntegralComplex:
6468 case CK_IntegralRealToComplex:
6469 case CK_IntegralComplexCast:
6470 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006471 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006472 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006473 llvm_unreachable("invalid cast kind for integral value");
6474
Eli Friedman9faf2f92011-03-25 19:07:11 +00006475 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006476 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006477 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006478 case CK_ARCProduceObject:
6479 case CK_ARCConsumeObject:
6480 case CK_ARCReclaimReturnedObject:
6481 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006482 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006483 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006484
Richard Smith4ef685b2012-01-17 21:17:26 +00006485 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006486 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006487 case CK_AtomicToNonAtomic:
6488 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006489 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006490 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006491
6492 case CK_MemberPointerToBoolean:
6493 case CK_PointerToBoolean:
6494 case CK_IntegralToBoolean:
6495 case CK_FloatingToBoolean:
6496 case CK_FloatingComplexToBoolean:
6497 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006498 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006499 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006500 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006501 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006502 }
6503
Eli Friedmanc757de22011-03-25 00:43:55 +00006504 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006505 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006506 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006507
Eli Friedman742421e2009-02-20 01:15:07 +00006508 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006509 // Allow casts of address-of-label differences if they are no-ops
6510 // or narrowing. (The narrowing case isn't actually guaranteed to
6511 // be constant-evaluatable except in some narrow cases which are hard
6512 // to detect here. We let it through on the assumption the user knows
6513 // what they are doing.)
6514 if (Result.isAddrLabelDiff())
6515 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006516 // Only allow casts of lvalues if they are lossless.
6517 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6518 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006519
Richard Smith911e1422012-01-30 22:27:01 +00006520 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6521 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006522 }
Mike Stump11289f42009-09-09 15:08:12 +00006523
Eli Friedmanc757de22011-03-25 00:43:55 +00006524 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006525 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6526
John McCall45d55e42010-05-07 21:00:08 +00006527 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006528 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006529 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006530
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006531 if (LV.getLValueBase()) {
6532 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006533 // FIXME: Allow a larger integer size than the pointer size, and allow
6534 // narrowing back down to pointer width in subsequent integral casts.
6535 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006536 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006537 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006538
Richard Smithcf74da72011-11-16 07:18:12 +00006539 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006540 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006541 return true;
6542 }
6543
Ken Dyck02990832010-01-15 12:37:54 +00006544 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6545 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006546 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006547 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006548
Eli Friedmanc757de22011-03-25 00:43:55 +00006549 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006550 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006551 if (!EvaluateComplex(SubExpr, C, Info))
6552 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006553 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006554 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006555
Eli Friedmanc757de22011-03-25 00:43:55 +00006556 case CK_FloatingToIntegral: {
6557 APFloat F(0.0);
6558 if (!EvaluateFloat(SubExpr, F, Info))
6559 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006560
Richard Smith357362d2011-12-13 06:39:58 +00006561 APSInt Value;
6562 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6563 return false;
6564 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006565 }
6566 }
Mike Stump11289f42009-09-09 15:08:12 +00006567
Eli Friedmanc757de22011-03-25 00:43:55 +00006568 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006569}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006570
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006571bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6572 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006573 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006574 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6575 return false;
6576 if (!LV.isComplexInt())
6577 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006578 return Success(LV.getComplexIntReal(), E);
6579 }
6580
6581 return Visit(E->getSubExpr());
6582}
6583
Eli Friedman4e7a2412009-02-27 04:45:43 +00006584bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006585 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006586 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006587 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6588 return false;
6589 if (!LV.isComplexInt())
6590 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006591 return Success(LV.getComplexIntImag(), E);
6592 }
6593
Richard Smith4a678122011-10-24 18:44:57 +00006594 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006595 return Success(0, E);
6596}
6597
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006598bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6599 return Success(E->getPackLength(), E);
6600}
6601
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006602bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6603 return Success(E->getValue(), E);
6604}
6605
Chris Lattner05706e882008-07-11 18:11:29 +00006606//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006607// Float Evaluation
6608//===----------------------------------------------------------------------===//
6609
6610namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006611class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006612 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006613 APFloat &Result;
6614public:
6615 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006616 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006617
Richard Smith2e312c82012-03-03 22:46:17 +00006618 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006619 Result = V.getFloat();
6620 return true;
6621 }
Eli Friedman24c01542008-08-22 00:06:13 +00006622
Richard Smithfddd3842011-12-30 21:15:51 +00006623 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006624 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6625 return true;
6626 }
6627
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006628 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006629
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006630 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006631 bool VisitBinaryOperator(const BinaryOperator *E);
6632 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006633 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006634
John McCallb1fb0d32010-05-07 22:08:54 +00006635 bool VisitUnaryReal(const UnaryOperator *E);
6636 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006637
Richard Smithfddd3842011-12-30 21:15:51 +00006638 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006639};
6640} // end anonymous namespace
6641
6642static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006643 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006644 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006645}
6646
Jay Foad39c79802011-01-12 09:06:06 +00006647static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006648 QualType ResultTy,
6649 const Expr *Arg,
6650 bool SNaN,
6651 llvm::APFloat &Result) {
6652 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6653 if (!S) return false;
6654
6655 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6656
6657 llvm::APInt fill;
6658
6659 // Treat empty strings as if they were zero.
6660 if (S->getString().empty())
6661 fill = llvm::APInt(32, 0);
6662 else if (S->getString().getAsInteger(0, fill))
6663 return false;
6664
6665 if (SNaN)
6666 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6667 else
6668 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6669 return true;
6670}
6671
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006672bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006673 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006674 default:
6675 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6676
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006677 case Builtin::BI__builtin_huge_val:
6678 case Builtin::BI__builtin_huge_valf:
6679 case Builtin::BI__builtin_huge_vall:
6680 case Builtin::BI__builtin_inf:
6681 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006682 case Builtin::BI__builtin_infl: {
6683 const llvm::fltSemantics &Sem =
6684 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006685 Result = llvm::APFloat::getInf(Sem);
6686 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006687 }
Mike Stump11289f42009-09-09 15:08:12 +00006688
John McCall16291492010-02-28 13:00:19 +00006689 case Builtin::BI__builtin_nans:
6690 case Builtin::BI__builtin_nansf:
6691 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006692 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6693 true, Result))
6694 return Error(E);
6695 return true;
John McCall16291492010-02-28 13:00:19 +00006696
Chris Lattner0b7282e2008-10-06 06:31:58 +00006697 case Builtin::BI__builtin_nan:
6698 case Builtin::BI__builtin_nanf:
6699 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006700 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006701 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006702 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6703 false, Result))
6704 return Error(E);
6705 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006706
6707 case Builtin::BI__builtin_fabs:
6708 case Builtin::BI__builtin_fabsf:
6709 case Builtin::BI__builtin_fabsl:
6710 if (!EvaluateFloat(E->getArg(0), Result, Info))
6711 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006712
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006713 if (Result.isNegative())
6714 Result.changeSign();
6715 return true;
6716
Mike Stump11289f42009-09-09 15:08:12 +00006717 case Builtin::BI__builtin_copysign:
6718 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006719 case Builtin::BI__builtin_copysignl: {
6720 APFloat RHS(0.);
6721 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6722 !EvaluateFloat(E->getArg(1), RHS, Info))
6723 return false;
6724 Result.copySign(RHS);
6725 return true;
6726 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006727 }
6728}
6729
John McCallb1fb0d32010-05-07 22:08:54 +00006730bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006731 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6732 ComplexValue CV;
6733 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6734 return false;
6735 Result = CV.FloatReal;
6736 return true;
6737 }
6738
6739 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006740}
6741
6742bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006743 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6744 ComplexValue CV;
6745 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6746 return false;
6747 Result = CV.FloatImag;
6748 return true;
6749 }
6750
Richard Smith4a678122011-10-24 18:44:57 +00006751 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006752 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6753 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006754 return true;
6755}
6756
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006757bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006758 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006759 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006760 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006761 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006762 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006763 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6764 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006765 Result.changeSign();
6766 return true;
6767 }
6768}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006769
Eli Friedman24c01542008-08-22 00:06:13 +00006770bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006771 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6772 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006773
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006774 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006775 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6776 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006777 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006778 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
6779 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00006780}
6781
6782bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6783 Result = E->getValue();
6784 return true;
6785}
6786
Peter Collingbournee9200682011-05-13 03:29:01 +00006787bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6788 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006789
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006790 switch (E->getCastKind()) {
6791 default:
Richard Smith11562c52011-10-28 17:51:58 +00006792 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006793
6794 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006795 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006796 return EvaluateInteger(SubExpr, IntResult, Info) &&
6797 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6798 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006799 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006800
6801 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006802 if (!Visit(SubExpr))
6803 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006804 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6805 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006806 }
John McCalld7646252010-11-14 08:17:51 +00006807
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006808 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006809 ComplexValue V;
6810 if (!EvaluateComplex(SubExpr, V, Info))
6811 return false;
6812 Result = V.getComplexFloatReal();
6813 return true;
6814 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006815 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006816}
6817
Eli Friedman24c01542008-08-22 00:06:13 +00006818//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006819// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006820//===----------------------------------------------------------------------===//
6821
6822namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006823class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006824 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006825 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006826
Anders Carlsson537969c2008-11-16 20:27:53 +00006827public:
John McCall93d91dc2010-05-07 17:22:02 +00006828 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006829 : ExprEvaluatorBaseTy(info), Result(Result) {}
6830
Richard Smith2e312c82012-03-03 22:46:17 +00006831 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006832 Result.setFrom(V);
6833 return true;
6834 }
Mike Stump11289f42009-09-09 15:08:12 +00006835
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006836 bool ZeroInitialization(const Expr *E);
6837
Anders Carlsson537969c2008-11-16 20:27:53 +00006838 //===--------------------------------------------------------------------===//
6839 // Visitor Methods
6840 //===--------------------------------------------------------------------===//
6841
Peter Collingbournee9200682011-05-13 03:29:01 +00006842 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006843 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006844 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006845 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006846 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006847};
6848} // end anonymous namespace
6849
John McCall93d91dc2010-05-07 17:22:02 +00006850static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6851 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006852 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006853 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006854}
6855
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006856bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006857 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006858 if (ElemTy->isRealFloatingType()) {
6859 Result.makeComplexFloat();
6860 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6861 Result.FloatReal = Zero;
6862 Result.FloatImag = Zero;
6863 } else {
6864 Result.makeComplexInt();
6865 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6866 Result.IntReal = Zero;
6867 Result.IntImag = Zero;
6868 }
6869 return true;
6870}
6871
Peter Collingbournee9200682011-05-13 03:29:01 +00006872bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6873 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006874
6875 if (SubExpr->getType()->isRealFloatingType()) {
6876 Result.makeComplexFloat();
6877 APFloat &Imag = Result.FloatImag;
6878 if (!EvaluateFloat(SubExpr, Imag, Info))
6879 return false;
6880
6881 Result.FloatReal = APFloat(Imag.getSemantics());
6882 return true;
6883 } else {
6884 assert(SubExpr->getType()->isIntegerType() &&
6885 "Unexpected imaginary literal.");
6886
6887 Result.makeComplexInt();
6888 APSInt &Imag = Result.IntImag;
6889 if (!EvaluateInteger(SubExpr, Imag, Info))
6890 return false;
6891
6892 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6893 return true;
6894 }
6895}
6896
Peter Collingbournee9200682011-05-13 03:29:01 +00006897bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006898
John McCallfcef3cf2010-12-14 17:51:41 +00006899 switch (E->getCastKind()) {
6900 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006901 case CK_BaseToDerived:
6902 case CK_DerivedToBase:
6903 case CK_UncheckedDerivedToBase:
6904 case CK_Dynamic:
6905 case CK_ToUnion:
6906 case CK_ArrayToPointerDecay:
6907 case CK_FunctionToPointerDecay:
6908 case CK_NullToPointer:
6909 case CK_NullToMemberPointer:
6910 case CK_BaseToDerivedMemberPointer:
6911 case CK_DerivedToBaseMemberPointer:
6912 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006913 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006914 case CK_ConstructorConversion:
6915 case CK_IntegralToPointer:
6916 case CK_PointerToIntegral:
6917 case CK_PointerToBoolean:
6918 case CK_ToVoid:
6919 case CK_VectorSplat:
6920 case CK_IntegralCast:
6921 case CK_IntegralToBoolean:
6922 case CK_IntegralToFloating:
6923 case CK_FloatingToIntegral:
6924 case CK_FloatingToBoolean:
6925 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006926 case CK_CPointerToObjCPointerCast:
6927 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006928 case CK_AnyPointerToBlockPointerCast:
6929 case CK_ObjCObjectLValueCast:
6930 case CK_FloatingComplexToReal:
6931 case CK_FloatingComplexToBoolean:
6932 case CK_IntegralComplexToReal:
6933 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006934 case CK_ARCProduceObject:
6935 case CK_ARCConsumeObject:
6936 case CK_ARCReclaimReturnedObject:
6937 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006938 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006939 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006940 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006941 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006942
John McCallfcef3cf2010-12-14 17:51:41 +00006943 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006944 case CK_AtomicToNonAtomic:
6945 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006946 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006947 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006948
6949 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006950 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006951 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006952 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006953
6954 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006955 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006956 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006957 return false;
6958
John McCallfcef3cf2010-12-14 17:51:41 +00006959 Result.makeComplexFloat();
6960 Result.FloatImag = APFloat(Real.getSemantics());
6961 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006962 }
6963
John McCallfcef3cf2010-12-14 17:51:41 +00006964 case CK_FloatingComplexCast: {
6965 if (!Visit(E->getSubExpr()))
6966 return false;
6967
6968 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6969 QualType From
6970 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6971
Richard Smith357362d2011-12-13 06:39:58 +00006972 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6973 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006974 }
6975
6976 case CK_FloatingComplexToIntegralComplex: {
6977 if (!Visit(E->getSubExpr()))
6978 return false;
6979
6980 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6981 QualType From
6982 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6983 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006984 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6985 To, Result.IntReal) &&
6986 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6987 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006988 }
6989
6990 case CK_IntegralRealToComplex: {
6991 APSInt &Real = Result.IntReal;
6992 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6993 return false;
6994
6995 Result.makeComplexInt();
6996 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6997 return true;
6998 }
6999
7000 case CK_IntegralComplexCast: {
7001 if (!Visit(E->getSubExpr()))
7002 return false;
7003
7004 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7005 QualType From
7006 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7007
Richard Smith911e1422012-01-30 22:27:01 +00007008 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7009 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007010 return true;
7011 }
7012
7013 case CK_IntegralComplexToFloatingComplex: {
7014 if (!Visit(E->getSubExpr()))
7015 return false;
7016
Ted Kremenek28831752012-08-23 20:46:57 +00007017 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007018 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007019 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007020 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007021 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7022 To, Result.FloatReal) &&
7023 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7024 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007025 }
7026 }
7027
7028 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007029}
7030
John McCall93d91dc2010-05-07 17:22:02 +00007031bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007032 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007033 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7034
Richard Smith253c2a32012-01-27 01:14:48 +00007035 bool LHSOK = Visit(E->getLHS());
7036 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007037 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007038
John McCall93d91dc2010-05-07 17:22:02 +00007039 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007040 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007041 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007042
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007043 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7044 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007045 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007046 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007047 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007048 if (Result.isComplexFloat()) {
7049 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7050 APFloat::rmNearestTiesToEven);
7051 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7052 APFloat::rmNearestTiesToEven);
7053 } else {
7054 Result.getComplexIntReal() += RHS.getComplexIntReal();
7055 Result.getComplexIntImag() += RHS.getComplexIntImag();
7056 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007057 break;
John McCalle3027922010-08-25 11:45:40 +00007058 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007059 if (Result.isComplexFloat()) {
7060 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7061 APFloat::rmNearestTiesToEven);
7062 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7063 APFloat::rmNearestTiesToEven);
7064 } else {
7065 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7066 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7067 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007068 break;
John McCalle3027922010-08-25 11:45:40 +00007069 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007070 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007071 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007072 APFloat &LHS_r = LHS.getComplexFloatReal();
7073 APFloat &LHS_i = LHS.getComplexFloatImag();
7074 APFloat &RHS_r = RHS.getComplexFloatReal();
7075 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007076
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007077 APFloat Tmp = LHS_r;
7078 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7079 Result.getComplexFloatReal() = Tmp;
7080 Tmp = LHS_i;
7081 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7082 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7083
7084 Tmp = LHS_r;
7085 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7086 Result.getComplexFloatImag() = Tmp;
7087 Tmp = LHS_i;
7088 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7089 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7090 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007091 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007092 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007093 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7094 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007095 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007096 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7097 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7098 }
7099 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007100 case BO_Div:
7101 if (Result.isComplexFloat()) {
7102 ComplexValue LHS = Result;
7103 APFloat &LHS_r = LHS.getComplexFloatReal();
7104 APFloat &LHS_i = LHS.getComplexFloatImag();
7105 APFloat &RHS_r = RHS.getComplexFloatReal();
7106 APFloat &RHS_i = RHS.getComplexFloatImag();
7107 APFloat &Res_r = Result.getComplexFloatReal();
7108 APFloat &Res_i = Result.getComplexFloatImag();
7109
7110 APFloat Den = RHS_r;
7111 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7112 APFloat Tmp = RHS_i;
7113 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7114 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7115
7116 Res_r = LHS_r;
7117 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7118 Tmp = LHS_i;
7119 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7120 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7121 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7122
7123 Res_i = LHS_i;
7124 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7125 Tmp = LHS_r;
7126 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7127 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7128 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7129 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007130 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7131 return Error(E, diag::note_expr_divide_by_zero);
7132
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007133 ComplexValue LHS = Result;
7134 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7135 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7136 Result.getComplexIntReal() =
7137 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7138 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7139 Result.getComplexIntImag() =
7140 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7141 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7142 }
7143 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007144 }
7145
John McCall93d91dc2010-05-07 17:22:02 +00007146 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007147}
7148
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007149bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7150 // Get the operand value into 'Result'.
7151 if (!Visit(E->getSubExpr()))
7152 return false;
7153
7154 switch (E->getOpcode()) {
7155 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007156 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007157 case UO_Extension:
7158 return true;
7159 case UO_Plus:
7160 // The result is always just the subexpr.
7161 return true;
7162 case UO_Minus:
7163 if (Result.isComplexFloat()) {
7164 Result.getComplexFloatReal().changeSign();
7165 Result.getComplexFloatImag().changeSign();
7166 }
7167 else {
7168 Result.getComplexIntReal() = -Result.getComplexIntReal();
7169 Result.getComplexIntImag() = -Result.getComplexIntImag();
7170 }
7171 return true;
7172 case UO_Not:
7173 if (Result.isComplexFloat())
7174 Result.getComplexFloatImag().changeSign();
7175 else
7176 Result.getComplexIntImag() = -Result.getComplexIntImag();
7177 return true;
7178 }
7179}
7180
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007181bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7182 if (E->getNumInits() == 2) {
7183 if (E->getType()->isComplexType()) {
7184 Result.makeComplexFloat();
7185 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7186 return false;
7187 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7188 return false;
7189 } else {
7190 Result.makeComplexInt();
7191 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7192 return false;
7193 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7194 return false;
7195 }
7196 return true;
7197 }
7198 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7199}
7200
Anders Carlsson537969c2008-11-16 20:27:53 +00007201//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007202// Void expression evaluation, primarily for a cast to void on the LHS of a
7203// comma operator
7204//===----------------------------------------------------------------------===//
7205
7206namespace {
7207class VoidExprEvaluator
7208 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7209public:
7210 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7211
Richard Smith2e312c82012-03-03 22:46:17 +00007212 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007213
7214 bool VisitCastExpr(const CastExpr *E) {
7215 switch (E->getCastKind()) {
7216 default:
7217 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7218 case CK_ToVoid:
7219 VisitIgnoredValue(E->getSubExpr());
7220 return true;
7221 }
7222 }
7223};
7224} // end anonymous namespace
7225
7226static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7227 assert(E->isRValue() && E->getType()->isVoidType());
7228 return VoidExprEvaluator(Info).Visit(E);
7229}
7230
7231//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007232// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007233//===----------------------------------------------------------------------===//
7234
Richard Smith2e312c82012-03-03 22:46:17 +00007235static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007236 // In C, function designators are not lvalues, but we evaluate them as if they
7237 // are.
7238 if (E->isGLValue() || E->getType()->isFunctionType()) {
7239 LValue LV;
7240 if (!EvaluateLValue(E, LV, Info))
7241 return false;
7242 LV.moveInto(Result);
7243 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007244 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007245 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007246 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007247 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007248 return false;
John McCall45d55e42010-05-07 21:00:08 +00007249 } else if (E->getType()->hasPointerRepresentation()) {
7250 LValue LV;
7251 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007252 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007253 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00007254 } else if (E->getType()->isRealFloatingType()) {
7255 llvm::APFloat F(0.0);
7256 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007257 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007258 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00007259 } else if (E->getType()->isAnyComplexType()) {
7260 ComplexValue C;
7261 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007262 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007263 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00007264 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007265 MemberPtr P;
7266 if (!EvaluateMemberPointer(E, P, Info))
7267 return false;
7268 P.moveInto(Result);
7269 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00007270 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007271 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007272 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007273 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007274 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007275 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00007276 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007277 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007278 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007279 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7280 return false;
7281 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00007282 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007283 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007284 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007285 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007286 if (!EvaluateVoid(E, Info))
7287 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007288 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007289 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007290 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007291 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007292 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007293 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007294 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007295
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007296 return true;
7297}
7298
Richard Smithb228a862012-02-15 02:18:13 +00007299/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7300/// cases, the in-place evaluation is essential, since later initializers for
7301/// an object can indirectly refer to subobjects which were initialized earlier.
7302static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007303 const Expr *E, bool AllowNonLiteralTypes) {
7304 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007305 return false;
7306
7307 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007308 // Evaluate arrays and record types in-place, so that later initializers can
7309 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007310 if (E->getType()->isArrayType())
7311 return EvaluateArray(E, This, Result, Info);
7312 else if (E->getType()->isRecordType())
7313 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007314 }
7315
7316 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007317 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007318}
7319
Richard Smithf57d8cb2011-12-09 22:58:01 +00007320/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7321/// lvalue-to-rvalue cast if it is an lvalue.
7322static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007323 if (!CheckLiteralType(Info, E))
7324 return false;
7325
Richard Smith2e312c82012-03-03 22:46:17 +00007326 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007327 return false;
7328
7329 if (E->isGLValue()) {
7330 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007331 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007332 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007333 return false;
7334 }
7335
Richard Smith2e312c82012-03-03 22:46:17 +00007336 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007337 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007338}
Richard Smith11562c52011-10-28 17:51:58 +00007339
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007340static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7341 const ASTContext &Ctx, bool &IsConst) {
7342 // Fast-path evaluations of integer literals, since we sometimes see files
7343 // containing vast quantities of these.
7344 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7345 Result.Val = APValue(APSInt(L->getValue(),
7346 L->getType()->isUnsignedIntegerType()));
7347 IsConst = true;
7348 return true;
7349 }
7350
7351 // FIXME: Evaluating values of large array and record types can cause
7352 // performance problems. Only do so in C++11 for now.
7353 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7354 Exp->getType()->isRecordType()) &&
7355 !Ctx.getLangOpts().CPlusPlus11) {
7356 IsConst = false;
7357 return true;
7358 }
7359 return false;
7360}
7361
7362
Richard Smith7b553f12011-10-29 00:50:52 +00007363/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007364/// any crazy technique (that has nothing to do with language standards) that
7365/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007366/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7367/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007368bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007369 bool IsConst;
7370 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7371 return IsConst;
7372
Richard Smithf57d8cb2011-12-09 22:58:01 +00007373 EvalInfo Info(Ctx, Result);
7374 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007375}
7376
Jay Foad39c79802011-01-12 09:06:06 +00007377bool Expr::EvaluateAsBooleanCondition(bool &Result,
7378 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007379 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007380 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007381 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007382}
7383
Richard Smith5fab0c92011-12-28 19:48:30 +00007384bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7385 SideEffectsKind AllowSideEffects) const {
7386 if (!getType()->isIntegralOrEnumerationType())
7387 return false;
7388
Richard Smith11562c52011-10-28 17:51:58 +00007389 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007390 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7391 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007392 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007393
Richard Smith11562c52011-10-28 17:51:58 +00007394 Result = ExprResult.Val.getInt();
7395 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007396}
7397
Jay Foad39c79802011-01-12 09:06:06 +00007398bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007399 EvalInfo Info(Ctx, Result);
7400
John McCall45d55e42010-05-07 21:00:08 +00007401 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007402 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7403 !CheckLValueConstantExpression(Info, getExprLoc(),
7404 Ctx.getLValueReferenceType(getType()), LV))
7405 return false;
7406
Richard Smith2e312c82012-03-03 22:46:17 +00007407 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007408 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007409}
7410
Richard Smithd0b4dd62011-12-19 06:19:21 +00007411bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7412 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007413 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007414 // FIXME: Evaluating initializers for large array and record types can cause
7415 // performance problems. Only do so in C++11 for now.
7416 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007417 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007418 return false;
7419
Richard Smithd0b4dd62011-12-19 06:19:21 +00007420 Expr::EvalStatus EStatus;
7421 EStatus.Diag = &Notes;
7422
7423 EvalInfo InitInfo(Ctx, EStatus);
7424 InitInfo.setEvaluatingDecl(VD, Value);
7425
7426 LValue LVal;
7427 LVal.set(VD);
7428
Richard Smithfddd3842011-12-30 21:15:51 +00007429 // C++11 [basic.start.init]p2:
7430 // Variables with static storage duration or thread storage duration shall be
7431 // zero-initialized before any other initialization takes place.
7432 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007433 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007434 !VD->getType()->isReferenceType()) {
7435 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007436 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007437 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007438 return false;
7439 }
7440
Richard Smith7525ff62013-05-09 07:14:00 +00007441 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7442 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007443 EStatus.HasSideEffects)
7444 return false;
7445
7446 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7447 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007448}
7449
Richard Smith7b553f12011-10-29 00:50:52 +00007450/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7451/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007452bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007453 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007454 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007455}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007456
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007457APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007458 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007459 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007460 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007461 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007462 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007463 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007464 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007465
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007466 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007467}
John McCall864e3962010-05-07 05:32:02 +00007468
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007469void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7470 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7471 bool IsConst;
7472 EvalResult EvalResult;
7473 EvalResult.Diag = Diags;
7474 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7475 EvalInfo Info(Ctx, EvalResult, true);
7476 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7477 }
7478}
7479
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007480 bool Expr::EvalResult::isGlobalLValue() const {
7481 assert(Val.isLValue());
7482 return IsGlobalLValue(Val.getLValueBase());
7483 }
7484
7485
John McCall864e3962010-05-07 05:32:02 +00007486/// isIntegerConstantExpr - this recursive routine will test if an expression is
7487/// an integer constant expression.
7488
7489/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7490/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007491
7492// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007493// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7494// and a (possibly null) SourceLocation indicating the location of the problem.
7495//
John McCall864e3962010-05-07 05:32:02 +00007496// Note that to reduce code duplication, this helper does no evaluation
7497// itself; the caller checks whether the expression is evaluatable, and
7498// in the rare cases where CheckICE actually cares about the evaluated
7499// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007500
Dan Gohman28ade552010-07-26 21:25:24 +00007501namespace {
7502
Richard Smith9e575da2012-12-28 13:25:52 +00007503enum ICEKind {
7504 /// This expression is an ICE.
7505 IK_ICE,
7506 /// This expression is not an ICE, but if it isn't evaluated, it's
7507 /// a legal subexpression for an ICE. This return value is used to handle
7508 /// the comma operator in C99 mode, and non-constant subexpressions.
7509 IK_ICEIfUnevaluated,
7510 /// This expression is not an ICE, and is not a legal subexpression for one.
7511 IK_NotICE
7512};
7513
John McCall864e3962010-05-07 05:32:02 +00007514struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007515 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007516 SourceLocation Loc;
7517
Richard Smith9e575da2012-12-28 13:25:52 +00007518 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007519};
7520
Dan Gohman28ade552010-07-26 21:25:24 +00007521}
7522
Richard Smith9e575da2012-12-28 13:25:52 +00007523static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7524
7525static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007526
7527static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7528 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007529 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007530 !EVResult.Val.isInt())
7531 return ICEDiag(IK_NotICE, E->getLocStart());
7532
John McCall864e3962010-05-07 05:32:02 +00007533 return NoDiag();
7534}
7535
7536static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7537 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007538 if (!E->getType()->isIntegralOrEnumerationType())
7539 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007540
7541 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007542#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007543#define STMT(Node, Base) case Expr::Node##Class:
7544#define EXPR(Node, Base)
7545#include "clang/AST/StmtNodes.inc"
7546 case Expr::PredefinedExprClass:
7547 case Expr::FloatingLiteralClass:
7548 case Expr::ImaginaryLiteralClass:
7549 case Expr::StringLiteralClass:
7550 case Expr::ArraySubscriptExprClass:
7551 case Expr::MemberExprClass:
7552 case Expr::CompoundAssignOperatorClass:
7553 case Expr::CompoundLiteralExprClass:
7554 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007555 case Expr::DesignatedInitExprClass:
7556 case Expr::ImplicitValueInitExprClass:
7557 case Expr::ParenListExprClass:
7558 case Expr::VAArgExprClass:
7559 case Expr::AddrLabelExprClass:
7560 case Expr::StmtExprClass:
7561 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007562 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007563 case Expr::CXXDynamicCastExprClass:
7564 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007565 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007566 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007567 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007568 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007569 case Expr::CXXThisExprClass:
7570 case Expr::CXXThrowExprClass:
7571 case Expr::CXXNewExprClass:
7572 case Expr::CXXDeleteExprClass:
7573 case Expr::CXXPseudoDestructorExprClass:
7574 case Expr::UnresolvedLookupExprClass:
7575 case Expr::DependentScopeDeclRefExprClass:
7576 case Expr::CXXConstructExprClass:
7577 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007578 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007579 case Expr::CXXTemporaryObjectExprClass:
7580 case Expr::CXXUnresolvedConstructExprClass:
7581 case Expr::CXXDependentScopeMemberExprClass:
7582 case Expr::UnresolvedMemberExprClass:
7583 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007584 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007585 case Expr::ObjCArrayLiteralClass:
7586 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007587 case Expr::ObjCEncodeExprClass:
7588 case Expr::ObjCMessageExprClass:
7589 case Expr::ObjCSelectorExprClass:
7590 case Expr::ObjCProtocolExprClass:
7591 case Expr::ObjCIvarRefExprClass:
7592 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007593 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007594 case Expr::ObjCIsaExprClass:
7595 case Expr::ShuffleVectorExprClass:
7596 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007597 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007598 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007599 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007600 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007601 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007602 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007603 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007604 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007605 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007606 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007607 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007608 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007609 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007610
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007611 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007612 case Expr::GNUNullExprClass:
7613 // GCC considers the GNU __null value to be an integral constant expression.
7614 return NoDiag();
7615
John McCall7c454bb2011-07-15 05:09:51 +00007616 case Expr::SubstNonTypeTemplateParmExprClass:
7617 return
7618 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7619
John McCall864e3962010-05-07 05:32:02 +00007620 case Expr::ParenExprClass:
7621 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007622 case Expr::GenericSelectionExprClass:
7623 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007624 case Expr::IntegerLiteralClass:
7625 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007626 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007627 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007628 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007629 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007630 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007631 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007632 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007633 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007634 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007635 return NoDiag();
7636 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007637 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007638 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7639 // constant expressions, but they can never be ICEs because an ICE cannot
7640 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007641 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007642 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007643 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007644 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007645 }
Richard Smith6365c912012-02-24 22:12:32 +00007646 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007647 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7648 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007649 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007650 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007651 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007652 // Parameter variables are never constants. Without this check,
7653 // getAnyInitializer() can find a default argument, which leads
7654 // to chaos.
7655 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007656 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007657
7658 // C++ 7.1.5.1p2
7659 // A variable of non-volatile const-qualified integral or enumeration
7660 // type initialized by an ICE can be used in ICEs.
7661 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007662 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007663 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007664
Richard Smithd0b4dd62011-12-19 06:19:21 +00007665 const VarDecl *VD;
7666 // Look for a declaration of this variable that has an initializer, and
7667 // check whether it is an ICE.
7668 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7669 return NoDiag();
7670 else
Richard Smith9e575da2012-12-28 13:25:52 +00007671 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007672 }
7673 }
Richard Smith9e575da2012-12-28 13:25:52 +00007674 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007675 }
John McCall864e3962010-05-07 05:32:02 +00007676 case Expr::UnaryOperatorClass: {
7677 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7678 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007679 case UO_PostInc:
7680 case UO_PostDec:
7681 case UO_PreInc:
7682 case UO_PreDec:
7683 case UO_AddrOf:
7684 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007685 // C99 6.6/3 allows increment and decrement within unevaluated
7686 // subexpressions of constant expressions, but they can never be ICEs
7687 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007688 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007689 case UO_Extension:
7690 case UO_LNot:
7691 case UO_Plus:
7692 case UO_Minus:
7693 case UO_Not:
7694 case UO_Real:
7695 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007696 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007697 }
Richard Smith9e575da2012-12-28 13:25:52 +00007698
John McCall864e3962010-05-07 05:32:02 +00007699 // OffsetOf falls through here.
7700 }
7701 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007702 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7703 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7704 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7705 // compliance: we should warn earlier for offsetof expressions with
7706 // array subscripts that aren't ICEs, and if the array subscripts
7707 // are ICEs, the value of the offsetof must be an integer constant.
7708 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007709 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007710 case Expr::UnaryExprOrTypeTraitExprClass: {
7711 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7712 if ((Exp->getKind() == UETT_SizeOf) &&
7713 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007714 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007715 return NoDiag();
7716 }
7717 case Expr::BinaryOperatorClass: {
7718 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7719 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007720 case BO_PtrMemD:
7721 case BO_PtrMemI:
7722 case BO_Assign:
7723 case BO_MulAssign:
7724 case BO_DivAssign:
7725 case BO_RemAssign:
7726 case BO_AddAssign:
7727 case BO_SubAssign:
7728 case BO_ShlAssign:
7729 case BO_ShrAssign:
7730 case BO_AndAssign:
7731 case BO_XorAssign:
7732 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007733 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7734 // constant expressions, but they can never be ICEs because an ICE cannot
7735 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007736 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007737
John McCalle3027922010-08-25 11:45:40 +00007738 case BO_Mul:
7739 case BO_Div:
7740 case BO_Rem:
7741 case BO_Add:
7742 case BO_Sub:
7743 case BO_Shl:
7744 case BO_Shr:
7745 case BO_LT:
7746 case BO_GT:
7747 case BO_LE:
7748 case BO_GE:
7749 case BO_EQ:
7750 case BO_NE:
7751 case BO_And:
7752 case BO_Xor:
7753 case BO_Or:
7754 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007755 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7756 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007757 if (Exp->getOpcode() == BO_Div ||
7758 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007759 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007760 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007761 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007762 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007763 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007764 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007765 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007766 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007767 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007768 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007769 }
7770 }
7771 }
John McCalle3027922010-08-25 11:45:40 +00007772 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007773 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007774 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7775 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007776 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7777 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007778 } else {
7779 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007780 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007781 }
7782 }
Richard Smith9e575da2012-12-28 13:25:52 +00007783 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007784 }
John McCalle3027922010-08-25 11:45:40 +00007785 case BO_LAnd:
7786 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007787 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7788 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007789 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007790 // Rare case where the RHS has a comma "side-effect"; we need
7791 // to actually check the condition to see whether the side
7792 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007793 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007794 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007795 return RHSResult;
7796 return NoDiag();
7797 }
7798
Richard Smith9e575da2012-12-28 13:25:52 +00007799 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007800 }
7801 }
7802 }
7803 case Expr::ImplicitCastExprClass:
7804 case Expr::CStyleCastExprClass:
7805 case Expr::CXXFunctionalCastExprClass:
7806 case Expr::CXXStaticCastExprClass:
7807 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007808 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007809 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007810 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007811 if (isa<ExplicitCastExpr>(E)) {
7812 if (const FloatingLiteral *FL
7813 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7814 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7815 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7816 APSInt IgnoredVal(DestWidth, !DestSigned);
7817 bool Ignored;
7818 // If the value does not fit in the destination type, the behavior is
7819 // undefined, so we are not required to treat it as a constant
7820 // expression.
7821 if (FL->getValue().convertToInteger(IgnoredVal,
7822 llvm::APFloat::rmTowardZero,
7823 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007824 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007825 return NoDiag();
7826 }
7827 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007828 switch (cast<CastExpr>(E)->getCastKind()) {
7829 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007830 case CK_AtomicToNonAtomic:
7831 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007832 case CK_NoOp:
7833 case CK_IntegralToBoolean:
7834 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007835 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007836 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007837 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007838 }
John McCall864e3962010-05-07 05:32:02 +00007839 }
John McCallc07a0c72011-02-17 10:25:35 +00007840 case Expr::BinaryConditionalOperatorClass: {
7841 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7842 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007843 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007844 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007845 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7846 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7847 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007848 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007849 return FalseResult;
7850 }
John McCall864e3962010-05-07 05:32:02 +00007851 case Expr::ConditionalOperatorClass: {
7852 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7853 // If the condition (ignoring parens) is a __builtin_constant_p call,
7854 // then only the true side is actually considered in an integer constant
7855 // expression, and it is fully evaluated. This is an important GNU
7856 // extension. See GCC PR38377 for discussion.
7857 if (const CallExpr *CallCE
7858 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007859 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7860 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007861 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007862 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007863 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007864
Richard Smithf57d8cb2011-12-09 22:58:01 +00007865 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7866 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007867
Richard Smith9e575da2012-12-28 13:25:52 +00007868 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007869 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007870 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007871 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007872 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007873 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007874 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007875 return NoDiag();
7876 // Rare case where the diagnostics depend on which side is evaluated
7877 // Note that if we get here, CondResult is 0, and at least one of
7878 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007879 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007880 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007881 return TrueResult;
7882 }
7883 case Expr::CXXDefaultArgExprClass:
7884 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007885 case Expr::CXXDefaultInitExprClass:
7886 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007887 case Expr::ChooseExprClass: {
7888 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7889 }
7890 }
7891
David Blaikiee4d798f2012-01-20 21:50:17 +00007892 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007893}
7894
Richard Smithf57d8cb2011-12-09 22:58:01 +00007895/// Evaluate an expression as a C++11 integral constant expression.
7896static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7897 const Expr *E,
7898 llvm::APSInt *Value,
7899 SourceLocation *Loc) {
7900 if (!E->getType()->isIntegralOrEnumerationType()) {
7901 if (Loc) *Loc = E->getExprLoc();
7902 return false;
7903 }
7904
Richard Smith66e05fe2012-01-18 05:21:49 +00007905 APValue Result;
7906 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007907 return false;
7908
Richard Smith66e05fe2012-01-18 05:21:49 +00007909 assert(Result.isInt() && "pointer cast to int is not an ICE");
7910 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007911 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007912}
7913
Richard Smith92b1ce02011-12-12 09:28:41 +00007914bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007915 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007916 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7917
Richard Smith9e575da2012-12-28 13:25:52 +00007918 ICEDiag D = CheckICE(this, Ctx);
7919 if (D.Kind != IK_ICE) {
7920 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007921 return false;
7922 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007923 return true;
7924}
7925
7926bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7927 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007928 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007929 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7930
7931 if (!isIntegerConstantExpr(Ctx, Loc))
7932 return false;
7933 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007934 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007935 return true;
7936}
Richard Smith66e05fe2012-01-18 05:21:49 +00007937
Richard Smith98a0a492012-02-14 21:38:30 +00007938bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007939 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007940}
7941
Richard Smith66e05fe2012-01-18 05:21:49 +00007942bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7943 SourceLocation *Loc) const {
7944 // We support this checking in C++98 mode in order to diagnose compatibility
7945 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007946 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007947
Richard Smith98a0a492012-02-14 21:38:30 +00007948 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007949 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007950 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007951 Status.Diag = &Diags;
7952 EvalInfo Info(Ctx, Status);
7953
7954 APValue Scratch;
7955 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7956
7957 if (!Diags.empty()) {
7958 IsConstExpr = false;
7959 if (Loc) *Loc = Diags[0].first;
7960 } else if (!IsConstExpr) {
7961 // FIXME: This shouldn't happen.
7962 if (Loc) *Loc = getExprLoc();
7963 }
7964
7965 return IsConstExpr;
7966}
Richard Smith253c2a32012-01-27 01:14:48 +00007967
7968bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007969 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007970 PartialDiagnosticAt> &Diags) {
7971 // FIXME: It would be useful to check constexpr function templates, but at the
7972 // moment the constant expression evaluator cannot cope with the non-rigorous
7973 // ASTs which we build for dependent expressions.
7974 if (FD->isDependentContext())
7975 return true;
7976
7977 Expr::EvalStatus Status;
7978 Status.Diag = &Diags;
7979
7980 EvalInfo Info(FD->getASTContext(), Status);
7981 Info.CheckingPotentialConstantExpression = true;
7982
7983 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7984 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7985
Richard Smith7525ff62013-05-09 07:14:00 +00007986 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00007987 // is a temporary being used as the 'this' pointer.
7988 LValue This;
7989 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007990 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007991
Richard Smith253c2a32012-01-27 01:14:48 +00007992 ArrayRef<const Expr*> Args;
7993
7994 SourceLocation Loc = FD->getLocation();
7995
Richard Smith2e312c82012-03-03 22:46:17 +00007996 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00007997 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
7998 // Evaluate the call as a constant initializer, to allow the construction
7999 // of objects of non-literal types.
8000 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008001 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008002 } else
Richard Smith253c2a32012-01-27 01:14:48 +00008003 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8004 Args, FD->getBody(), Info, Scratch);
8005
8006 return Diags.empty();
8007}