blob: db300c4fec4e4a8610a0816d32c01dd8a34d5ccc [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();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type) {
118 unsigned MostDerivedLength = 0;
119 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000121 if (Type->isArrayType()) {
122 const ConstantArrayType *CAT =
123 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124 Type = CAT->getElementType();
125 ArraySize = CAT->getSize().getZExtValue();
126 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000127 } else if (Type->isAnyComplexType()) {
128 const ComplexType *CT = Type->castAs<ComplexType>();
129 Type = CT->getElementType();
130 ArraySize = 2;
131 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000132 } else if (const FieldDecl *FD = getAsField(Path[I])) {
133 Type = FD->getType();
134 ArraySize = 0;
135 MostDerivedLength = I + 1;
136 } else {
Richard Smith80815602011-11-07 05:07:52 +0000137 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000138 ArraySize = 0;
139 }
Richard Smith80815602011-11-07 05:07:52 +0000140 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000142 }
143
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000147 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000148 };
149
Richard Smith96e0c102011-11-04 02:25:55 +0000150 /// A path from a glvalue to a subobject of that glvalue.
151 struct SubobjectDesignator {
152 /// True if the subobject was named in a manner not supported by C++11. Such
153 /// lvalues can still be folded, but they are not core constant expressions
154 /// and we cannot perform lvalue-to-rvalue conversions on them.
155 bool Invalid : 1;
156
Richard Smitha8105bc2012-01-06 16:39:00 +0000157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 /// The length of the path to the most-derived object of which this is a
161 /// subobject.
162 unsigned MostDerivedPathLength : 30;
163
164 /// The size of the array of which the most-derived object is an element, or
165 /// 0 if the most-derived object is not an array element.
166 uint64_t MostDerivedArraySize;
167
168 /// The type of the most derived object referred to by this address.
169 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000170
Richard Smith80815602011-11-07 05:07:52 +0000171 typedef APValue::LValuePathEntry PathEntry;
172
Richard Smith96e0c102011-11-04 02:25:55 +0000173 /// The entries on the path from the glvalue to the designated subobject.
174 SmallVector<PathEntry, 8> Entries;
175
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000177
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 explicit SubobjectDesignator(QualType T)
179 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180 MostDerivedArraySize(0), MostDerivedType(T) {}
181
182 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000185 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000187 ArrayRef<PathEntry> VEntries = V.getLValuePath();
188 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
193 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000194 }
195 }
196
Richard Smith96e0c102011-11-04 02:25:55 +0000197 void setInvalid() {
198 Invalid = true;
199 Entries.clear();
200 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000201
202 /// Determine whether this is a one-past-the-end pointer.
203 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000204 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000205 if (IsOnePastTheEnd)
206 return true;
207 if (MostDerivedArraySize &&
208 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
209 return true;
210 return false;
211 }
212
213 /// Check that this refers to a valid subobject.
214 bool isValidSubobject() const {
215 if (Invalid)
216 return false;
217 return !isOnePastTheEnd();
218 }
219 /// Check that this refers to a valid subobject, and if not, produce a
220 /// relevant diagnostic and set the designator as invalid.
221 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
222
223 /// Update this designator to refer to the first element within this array.
224 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000225 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000227 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000228
229 // This is a most-derived object.
230 MostDerivedType = CAT->getElementType();
231 MostDerivedArraySize = CAT->getSize().getZExtValue();
232 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000233 }
234 /// Update this designator to refer to the given base or member of this
235 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000236 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000237 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000238 APValue::BaseOrMemberType Value(D, Virtual);
239 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000240 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000241
242 // If this isn't a base class, it's a new most-derived object.
243 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
244 MostDerivedType = FD->getType();
245 MostDerivedArraySize = 0;
246 MostDerivedPathLength = Entries.size();
247 }
Richard Smith96e0c102011-11-04 02:25:55 +0000248 }
Richard Smith66c96992012-02-18 22:04:06 +0000249 /// Update this designator to refer to the given complex component.
250 void addComplexUnchecked(QualType EltTy, bool Imag) {
251 PathEntry Entry;
252 Entry.ArrayIndex = Imag;
253 Entries.push_back(Entry);
254
255 // This is technically a most-derived object, though in practice this
256 // is unlikely to matter.
257 MostDerivedType = EltTy;
258 MostDerivedArraySize = 2;
259 MostDerivedPathLength = Entries.size();
260 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000261 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000262 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000264 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000266 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000267 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
268 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
269 setInvalid();
270 }
Richard Smith96e0c102011-11-04 02:25:55 +0000271 return;
272 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000273 // [expr.add]p4: For the purposes of these operators, a pointer to a
274 // nonarray object behaves the same as a pointer to the first element of
275 // an array of length one with the type of the object as its element type.
276 if (IsOnePastTheEnd && N == (uint64_t)-1)
277 IsOnePastTheEnd = false;
278 else if (!IsOnePastTheEnd && N == 1)
279 IsOnePastTheEnd = true;
280 else if (N != 0) {
281 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000282 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000283 }
Richard Smith96e0c102011-11-04 02:25:55 +0000284 }
285 };
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// A stack frame in the constexpr call stack.
288 struct CallStackFrame {
289 EvalInfo &Info;
290
291 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000292 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000293
Richard Smithf6f003a2011-12-16 19:06:07 +0000294 /// CallLoc - The location of the call expression for this call.
295 SourceLocation CallLoc;
296
297 /// Callee - The function which was called.
298 const FunctionDecl *Callee;
299
Richard Smithb228a862012-02-15 02:18:13 +0000300 /// Index - The call index of this call.
301 unsigned Index;
302
Richard Smithd62306a2011-11-10 06:34:14 +0000303 /// This - The binding for the this pointer in this call, if any.
304 const LValue *This;
305
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000306 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000307 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000308 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000309
Eli Friedman4830ec82012-06-25 21:21:08 +0000310 // Note that we intentionally use std::map here so that references to
311 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000312 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000313 typedef MapTy::const_iterator temp_iterator;
314 /// Temporaries - Temporary lvalues materialized within this stack frame.
315 MapTy Temporaries;
316
Richard Smithf6f003a2011-12-16 19:06:07 +0000317 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
318 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000319 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000320 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000321
322 APValue *getTemporary(const void *Key) {
323 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000324 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000325 }
326 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000327 };
328
Richard Smith852c9db2013-04-20 22:23:05 +0000329 /// Temporarily override 'this'.
330 class ThisOverrideRAII {
331 public:
332 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
333 : Frame(Frame), OldThis(Frame.This) {
334 if (Enable)
335 Frame.This = NewThis;
336 }
337 ~ThisOverrideRAII() {
338 Frame.This = OldThis;
339 }
340 private:
341 CallStackFrame &Frame;
342 const LValue *OldThis;
343 };
344
Richard Smith92b1ce02011-12-12 09:28:41 +0000345 /// A partial diagnostic which we might know in advance that we are not going
346 /// to emit.
347 class OptionalDiagnostic {
348 PartialDiagnostic *Diag;
349
350 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000351 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
352 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000353
354 template<typename T>
355 OptionalDiagnostic &operator<<(const T &v) {
356 if (Diag)
357 *Diag << v;
358 return *this;
359 }
Richard Smithfe800032012-01-31 04:08:20 +0000360
361 OptionalDiagnostic &operator<<(const APSInt &I) {
362 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000363 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000364 I.toString(Buffer);
365 *Diag << StringRef(Buffer.data(), Buffer.size());
366 }
367 return *this;
368 }
369
370 OptionalDiagnostic &operator<<(const APFloat &F) {
371 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000372 // FIXME: Force the precision of the source value down so we don't
373 // print digits which are usually useless (we don't really care here if
374 // we truncate a digit by accident in edge cases). Ideally,
375 // APFloat::toString would automatically print the shortest
376 // representation which rounds to the correct value, but it's a bit
377 // tricky to implement.
378 unsigned precision =
379 llvm::APFloat::semanticsPrecision(F.getSemantics());
380 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000381 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000382 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000383 *Diag << StringRef(Buffer.data(), Buffer.size());
384 }
385 return *this;
386 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000387 };
388
Richard Smith08d6a2c2013-07-24 07:11:57 +0000389 /// A cleanup, and a flag indicating whether it is lifetime-extended.
390 class Cleanup {
391 llvm::PointerIntPair<APValue*, 1, bool> Value;
392
393 public:
394 Cleanup(APValue *Val, bool IsLifetimeExtended)
395 : Value(Val, IsLifetimeExtended) {}
396
397 bool isLifetimeExtended() const { return Value.getInt(); }
398 void endLifetime() {
399 *Value.getPointer() = APValue();
400 }
401 };
402
Richard Smithb228a862012-02-15 02:18:13 +0000403 /// EvalInfo - This is a private struct used by the evaluator to capture
404 /// information about a subexpression as it is folded. It retains information
405 /// about the AST context, but also maintains information about the folded
406 /// expression.
407 ///
408 /// If an expression could be evaluated, it is still possible it is not a C
409 /// "integer constant expression" or constant expression. If not, this struct
410 /// captures information about how and why not.
411 ///
412 /// One bit of information passed *into* the request for constant folding
413 /// indicates whether the subexpression is "evaluated" or not according to C
414 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
415 /// evaluate the expression regardless of what the RHS is, but C only allows
416 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000417 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000418 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000419
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000420 /// EvalStatus - Contains information about the evaluation.
421 Expr::EvalStatus &EvalStatus;
422
423 /// CurrentCall - The top of the constexpr call stack.
424 CallStackFrame *CurrentCall;
425
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000426 /// CallStackDepth - The number of calls in the call stack right now.
427 unsigned CallStackDepth;
428
Richard Smithb228a862012-02-15 02:18:13 +0000429 /// NextCallIndex - The next call index to assign.
430 unsigned NextCallIndex;
431
Richard Smitha3d3bd22013-05-08 02:12:03 +0000432 /// StepsLeft - The remaining number of evaluation steps we're permitted
433 /// to perform. This is essentially a limit for the number of statements
434 /// we will evaluate.
435 unsigned StepsLeft;
436
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000438 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 CallStackFrame BottomFrame;
440
Richard Smith08d6a2c2013-07-24 07:11:57 +0000441 /// A stack of values whose lifetimes end at the end of some surrounding
442 /// evaluation frame.
443 llvm::SmallVector<Cleanup, 16> CleanupStack;
444
Richard Smithd62306a2011-11-10 06:34:14 +0000445 /// EvaluatingDecl - This is the declaration whose initializer is being
446 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000447 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000448
449 /// EvaluatingDeclValue - This is the value being constructed for the
450 /// declaration whose initializer is being evaluated, if any.
451 APValue *EvaluatingDeclValue;
452
Richard Smith357362d2011-12-13 06:39:58 +0000453 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
454 /// notes attached to it will also be stored, otherwise they will not be.
455 bool HasActiveDiagnostic;
456
Richard Smith6d4c6582013-11-05 22:18:15 +0000457 enum EvaluationMode {
458 /// Evaluate as a constant expression. Stop if we find that the expression
459 /// is not a constant expression.
460 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000461
Richard Smith6d4c6582013-11-05 22:18:15 +0000462 /// Evaluate as a potential constant expression. Keep going if we hit a
463 /// construct that we can't evaluate yet (because we don't yet know the
464 /// value of something) but stop if we hit something that could never be
465 /// a constant expression.
466 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000467
Richard Smith6d4c6582013-11-05 22:18:15 +0000468 /// Fold the expression to a constant. Stop if we hit a side-effect that
469 /// we can't model.
470 EM_ConstantFold,
471
472 /// Evaluate the expression looking for integer overflow and similar
473 /// issues. Don't worry about side-effects, and try to visit all
474 /// subexpressions.
475 EM_EvaluateForOverflow,
476
477 /// Evaluate in any way we know how. Don't worry about side-effects that
478 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000479 EM_IgnoreSideEffects,
480
481 /// Evaluate as a constant expression. Stop if we find that the expression
482 /// is not a constant expression. Some expressions can be retried in the
483 /// optimizer if we don't constant fold them here, but in an unevaluated
484 /// context we try to fold them immediately since the optimizer never
485 /// gets a chance to look at it.
486 EM_ConstantExpressionUnevaluated,
487
488 /// Evaluate as a potential constant expression. Keep going if we hit a
489 /// construct that we can't evaluate yet (because we don't yet know the
490 /// value of something) but stop if we hit something that could never be
491 /// a constant expression. Some expressions can be retried in the
492 /// optimizer if we don't constant fold them here, but in an unevaluated
493 /// context we try to fold them immediately since the optimizer never
494 /// gets a chance to look at it.
495 EM_PotentialConstantExpressionUnevaluated
Richard Smith6d4c6582013-11-05 22:18:15 +0000496 } EvalMode;
497
498 /// Are we checking whether the expression is a potential constant
499 /// expression?
500 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000501 return EvalMode == EM_PotentialConstantExpression ||
502 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000503 }
504
505 /// Are we checking an expression for overflow?
506 // FIXME: We should check for any kind of undefined or suspicious behavior
507 // in such constructs, not just overflow.
508 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
509
510 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000511 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000512 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000513 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000514 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
515 EvaluatingDecl((const ValueDecl *)nullptr),
516 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
517 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000518
Richard Smith7525ff62013-05-09 07:14:00 +0000519 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
520 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000521 EvaluatingDeclValue = &Value;
522 }
523
David Blaikiebbafb8a2012-03-11 07:00:24 +0000524 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000525
Richard Smith357362d2011-12-13 06:39:58 +0000526 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000527 // Don't perform any constexpr calls (other than the call we're checking)
528 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000529 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000530 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000531 if (NextCallIndex == 0) {
532 // NextCallIndex has wrapped around.
533 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
534 return false;
535 }
Richard Smith357362d2011-12-13 06:39:58 +0000536 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
537 return true;
538 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
539 << getLangOpts().ConstexprCallDepth;
540 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000541 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000542
Richard Smithb228a862012-02-15 02:18:13 +0000543 CallStackFrame *getCallFrame(unsigned CallIndex) {
544 assert(CallIndex && "no call index in getCallFrame");
545 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
546 // be null in this loop.
547 CallStackFrame *Frame = CurrentCall;
548 while (Frame->Index > CallIndex)
549 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000550 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000551 }
552
Richard Smitha3d3bd22013-05-08 02:12:03 +0000553 bool nextStep(const Stmt *S) {
554 if (!StepsLeft) {
555 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
556 return false;
557 }
558 --StepsLeft;
559 return true;
560 }
561
Richard Smith357362d2011-12-13 06:39:58 +0000562 private:
563 /// Add a diagnostic to the diagnostics list.
564 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
565 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
566 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
567 return EvalStatus.Diag->back().second;
568 }
569
Richard Smithf6f003a2011-12-16 19:06:07 +0000570 /// Add notes containing a call stack to the current point of evaluation.
571 void addCallStack(unsigned Limit);
572
Richard Smith357362d2011-12-13 06:39:58 +0000573 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000574 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000575 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
576 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000577 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000578 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000579 // If we have a prior diagnostic, it will be noting that the expression
580 // isn't a constant expression. This diagnostic is more important,
581 // unless we require this evaluation to produce a constant expression.
582 //
583 // FIXME: We might want to show both diagnostics to the user in
584 // EM_ConstantFold mode.
585 if (!EvalStatus.Diag->empty()) {
586 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000587 case EM_ConstantFold:
588 case EM_IgnoreSideEffects:
589 case EM_EvaluateForOverflow:
590 if (!EvalStatus.HasSideEffects)
591 break;
592 // We've had side-effects; we want the diagnostic from them, not
593 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000594 case EM_ConstantExpression:
595 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000596 case EM_ConstantExpressionUnevaluated:
597 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000598 HasActiveDiagnostic = false;
599 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000600 }
601 }
602
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 unsigned CallStackNotes = CallStackDepth - 1;
604 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
605 if (Limit)
606 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000607 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000608 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000609
Richard Smith357362d2011-12-13 06:39:58 +0000610 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000611 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000612 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
613 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000614 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000615 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000616 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000617 }
Richard Smith357362d2011-12-13 06:39:58 +0000618 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000619 return OptionalDiagnostic();
620 }
621
Richard Smithce1ec5e2012-03-15 04:53:45 +0000622 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
623 = diag::note_invalid_subexpr_in_const_expr,
624 unsigned ExtraNotes = 0) {
625 if (EvalStatus.Diag)
626 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
627 HasActiveDiagnostic = false;
628 return OptionalDiagnostic();
629 }
630
Richard Smith92b1ce02011-12-12 09:28:41 +0000631 /// Diagnose that the evaluation does not produce a C++11 core constant
632 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000633 ///
634 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
635 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000636 template<typename LocArg>
637 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000638 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000639 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000640 // Don't override a previous diagnostic. Don't bother collecting
641 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000642 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000643 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000644 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000645 }
Richard Smith357362d2011-12-13 06:39:58 +0000646 return Diag(Loc, DiagId, ExtraNotes);
647 }
648
649 /// Add a note to a prior diagnostic.
650 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
651 if (!HasActiveDiagnostic)
652 return OptionalDiagnostic();
653 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000654 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000655
656 /// Add a stack of notes to a prior diagnostic.
657 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
658 if (HasActiveDiagnostic) {
659 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
660 Diags.begin(), Diags.end());
661 }
662 }
Richard Smith253c2a32012-01-27 01:14:48 +0000663
Richard Smith6d4c6582013-11-05 22:18:15 +0000664 /// Should we continue evaluation after encountering a side-effect that we
665 /// couldn't model?
666 bool keepEvaluatingAfterSideEffect() {
667 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000668 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000669 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000670 case EM_EvaluateForOverflow:
671 case EM_IgnoreSideEffects:
672 return true;
673
Richard Smith6d4c6582013-11-05 22:18:15 +0000674 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000675 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000676 case EM_ConstantFold:
677 return false;
678 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000679 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000680 }
681
682 /// Note that we have had a side-effect, and determine whether we should
683 /// keep evaluating.
684 bool noteSideEffect() {
685 EvalStatus.HasSideEffects = true;
686 return keepEvaluatingAfterSideEffect();
687 }
688
Richard Smith253c2a32012-01-27 01:14:48 +0000689 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000690 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000691 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000692 if (!StepsLeft)
693 return false;
694
695 switch (EvalMode) {
696 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000697 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000698 case EM_EvaluateForOverflow:
699 return true;
700
701 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000702 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 case EM_ConstantFold:
704 case EM_IgnoreSideEffects:
705 return false;
706 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000707 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000708 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000709 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000710
711 /// Object used to treat all foldable expressions as constant expressions.
712 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000713 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000714 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000715 bool HadNoPriorDiags;
716 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000717
Richard Smith6d4c6582013-11-05 22:18:15 +0000718 explicit FoldConstant(EvalInfo &Info, bool Enabled)
719 : Info(Info),
720 Enabled(Enabled),
721 HadNoPriorDiags(Info.EvalStatus.Diag &&
722 Info.EvalStatus.Diag->empty() &&
723 !Info.EvalStatus.HasSideEffects),
724 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000725 if (Enabled &&
726 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
727 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000728 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000729 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000730 void keepDiagnostics() { Enabled = false; }
731 ~FoldConstant() {
732 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000733 !Info.EvalStatus.HasSideEffects)
734 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000735 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000736 }
737 };
Richard Smith17100ba2012-02-16 02:46:34 +0000738
739 /// RAII object used to suppress diagnostics and side-effects from a
740 /// speculative evaluation.
741 class SpeculativeEvaluationRAII {
742 EvalInfo &Info;
743 Expr::EvalStatus Old;
744
745 public:
746 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000747 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000748 : Info(Info), Old(Info.EvalStatus) {
749 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000750 // If we're speculatively evaluating, we may have skipped over some
751 // evaluations and missed out a side effect.
752 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000753 }
754 ~SpeculativeEvaluationRAII() {
755 Info.EvalStatus = Old;
756 }
757 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000758
759 /// RAII object wrapping a full-expression or block scope, and handling
760 /// the ending of the lifetime of temporaries created within it.
761 template<bool IsFullExpression>
762 class ScopeRAII {
763 EvalInfo &Info;
764 unsigned OldStackSize;
765 public:
766 ScopeRAII(EvalInfo &Info)
767 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
768 ~ScopeRAII() {
769 // Body moved to a static method to encourage the compiler to inline away
770 // instances of this class.
771 cleanup(Info, OldStackSize);
772 }
773 private:
774 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
775 unsigned NewEnd = OldStackSize;
776 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
777 I != N; ++I) {
778 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
779 // Full-expression cleanup of a lifetime-extended temporary: nothing
780 // to do, just move this cleanup to the right place in the stack.
781 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
782 ++NewEnd;
783 } else {
784 // End the lifetime of the object.
785 Info.CleanupStack[I].endLifetime();
786 }
787 }
788 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
789 Info.CleanupStack.end());
790 }
791 };
792 typedef ScopeRAII<false> BlockScopeRAII;
793 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smithf6f003a2011-12-16 19:06:07 +0000794}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000795
Richard Smitha8105bc2012-01-06 16:39:00 +0000796bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
797 CheckSubobjectKind CSK) {
798 if (Invalid)
799 return false;
800 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000801 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000802 << CSK;
803 setInvalid();
804 return false;
805 }
806 return true;
807}
808
809void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
810 const Expr *E, uint64_t N) {
811 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000812 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000813 << static_cast<int>(N) << /*array*/ 0
814 << static_cast<unsigned>(MostDerivedArraySize);
815 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000816 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000817 << static_cast<int>(N) << /*non-array*/ 1;
818 setInvalid();
819}
820
Richard Smithf6f003a2011-12-16 19:06:07 +0000821CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
822 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000823 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000824 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000825 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000826 Info.CurrentCall = this;
827 ++Info.CallStackDepth;
828}
829
830CallStackFrame::~CallStackFrame() {
831 assert(Info.CurrentCall == this && "calls retired out of order");
832 --Info.CallStackDepth;
833 Info.CurrentCall = Caller;
834}
835
Richard Smith08d6a2c2013-07-24 07:11:57 +0000836APValue &CallStackFrame::createTemporary(const void *Key,
837 bool IsLifetimeExtended) {
838 APValue &Result = Temporaries[Key];
839 assert(Result.isUninit() && "temporary created multiple times");
840 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
841 return Result;
842}
843
Richard Smith84401042013-06-03 05:03:02 +0000844static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000845
846void EvalInfo::addCallStack(unsigned Limit) {
847 // Determine which calls to skip, if any.
848 unsigned ActiveCalls = CallStackDepth - 1;
849 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
850 if (Limit && Limit < ActiveCalls) {
851 SkipStart = Limit / 2 + Limit % 2;
852 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000853 }
854
Richard Smithf6f003a2011-12-16 19:06:07 +0000855 // Walk the call stack and add the diagnostics.
856 unsigned CallIdx = 0;
857 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
858 Frame = Frame->Caller, ++CallIdx) {
859 // Skip this call?
860 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
861 if (CallIdx == SkipStart) {
862 // Note that we're skipping calls.
863 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
864 << unsigned(ActiveCalls - Limit);
865 }
866 continue;
867 }
868
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000869 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000870 llvm::raw_svector_ostream Out(Buffer);
871 describeCall(Frame, Out);
872 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
873 }
874}
875
876namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000877 struct ComplexValue {
878 private:
879 bool IsInt;
880
881 public:
882 APSInt IntReal, IntImag;
883 APFloat FloatReal, FloatImag;
884
885 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
886
887 void makeComplexFloat() { IsInt = false; }
888 bool isComplexFloat() const { return !IsInt; }
889 APFloat &getComplexFloatReal() { return FloatReal; }
890 APFloat &getComplexFloatImag() { return FloatImag; }
891
892 void makeComplexInt() { IsInt = true; }
893 bool isComplexInt() const { return IsInt; }
894 APSInt &getComplexIntReal() { return IntReal; }
895 APSInt &getComplexIntImag() { return IntImag; }
896
Richard Smith2e312c82012-03-03 22:46:17 +0000897 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000898 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000899 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000900 else
Richard Smith2e312c82012-03-03 22:46:17 +0000901 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000902 }
Richard Smith2e312c82012-03-03 22:46:17 +0000903 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000904 assert(v.isComplexFloat() || v.isComplexInt());
905 if (v.isComplexFloat()) {
906 makeComplexFloat();
907 FloatReal = v.getComplexFloatReal();
908 FloatImag = v.getComplexFloatImag();
909 } else {
910 makeComplexInt();
911 IntReal = v.getComplexIntReal();
912 IntImag = v.getComplexIntImag();
913 }
914 }
John McCall93d91dc2010-05-07 17:22:02 +0000915 };
John McCall45d55e42010-05-07 21:00:08 +0000916
917 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000918 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000919 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000920 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000921 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000922
Richard Smithce40ad62011-11-12 22:28:03 +0000923 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000924 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000925 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000926 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000927 SubobjectDesignator &getLValueDesignator() { return Designator; }
928 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000929
Richard Smith2e312c82012-03-03 22:46:17 +0000930 void moveInto(APValue &V) const {
931 if (Designator.Invalid)
932 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
933 else
934 V = APValue(Base, Offset, Designator.Entries,
935 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000936 }
Richard Smith2e312c82012-03-03 22:46:17 +0000937 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000938 assert(V.isLValue());
939 Base = V.getLValueBase();
940 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000941 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000942 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000943 }
944
Richard Smithb228a862012-02-15 02:18:13 +0000945 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000946 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000947 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000948 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000949 Designator = SubobjectDesignator(getType(B));
950 }
951
952 // Check that this LValue is not based on a null pointer. If it is, produce
953 // a diagnostic and mark the designator as invalid.
954 bool checkNullPointer(EvalInfo &Info, const Expr *E,
955 CheckSubobjectKind CSK) {
956 if (Designator.Invalid)
957 return false;
958 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000959 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000960 << CSK;
961 Designator.setInvalid();
962 return false;
963 }
964 return true;
965 }
966
967 // Check this LValue refers to an object. If not, set the designator to be
968 // invalid and emit a diagnostic.
969 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000970 // Outside C++11, do not build a designator referring to a subobject of
971 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000972 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000973 Designator.setInvalid();
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000974 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000975 Designator.checkSubobject(Info, E, CSK);
976 }
977
978 void addDecl(EvalInfo &Info, const Expr *E,
979 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000980 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
981 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000982 }
983 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000984 if (checkSubobject(Info, E, CSK_ArrayToPointer))
985 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000986 }
Richard Smith66c96992012-02-18 22:04:06 +0000987 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000988 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
989 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000990 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000991 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000992 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +0000993 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000994 }
John McCall45d55e42010-05-07 21:00:08 +0000995 };
Richard Smith027bf112011-11-17 22:56:20 +0000996
997 struct MemberPtr {
998 MemberPtr() {}
999 explicit MemberPtr(const ValueDecl *Decl) :
1000 DeclAndIsDerivedMember(Decl, false), Path() {}
1001
1002 /// The member or (direct or indirect) field referred to by this member
1003 /// pointer, or 0 if this is a null member pointer.
1004 const ValueDecl *getDecl() const {
1005 return DeclAndIsDerivedMember.getPointer();
1006 }
1007 /// Is this actually a member of some type derived from the relevant class?
1008 bool isDerivedMember() const {
1009 return DeclAndIsDerivedMember.getInt();
1010 }
1011 /// Get the class which the declaration actually lives in.
1012 const CXXRecordDecl *getContainingRecord() const {
1013 return cast<CXXRecordDecl>(
1014 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1015 }
1016
Richard Smith2e312c82012-03-03 22:46:17 +00001017 void moveInto(APValue &V) const {
1018 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001019 }
Richard Smith2e312c82012-03-03 22:46:17 +00001020 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001021 assert(V.isMemberPointer());
1022 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1023 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1024 Path.clear();
1025 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1026 Path.insert(Path.end(), P.begin(), P.end());
1027 }
1028
1029 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1030 /// whether the member is a member of some class derived from the class type
1031 /// of the member pointer.
1032 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1033 /// Path - The path of base/derived classes from the member declaration's
1034 /// class (exclusive) to the class type of the member pointer (inclusive).
1035 SmallVector<const CXXRecordDecl*, 4> Path;
1036
1037 /// Perform a cast towards the class of the Decl (either up or down the
1038 /// hierarchy).
1039 bool castBack(const CXXRecordDecl *Class) {
1040 assert(!Path.empty());
1041 const CXXRecordDecl *Expected;
1042 if (Path.size() >= 2)
1043 Expected = Path[Path.size() - 2];
1044 else
1045 Expected = getContainingRecord();
1046 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1047 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1048 // if B does not contain the original member and is not a base or
1049 // derived class of the class containing the original member, the result
1050 // of the cast is undefined.
1051 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1052 // (D::*). We consider that to be a language defect.
1053 return false;
1054 }
1055 Path.pop_back();
1056 return true;
1057 }
1058 /// Perform a base-to-derived member pointer cast.
1059 bool castToDerived(const CXXRecordDecl *Derived) {
1060 if (!getDecl())
1061 return true;
1062 if (!isDerivedMember()) {
1063 Path.push_back(Derived);
1064 return true;
1065 }
1066 if (!castBack(Derived))
1067 return false;
1068 if (Path.empty())
1069 DeclAndIsDerivedMember.setInt(false);
1070 return true;
1071 }
1072 /// Perform a derived-to-base member pointer cast.
1073 bool castToBase(const CXXRecordDecl *Base) {
1074 if (!getDecl())
1075 return true;
1076 if (Path.empty())
1077 DeclAndIsDerivedMember.setInt(true);
1078 if (isDerivedMember()) {
1079 Path.push_back(Base);
1080 return true;
1081 }
1082 return castBack(Base);
1083 }
1084 };
Richard Smith357362d2011-12-13 06:39:58 +00001085
Richard Smith7bb00672012-02-01 01:42:44 +00001086 /// Compare two member pointers, which are assumed to be of the same type.
1087 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1088 if (!LHS.getDecl() || !RHS.getDecl())
1089 return !LHS.getDecl() && !RHS.getDecl();
1090 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1091 return false;
1092 return LHS.Path == RHS.Path;
1093 }
John McCall93d91dc2010-05-07 17:22:02 +00001094}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001095
Richard Smith2e312c82012-03-03 22:46:17 +00001096static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001097static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1098 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001099 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001100static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1101static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001102static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1103 EvalInfo &Info);
1104static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001105static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001106static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001107 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001108static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001109static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001110static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001111
1112//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001113// Misc utilities
1114//===----------------------------------------------------------------------===//
1115
Richard Smith84401042013-06-03 05:03:02 +00001116/// Produce a string describing the given constexpr call.
1117static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1118 unsigned ArgIndex = 0;
1119 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1120 !isa<CXXConstructorDecl>(Frame->Callee) &&
1121 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1122
1123 if (!IsMemberCall)
1124 Out << *Frame->Callee << '(';
1125
1126 if (Frame->This && IsMemberCall) {
1127 APValue Val;
1128 Frame->This->moveInto(Val);
1129 Val.printPretty(Out, Frame->Info.Ctx,
1130 Frame->This->Designator.MostDerivedType);
1131 // FIXME: Add parens around Val if needed.
1132 Out << "->" << *Frame->Callee << '(';
1133 IsMemberCall = false;
1134 }
1135
1136 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1137 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1138 if (ArgIndex > (unsigned)IsMemberCall)
1139 Out << ", ";
1140
1141 const ParmVarDecl *Param = *I;
1142 const APValue &Arg = Frame->Arguments[ArgIndex];
1143 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1144
1145 if (ArgIndex == 0 && IsMemberCall)
1146 Out << "->" << *Frame->Callee << '(';
1147 }
1148
1149 Out << ')';
1150}
1151
Richard Smithd9f663b2013-04-22 15:31:51 +00001152/// Evaluate an expression to see if it had side-effects, and discard its
1153/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001154/// \return \c true if the caller should keep evaluating.
1155static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001156 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001157 if (!Evaluate(Scratch, Info, E))
1158 // We don't need the value, but we might have skipped a side effect here.
1159 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001160 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001161}
1162
Richard Smith861b5b52013-05-07 23:34:45 +00001163/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1164/// return its existing value.
1165static int64_t getExtValue(const APSInt &Value) {
1166 return Value.isSigned() ? Value.getSExtValue()
1167 : static_cast<int64_t>(Value.getZExtValue());
1168}
1169
Richard Smithd62306a2011-11-10 06:34:14 +00001170/// Should this call expression be treated as a string literal?
1171static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001172 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001173 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1174 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1175}
1176
Richard Smithce40ad62011-11-12 22:28:03 +00001177static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001178 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1179 // constant expression of pointer type that evaluates to...
1180
1181 // ... a null pointer value, or a prvalue core constant expression of type
1182 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001183 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001184
Richard Smithce40ad62011-11-12 22:28:03 +00001185 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1186 // ... the address of an object with static storage duration,
1187 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1188 return VD->hasGlobalStorage();
1189 // ... the address of a function,
1190 return isa<FunctionDecl>(D);
1191 }
1192
1193 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001194 switch (E->getStmtClass()) {
1195 default:
1196 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001197 case Expr::CompoundLiteralExprClass: {
1198 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1199 return CLE->isFileScope() && CLE->isLValue();
1200 }
Richard Smithe6c01442013-06-05 00:46:14 +00001201 case Expr::MaterializeTemporaryExprClass:
1202 // A materialized temporary might have been lifetime-extended to static
1203 // storage duration.
1204 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001205 // A string literal has static storage duration.
1206 case Expr::StringLiteralClass:
1207 case Expr::PredefinedExprClass:
1208 case Expr::ObjCStringLiteralClass:
1209 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001210 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001211 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001212 return true;
1213 case Expr::CallExprClass:
1214 return IsStringLiteralCall(cast<CallExpr>(E));
1215 // For GCC compatibility, &&label has static storage duration.
1216 case Expr::AddrLabelExprClass:
1217 return true;
1218 // A Block literal expression may be used as the initialization value for
1219 // Block variables at global or local static scope.
1220 case Expr::BlockExprClass:
1221 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001222 case Expr::ImplicitValueInitExprClass:
1223 // FIXME:
1224 // We can never form an lvalue with an implicit value initialization as its
1225 // base through expression evaluation, so these only appear in one case: the
1226 // implicit variable declaration we invent when checking whether a constexpr
1227 // constructor can produce a constant expression. We must assume that such
1228 // an expression might be a global lvalue.
1229 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001230 }
John McCall95007602010-05-10 23:27:23 +00001231}
1232
Richard Smithb228a862012-02-15 02:18:13 +00001233static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1234 assert(Base && "no location for a null lvalue");
1235 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1236 if (VD)
1237 Info.Note(VD->getLocation(), diag::note_declared_at);
1238 else
Ted Kremenek28831752012-08-23 20:46:57 +00001239 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001240 diag::note_constexpr_temporary_here);
1241}
1242
Richard Smith80815602011-11-07 05:07:52 +00001243/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001244/// value for an address or reference constant expression. Return true if we
1245/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001246static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1247 QualType Type, const LValue &LVal) {
1248 bool IsReferenceType = Type->isReferenceType();
1249
Richard Smith357362d2011-12-13 06:39:58 +00001250 APValue::LValueBase Base = LVal.getLValueBase();
1251 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1252
Richard Smith0dea49e2012-02-18 04:58:18 +00001253 // Check that the object is a global. Note that the fake 'this' object we
1254 // manufacture when checking potential constant expressions is conservatively
1255 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001256 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001257 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001258 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001259 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1260 << IsReferenceType << !Designator.Entries.empty()
1261 << !!VD << VD;
1262 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001263 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001264 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001265 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001266 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001267 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001268 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001269 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001270 LVal.getLValueCallIndex() == 0) &&
1271 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001272
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001273 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1274 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001275 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001276 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001277 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001278
Hans Wennborg82dd8772014-06-25 22:19:48 +00001279 // A dllimport variable never acts like a constant.
1280 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001281 return false;
1282 }
1283 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1284 // __declspec(dllimport) must be handled very carefully:
1285 // We must never initialize an expression with the thunk in C++.
1286 // Doing otherwise would allow the same id-expression to yield
1287 // different addresses for the same function in different translation
1288 // units. However, this means that we must dynamically initialize the
1289 // expression with the contents of the import address table at runtime.
1290 //
1291 // The C language has no notion of ODR; furthermore, it has no notion of
1292 // dynamic initialization. This means that we are permitted to
1293 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001294 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001295 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001296 }
1297 }
1298
Richard Smitha8105bc2012-01-06 16:39:00 +00001299 // Allow address constant expressions to be past-the-end pointers. This is
1300 // an extension: the standard requires them to point to an object.
1301 if (!IsReferenceType)
1302 return true;
1303
1304 // A reference constant expression must refer to an object.
1305 if (!Base) {
1306 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001307 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001308 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001309 }
1310
Richard Smith357362d2011-12-13 06:39:58 +00001311 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001312 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001313 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001314 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001315 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001316 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001317 }
1318
Richard Smith80815602011-11-07 05:07:52 +00001319 return true;
1320}
1321
Richard Smithfddd3842011-12-30 21:15:51 +00001322/// Check that this core constant expression is of literal type, and if not,
1323/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001324static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001325 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001326 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001327 return true;
1328
Richard Smith7525ff62013-05-09 07:14:00 +00001329 // C++1y: A constant initializer for an object o [...] may also invoke
1330 // constexpr constructors for o and its subobjects even if those objects
1331 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001332 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001333 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001334 return true;
1335
Richard Smithfddd3842011-12-30 21:15:51 +00001336 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001337 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001338 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001339 << E->getType();
1340 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001341 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001342 return false;
1343}
1344
Richard Smith0b0a0b62011-10-29 20:57:55 +00001345/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001346/// constant expression. If not, report an appropriate diagnostic. Does not
1347/// check that the expression is of literal type.
1348static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1349 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001350 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001351 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1352 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001353 return false;
1354 }
1355
Richard Smith77be48a2014-07-31 06:31:19 +00001356 // We allow _Atomic(T) to be initialized from anything that T can be
1357 // initialized from.
1358 if (const AtomicType *AT = Type->getAs<AtomicType>())
1359 Type = AT->getValueType();
1360
Richard Smithb228a862012-02-15 02:18:13 +00001361 // Core issue 1454: For a literal constant expression of array or class type,
1362 // each subobject of its value shall have been initialized by a constant
1363 // expression.
1364 if (Value.isArray()) {
1365 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1366 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1367 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1368 Value.getArrayInitializedElt(I)))
1369 return false;
1370 }
1371 if (!Value.hasArrayFiller())
1372 return true;
1373 return CheckConstantExpression(Info, DiagLoc, EltTy,
1374 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001375 }
Richard Smithb228a862012-02-15 02:18:13 +00001376 if (Value.isUnion() && Value.getUnionField()) {
1377 return CheckConstantExpression(Info, DiagLoc,
1378 Value.getUnionField()->getType(),
1379 Value.getUnionValue());
1380 }
1381 if (Value.isStruct()) {
1382 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1383 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1384 unsigned BaseIndex = 0;
1385 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1386 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1387 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1388 Value.getStructBase(BaseIndex)))
1389 return false;
1390 }
1391 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001392 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001393 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1394 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001395 return false;
1396 }
1397 }
1398
1399 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001400 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001401 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001402 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1403 }
1404
1405 // Everything else is fine.
1406 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001407}
1408
Richard Smith83c68212011-10-31 05:11:32 +00001409const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001410 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001411}
1412
1413static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001414 if (Value.CallIndex)
1415 return false;
1416 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1417 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001418}
1419
Richard Smithcecf1842011-11-01 21:06:14 +00001420static bool IsWeakLValue(const LValue &Value) {
1421 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001422 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001423}
1424
Richard Smith2e312c82012-03-03 22:46:17 +00001425static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001426 // A null base expression indicates a null pointer. These are always
1427 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001428 if (!Value.getLValueBase()) {
1429 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001430 return true;
1431 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001432
Richard Smith027bf112011-11-17 22:56:20 +00001433 // We have a non-null base. These are generally known to be true, but if it's
1434 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001435 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001436 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001437 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001438}
1439
Richard Smith2e312c82012-03-03 22:46:17 +00001440static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001441 switch (Val.getKind()) {
1442 case APValue::Uninitialized:
1443 return false;
1444 case APValue::Int:
1445 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001446 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001447 case APValue::Float:
1448 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001449 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001450 case APValue::ComplexInt:
1451 Result = Val.getComplexIntReal().getBoolValue() ||
1452 Val.getComplexIntImag().getBoolValue();
1453 return true;
1454 case APValue::ComplexFloat:
1455 Result = !Val.getComplexFloatReal().isZero() ||
1456 !Val.getComplexFloatImag().isZero();
1457 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001458 case APValue::LValue:
1459 return EvalPointerValueAsBool(Val, Result);
1460 case APValue::MemberPointer:
1461 Result = Val.getMemberPointerDecl();
1462 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001463 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001464 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001465 case APValue::Struct:
1466 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001467 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001468 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001469 }
1470
Richard Smith11562c52011-10-28 17:51:58 +00001471 llvm_unreachable("unknown APValue kind");
1472}
1473
1474static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1475 EvalInfo &Info) {
1476 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001477 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001478 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001479 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001480 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001481}
1482
Richard Smith357362d2011-12-13 06:39:58 +00001483template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001484static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001485 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001486 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001487 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001488}
1489
1490static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1491 QualType SrcType, const APFloat &Value,
1492 QualType DestType, APSInt &Result) {
1493 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001494 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001495 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001496
Richard Smith357362d2011-12-13 06:39:58 +00001497 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001498 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001499 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1500 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001501 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001502 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001503}
1504
Richard Smith357362d2011-12-13 06:39:58 +00001505static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1506 QualType SrcType, QualType DestType,
1507 APFloat &Result) {
1508 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001509 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001510 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1511 APFloat::rmNearestTiesToEven, &ignored)
1512 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001513 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001514 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001515}
1516
Richard Smith911e1422012-01-30 22:27:01 +00001517static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1518 QualType DestType, QualType SrcType,
1519 APSInt &Value) {
1520 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001521 APSInt Result = Value;
1522 // Figure out if this is a truncate, extend or noop cast.
1523 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001524 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001525 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001526 return Result;
1527}
1528
Richard Smith357362d2011-12-13 06:39:58 +00001529static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1530 QualType SrcType, const APSInt &Value,
1531 QualType DestType, APFloat &Result) {
1532 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1533 if (Result.convertFromAPInt(Value, Value.isSigned(),
1534 APFloat::rmNearestTiesToEven)
1535 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001536 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001537 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001538}
1539
Richard Smith49ca8aa2013-08-06 07:09:20 +00001540static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1541 APValue &Value, const FieldDecl *FD) {
1542 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1543
1544 if (!Value.isInt()) {
1545 // Trying to store a pointer-cast-to-integer into a bitfield.
1546 // FIXME: In this case, we should provide the diagnostic for casting
1547 // a pointer to an integer.
1548 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1549 Info.Diag(E);
1550 return false;
1551 }
1552
1553 APSInt &Int = Value.getInt();
1554 unsigned OldBitWidth = Int.getBitWidth();
1555 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1556 if (NewBitWidth < OldBitWidth)
1557 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1558 return true;
1559}
1560
Eli Friedman803acb32011-12-22 03:51:45 +00001561static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1562 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001563 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001564 if (!Evaluate(SVal, Info, E))
1565 return false;
1566 if (SVal.isInt()) {
1567 Res = SVal.getInt();
1568 return true;
1569 }
1570 if (SVal.isFloat()) {
1571 Res = SVal.getFloat().bitcastToAPInt();
1572 return true;
1573 }
1574 if (SVal.isVector()) {
1575 QualType VecTy = E->getType();
1576 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1577 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1578 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1579 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1580 Res = llvm::APInt::getNullValue(VecSize);
1581 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1582 APValue &Elt = SVal.getVectorElt(i);
1583 llvm::APInt EltAsInt;
1584 if (Elt.isInt()) {
1585 EltAsInt = Elt.getInt();
1586 } else if (Elt.isFloat()) {
1587 EltAsInt = Elt.getFloat().bitcastToAPInt();
1588 } else {
1589 // Don't try to handle vectors of anything other than int or float
1590 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001591 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001592 return false;
1593 }
1594 unsigned BaseEltSize = EltAsInt.getBitWidth();
1595 if (BigEndian)
1596 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1597 else
1598 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1599 }
1600 return true;
1601 }
1602 // Give up if the input isn't an int, float, or vector. For example, we
1603 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001604 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001605 return false;
1606}
1607
Richard Smith43e77732013-05-07 04:50:00 +00001608/// Perform the given integer operation, which is known to need at most BitWidth
1609/// bits, and check for overflow in the original type (if that type was not an
1610/// unsigned type).
1611template<typename Operation>
1612static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1613 const APSInt &LHS, const APSInt &RHS,
1614 unsigned BitWidth, Operation Op) {
1615 if (LHS.isUnsigned())
1616 return Op(LHS, RHS);
1617
1618 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1619 APSInt Result = Value.trunc(LHS.getBitWidth());
1620 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001621 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001622 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1623 diag::warn_integer_constant_overflow)
1624 << Result.toString(10) << E->getType();
1625 else
1626 HandleOverflow(Info, E, Value, E->getType());
1627 }
1628 return Result;
1629}
1630
1631/// Perform the given binary integer operation.
1632static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1633 BinaryOperatorKind Opcode, APSInt RHS,
1634 APSInt &Result) {
1635 switch (Opcode) {
1636 default:
1637 Info.Diag(E);
1638 return false;
1639 case BO_Mul:
1640 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1641 std::multiplies<APSInt>());
1642 return true;
1643 case BO_Add:
1644 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1645 std::plus<APSInt>());
1646 return true;
1647 case BO_Sub:
1648 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1649 std::minus<APSInt>());
1650 return true;
1651 case BO_And: Result = LHS & RHS; return true;
1652 case BO_Xor: Result = LHS ^ RHS; return true;
1653 case BO_Or: Result = LHS | RHS; return true;
1654 case BO_Div:
1655 case BO_Rem:
1656 if (RHS == 0) {
1657 Info.Diag(E, diag::note_expr_divide_by_zero);
1658 return false;
1659 }
1660 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1661 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1662 LHS.isSigned() && LHS.isMinSignedValue())
1663 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1664 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1665 return true;
1666 case BO_Shl: {
1667 if (Info.getLangOpts().OpenCL)
1668 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1669 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1670 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1671 RHS.isUnsigned());
1672 else if (RHS.isSigned() && RHS.isNegative()) {
1673 // During constant-folding, a negative shift is an opposite shift. Such
1674 // a shift is not a constant expression.
1675 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1676 RHS = -RHS;
1677 goto shift_right;
1678 }
1679 shift_left:
1680 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1681 // the shifted type.
1682 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1683 if (SA != RHS) {
1684 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1685 << RHS << E->getType() << LHS.getBitWidth();
1686 } else if (LHS.isSigned()) {
1687 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1688 // operand, and must not overflow the corresponding unsigned type.
1689 if (LHS.isNegative())
1690 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1691 else if (LHS.countLeadingZeros() < SA)
1692 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1693 }
1694 Result = LHS << SA;
1695 return true;
1696 }
1697 case BO_Shr: {
1698 if (Info.getLangOpts().OpenCL)
1699 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1700 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1701 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1702 RHS.isUnsigned());
1703 else if (RHS.isSigned() && RHS.isNegative()) {
1704 // During constant-folding, a negative shift is an opposite shift. Such a
1705 // shift is not a constant expression.
1706 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1707 RHS = -RHS;
1708 goto shift_left;
1709 }
1710 shift_right:
1711 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1712 // shifted type.
1713 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1714 if (SA != RHS)
1715 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1716 << RHS << E->getType() << LHS.getBitWidth();
1717 Result = LHS >> SA;
1718 return true;
1719 }
1720
1721 case BO_LT: Result = LHS < RHS; return true;
1722 case BO_GT: Result = LHS > RHS; return true;
1723 case BO_LE: Result = LHS <= RHS; return true;
1724 case BO_GE: Result = LHS >= RHS; return true;
1725 case BO_EQ: Result = LHS == RHS; return true;
1726 case BO_NE: Result = LHS != RHS; return true;
1727 }
1728}
1729
Richard Smith861b5b52013-05-07 23:34:45 +00001730/// Perform the given binary floating-point operation, in-place, on LHS.
1731static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1732 APFloat &LHS, BinaryOperatorKind Opcode,
1733 const APFloat &RHS) {
1734 switch (Opcode) {
1735 default:
1736 Info.Diag(E);
1737 return false;
1738 case BO_Mul:
1739 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1740 break;
1741 case BO_Add:
1742 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1743 break;
1744 case BO_Sub:
1745 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1746 break;
1747 case BO_Div:
1748 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1749 break;
1750 }
1751
1752 if (LHS.isInfinity() || LHS.isNaN())
1753 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1754 return true;
1755}
1756
Richard Smitha8105bc2012-01-06 16:39:00 +00001757/// Cast an lvalue referring to a base subobject to a derived class, by
1758/// truncating the lvalue's path to the given length.
1759static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1760 const RecordDecl *TruncatedType,
1761 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001762 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001763
1764 // Check we actually point to a derived class object.
1765 if (TruncatedElements == D.Entries.size())
1766 return true;
1767 assert(TruncatedElements >= D.MostDerivedPathLength &&
1768 "not casting to a derived class");
1769 if (!Result.checkSubobject(Info, E, CSK_Derived))
1770 return false;
1771
1772 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001773 const RecordDecl *RD = TruncatedType;
1774 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001775 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001776 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1777 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001778 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001779 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001780 else
Richard Smithd62306a2011-11-10 06:34:14 +00001781 Result.Offset -= Layout.getBaseClassOffset(Base);
1782 RD = Base;
1783 }
Richard Smith027bf112011-11-17 22:56:20 +00001784 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001785 return true;
1786}
1787
John McCalld7bca762012-05-01 00:38:49 +00001788static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001789 const CXXRecordDecl *Derived,
1790 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001791 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001792 if (!RL) {
1793 if (Derived->isInvalidDecl()) return false;
1794 RL = &Info.Ctx.getASTRecordLayout(Derived);
1795 }
1796
Richard Smithd62306a2011-11-10 06:34:14 +00001797 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001798 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001799 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001800}
1801
Richard Smitha8105bc2012-01-06 16:39:00 +00001802static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001803 const CXXRecordDecl *DerivedDecl,
1804 const CXXBaseSpecifier *Base) {
1805 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1806
John McCalld7bca762012-05-01 00:38:49 +00001807 if (!Base->isVirtual())
1808 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001809
Richard Smitha8105bc2012-01-06 16:39:00 +00001810 SubobjectDesignator &D = Obj.Designator;
1811 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001812 return false;
1813
Richard Smitha8105bc2012-01-06 16:39:00 +00001814 // Extract most-derived object and corresponding type.
1815 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1816 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1817 return false;
1818
1819 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001820 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001821 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1822 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001823 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001824 return true;
1825}
1826
Richard Smith84401042013-06-03 05:03:02 +00001827static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1828 QualType Type, LValue &Result) {
1829 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1830 PathE = E->path_end();
1831 PathI != PathE; ++PathI) {
1832 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1833 *PathI))
1834 return false;
1835 Type = (*PathI)->getType();
1836 }
1837 return true;
1838}
1839
Richard Smithd62306a2011-11-10 06:34:14 +00001840/// Update LVal to refer to the given field, which must be a member of the type
1841/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001842static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001843 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001844 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001845 if (!RL) {
1846 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001847 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001848 }
Richard Smithd62306a2011-11-10 06:34:14 +00001849
1850 unsigned I = FD->getFieldIndex();
1851 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001852 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001853 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001854}
1855
Richard Smith1b78b3d2012-01-25 22:15:11 +00001856/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001857static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001858 LValue &LVal,
1859 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001860 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001861 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001862 return false;
1863 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001864}
1865
Richard Smithd62306a2011-11-10 06:34:14 +00001866/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001867static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1868 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001869 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1870 // extension.
1871 if (Type->isVoidType() || Type->isFunctionType()) {
1872 Size = CharUnits::One();
1873 return true;
1874 }
1875
1876 if (!Type->isConstantSizeType()) {
1877 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001878 // FIXME: Better diagnostic.
1879 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001880 return false;
1881 }
1882
1883 Size = Info.Ctx.getTypeSizeInChars(Type);
1884 return true;
1885}
1886
1887/// Update a pointer value to model pointer arithmetic.
1888/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001889/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001890/// \param LVal - The pointer value to be updated.
1891/// \param EltTy - The pointee type represented by LVal.
1892/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001893static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1894 LValue &LVal, QualType EltTy,
1895 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001896 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001897 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001898 return false;
1899
1900 // Compute the new offset in the appropriate width.
1901 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001902 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001903 return true;
1904}
1905
Richard Smith66c96992012-02-18 22:04:06 +00001906/// Update an lvalue to refer to a component of a complex number.
1907/// \param Info - Information about the ongoing evaluation.
1908/// \param LVal - The lvalue to be updated.
1909/// \param EltTy - The complex number's component type.
1910/// \param Imag - False for the real component, true for the imaginary.
1911static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1912 LValue &LVal, QualType EltTy,
1913 bool Imag) {
1914 if (Imag) {
1915 CharUnits SizeOfComponent;
1916 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1917 return false;
1918 LVal.Offset += SizeOfComponent;
1919 }
1920 LVal.addComplex(Info, E, EltTy, Imag);
1921 return true;
1922}
1923
Richard Smith27908702011-10-24 17:54:18 +00001924/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001925///
1926/// \param Info Information about the ongoing evaluation.
1927/// \param E An expression to be used when printing diagnostics.
1928/// \param VD The variable whose initializer should be obtained.
1929/// \param Frame The frame in which the variable was created. Must be null
1930/// if this variable is not local to the evaluation.
1931/// \param Result Filled in with a pointer to the value of the variable.
1932static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1933 const VarDecl *VD, CallStackFrame *Frame,
1934 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001935 // If this is a parameter to an active constexpr function call, perform
1936 // argument substitution.
1937 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001938 // Assume arguments of a potential constant expression are unknown
1939 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001940 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001941 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001942 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001943 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001944 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001945 }
Richard Smith3229b742013-05-05 21:17:10 +00001946 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001947 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001948 }
Richard Smith27908702011-10-24 17:54:18 +00001949
Richard Smithd9f663b2013-04-22 15:31:51 +00001950 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001951 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001952 Result = Frame->getTemporary(VD);
1953 assert(Result && "missing value for local variable");
1954 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001955 }
1956
Richard Smithd0b4dd62011-12-19 06:19:21 +00001957 // Dig out the initializer, and use the declaration which it's attached to.
1958 const Expr *Init = VD->getAnyInitializer(VD);
1959 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001960 // If we're checking a potential constant expression, the variable could be
1961 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001962 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001963 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001964 return false;
1965 }
1966
Richard Smithd62306a2011-11-10 06:34:14 +00001967 // If we're currently evaluating the initializer of this declaration, use that
1968 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001969 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001970 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001971 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001972 }
1973
Richard Smithcecf1842011-11-01 21:06:14 +00001974 // Never evaluate the initializer of a weak variable. We can't be sure that
1975 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001976 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001977 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001978 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001979 }
Richard Smithcecf1842011-11-01 21:06:14 +00001980
Richard Smithd0b4dd62011-12-19 06:19:21 +00001981 // Check that we can fold the initializer. In C++, we will have already done
1982 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001983 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001984 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001985 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001986 Notes.size() + 1) << VD;
1987 Info.Note(VD->getLocation(), diag::note_declared_at);
1988 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001989 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001990 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001991 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001992 Notes.size() + 1) << VD;
1993 Info.Note(VD->getLocation(), diag::note_declared_at);
1994 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001995 }
Richard Smith27908702011-10-24 17:54:18 +00001996
Richard Smith3229b742013-05-05 21:17:10 +00001997 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001998 return true;
Richard Smith27908702011-10-24 17:54:18 +00001999}
2000
Richard Smith11562c52011-10-28 17:51:58 +00002001static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002002 Qualifiers Quals = T.getQualifiers();
2003 return Quals.hasConst() && !Quals.hasVolatile();
2004}
2005
Richard Smithe97cbd72011-11-11 04:05:33 +00002006/// Get the base index of the given base class within an APValue representing
2007/// the given derived class.
2008static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2009 const CXXRecordDecl *Base) {
2010 Base = Base->getCanonicalDecl();
2011 unsigned Index = 0;
2012 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2013 E = Derived->bases_end(); I != E; ++I, ++Index) {
2014 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2015 return Index;
2016 }
2017
2018 llvm_unreachable("base class missing from derived class's bases list");
2019}
2020
Richard Smith3da88fa2013-04-26 14:36:30 +00002021/// Extract the value of a character from a string literal.
2022static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2023 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002024 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2025 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2026 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002027 const StringLiteral *S = cast<StringLiteral>(Lit);
2028 const ConstantArrayType *CAT =
2029 Info.Ctx.getAsConstantArrayType(S->getType());
2030 assert(CAT && "string literal isn't an array");
2031 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002032 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002033
2034 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002035 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002036 if (Index < S->getLength())
2037 Value = S->getCodeUnit(Index);
2038 return Value;
2039}
2040
Richard Smith3da88fa2013-04-26 14:36:30 +00002041// Expand a string literal into an array of characters.
2042static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2043 APValue &Result) {
2044 const StringLiteral *S = cast<StringLiteral>(Lit);
2045 const ConstantArrayType *CAT =
2046 Info.Ctx.getAsConstantArrayType(S->getType());
2047 assert(CAT && "string literal isn't an array");
2048 QualType CharType = CAT->getElementType();
2049 assert(CharType->isIntegerType() && "unexpected character type");
2050
2051 unsigned Elts = CAT->getSize().getZExtValue();
2052 Result = APValue(APValue::UninitArray(),
2053 std::min(S->getLength(), Elts), Elts);
2054 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2055 CharType->isUnsignedIntegerType());
2056 if (Result.hasArrayFiller())
2057 Result.getArrayFiller() = APValue(Value);
2058 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2059 Value = S->getCodeUnit(I);
2060 Result.getArrayInitializedElt(I) = APValue(Value);
2061 }
2062}
2063
2064// Expand an array so that it has more than Index filled elements.
2065static void expandArray(APValue &Array, unsigned Index) {
2066 unsigned Size = Array.getArraySize();
2067 assert(Index < Size);
2068
2069 // Always at least double the number of elements for which we store a value.
2070 unsigned OldElts = Array.getArrayInitializedElts();
2071 unsigned NewElts = std::max(Index+1, OldElts * 2);
2072 NewElts = std::min(Size, std::max(NewElts, 8u));
2073
2074 // Copy the data across.
2075 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2076 for (unsigned I = 0; I != OldElts; ++I)
2077 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2078 for (unsigned I = OldElts; I != NewElts; ++I)
2079 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2080 if (NewValue.hasArrayFiller())
2081 NewValue.getArrayFiller() = Array.getArrayFiller();
2082 Array.swap(NewValue);
2083}
2084
Richard Smithb01fe402014-09-16 01:24:02 +00002085/// Determine whether a type would actually be read by an lvalue-to-rvalue
2086/// conversion. If it's of class type, we may assume that the copy operation
2087/// is trivial. Note that this is never true for a union type with fields
2088/// (because the copy always "reads" the active member) and always true for
2089/// a non-class type.
2090static bool isReadByLvalueToRvalueConversion(QualType T) {
2091 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2092 if (!RD || (RD->isUnion() && !RD->field_empty()))
2093 return true;
2094 if (RD->isEmpty())
2095 return false;
2096
2097 for (auto *Field : RD->fields())
2098 if (isReadByLvalueToRvalueConversion(Field->getType()))
2099 return true;
2100
2101 for (auto &BaseSpec : RD->bases())
2102 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2103 return true;
2104
2105 return false;
2106}
2107
2108/// Diagnose an attempt to read from any unreadable field within the specified
2109/// type, which might be a class type.
2110static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2111 QualType T) {
2112 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2113 if (!RD)
2114 return false;
2115
2116 if (!RD->hasMutableFields())
2117 return false;
2118
2119 for (auto *Field : RD->fields()) {
2120 // If we're actually going to read this field in some way, then it can't
2121 // be mutable. If we're in a union, then assigning to a mutable field
2122 // (even an empty one) can change the active member, so that's not OK.
2123 // FIXME: Add core issue number for the union case.
2124 if (Field->isMutable() &&
2125 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2126 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2127 Info.Note(Field->getLocation(), diag::note_declared_at);
2128 return true;
2129 }
2130
2131 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2132 return true;
2133 }
2134
2135 for (auto &BaseSpec : RD->bases())
2136 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2137 return true;
2138
2139 // All mutable fields were empty, and thus not actually read.
2140 return false;
2141}
2142
Richard Smith861b5b52013-05-07 23:34:45 +00002143/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002144enum AccessKinds {
2145 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002146 AK_Assign,
2147 AK_Increment,
2148 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002149};
2150
Richard Smith3229b742013-05-05 21:17:10 +00002151/// A handle to a complete object (an object that is not a subobject of
2152/// another object).
2153struct CompleteObject {
2154 /// The value of the complete object.
2155 APValue *Value;
2156 /// The type of the complete object.
2157 QualType Type;
2158
Craig Topper36250ad2014-05-12 05:36:57 +00002159 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002160 CompleteObject(APValue *Value, QualType Type)
2161 : Value(Value), Type(Type) {
2162 assert(Value && "missing value for complete object");
2163 }
2164
David Blaikie7d170102013-05-15 07:37:26 +00002165 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002166};
2167
Richard Smith3da88fa2013-04-26 14:36:30 +00002168/// Find the designated sub-object of an rvalue.
2169template<typename SubobjectHandler>
2170typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002171findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002172 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002173 if (Sub.Invalid)
2174 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002175 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002176 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002177 if (Info.getLangOpts().CPlusPlus11)
2178 Info.Diag(E, diag::note_constexpr_access_past_end)
2179 << handler.AccessKind;
2180 else
2181 Info.Diag(E);
2182 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002183 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002184
Richard Smith3229b742013-05-05 21:17:10 +00002185 APValue *O = Obj.Value;
2186 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002187 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002188
Richard Smithd62306a2011-11-10 06:34:14 +00002189 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002190 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2191 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002192 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002193 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2194 return handler.failed();
2195 }
2196
Richard Smith49ca8aa2013-08-06 07:09:20 +00002197 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002198 // If we are reading an object of class type, there may still be more
2199 // things we need to check: if there are any mutable subobjects, we
2200 // cannot perform this read. (This only happens when performing a trivial
2201 // copy or assignment.)
2202 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2203 diagnoseUnreadableFields(Info, E, ObjType))
2204 return handler.failed();
2205
Richard Smith49ca8aa2013-08-06 07:09:20 +00002206 if (!handler.found(*O, ObjType))
2207 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002208
Richard Smith49ca8aa2013-08-06 07:09:20 +00002209 // If we modified a bit-field, truncate it to the right width.
2210 if (handler.AccessKind != AK_Read &&
2211 LastField && LastField->isBitField() &&
2212 !truncateBitfieldValue(Info, E, *O, LastField))
2213 return false;
2214
2215 return true;
2216 }
2217
Craig Topper36250ad2014-05-12 05:36:57 +00002218 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002219 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002220 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002221 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002222 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002223 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002224 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002225 // Note, it should not be possible to form a pointer with a valid
2226 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002227 if (Info.getLangOpts().CPlusPlus11)
2228 Info.Diag(E, diag::note_constexpr_access_past_end)
2229 << handler.AccessKind;
2230 else
2231 Info.Diag(E);
2232 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002233 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002234
2235 ObjType = CAT->getElementType();
2236
Richard Smith14a94132012-02-17 03:35:37 +00002237 // An array object is represented as either an Array APValue or as an
2238 // LValue which refers to a string literal.
2239 if (O->isLValue()) {
2240 assert(I == N - 1 && "extracting subobject of character?");
2241 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002242 if (handler.AccessKind != AK_Read)
2243 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2244 *O);
2245 else
2246 return handler.foundString(*O, ObjType, Index);
2247 }
2248
2249 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002250 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002251 else if (handler.AccessKind != AK_Read) {
2252 expandArray(*O, Index);
2253 O = &O->getArrayInitializedElt(Index);
2254 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002255 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002256 } else if (ObjType->isAnyComplexType()) {
2257 // Next subobject is a complex number.
2258 uint64_t Index = Sub.Entries[I].ArrayIndex;
2259 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002260 if (Info.getLangOpts().CPlusPlus11)
2261 Info.Diag(E, diag::note_constexpr_access_past_end)
2262 << handler.AccessKind;
2263 else
2264 Info.Diag(E);
2265 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002266 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002267
2268 bool WasConstQualified = ObjType.isConstQualified();
2269 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2270 if (WasConstQualified)
2271 ObjType.addConst();
2272
Richard Smith66c96992012-02-18 22:04:06 +00002273 assert(I == N - 1 && "extracting subobject of scalar?");
2274 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002275 return handler.found(Index ? O->getComplexIntImag()
2276 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002277 } else {
2278 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002279 return handler.found(Index ? O->getComplexFloatImag()
2280 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002281 }
Richard Smithd62306a2011-11-10 06:34:14 +00002282 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002283 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002284 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002285 << Field;
2286 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002287 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002288 }
2289
Richard Smithd62306a2011-11-10 06:34:14 +00002290 // Next subobject is a class, struct or union field.
2291 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2292 if (RD->isUnion()) {
2293 const FieldDecl *UnionField = O->getUnionField();
2294 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002295 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002296 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2297 << handler.AccessKind << Field << !UnionField << UnionField;
2298 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002299 }
Richard Smithd62306a2011-11-10 06:34:14 +00002300 O = &O->getUnionValue();
2301 } else
2302 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002303
2304 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002305 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002306 if (WasConstQualified && !Field->isMutable())
2307 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002308
2309 if (ObjType.isVolatileQualified()) {
2310 if (Info.getLangOpts().CPlusPlus) {
2311 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002312 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2313 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002314 Info.Note(Field->getLocation(), diag::note_declared_at);
2315 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002316 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002317 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002318 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002319 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002320
2321 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002322 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002323 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002324 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2325 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2326 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002327
2328 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002329 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002330 if (WasConstQualified)
2331 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002332 }
2333 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002334}
2335
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002336namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002337struct ExtractSubobjectHandler {
2338 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002339 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002340
2341 static const AccessKinds AccessKind = AK_Read;
2342
2343 typedef bool result_type;
2344 bool failed() { return false; }
2345 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002346 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002347 return true;
2348 }
2349 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002350 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002351 return true;
2352 }
2353 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002354 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002355 return true;
2356 }
2357 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002358 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002359 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2360 return true;
2361 }
2362};
Richard Smith3229b742013-05-05 21:17:10 +00002363} // end anonymous namespace
2364
Richard Smith3da88fa2013-04-26 14:36:30 +00002365const AccessKinds ExtractSubobjectHandler::AccessKind;
2366
2367/// Extract the designated sub-object of an rvalue.
2368static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002369 const CompleteObject &Obj,
2370 const SubobjectDesignator &Sub,
2371 APValue &Result) {
2372 ExtractSubobjectHandler Handler = { Info, Result };
2373 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002374}
2375
Richard Smith3229b742013-05-05 21:17:10 +00002376namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002377struct ModifySubobjectHandler {
2378 EvalInfo &Info;
2379 APValue &NewVal;
2380 const Expr *E;
2381
2382 typedef bool result_type;
2383 static const AccessKinds AccessKind = AK_Assign;
2384
2385 bool checkConst(QualType QT) {
2386 // Assigning to a const object has undefined behavior.
2387 if (QT.isConstQualified()) {
2388 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2389 return false;
2390 }
2391 return true;
2392 }
2393
2394 bool failed() { return false; }
2395 bool found(APValue &Subobj, QualType SubobjType) {
2396 if (!checkConst(SubobjType))
2397 return false;
2398 // We've been given ownership of NewVal, so just swap it in.
2399 Subobj.swap(NewVal);
2400 return true;
2401 }
2402 bool found(APSInt &Value, QualType SubobjType) {
2403 if (!checkConst(SubobjType))
2404 return false;
2405 if (!NewVal.isInt()) {
2406 // Maybe trying to write a cast pointer value into a complex?
2407 Info.Diag(E);
2408 return false;
2409 }
2410 Value = NewVal.getInt();
2411 return true;
2412 }
2413 bool found(APFloat &Value, QualType SubobjType) {
2414 if (!checkConst(SubobjType))
2415 return false;
2416 Value = NewVal.getFloat();
2417 return true;
2418 }
2419 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2420 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2421 }
2422};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002423} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002424
Richard Smith3229b742013-05-05 21:17:10 +00002425const AccessKinds ModifySubobjectHandler::AccessKind;
2426
Richard Smith3da88fa2013-04-26 14:36:30 +00002427/// Update the designated sub-object of an rvalue to the given value.
2428static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002429 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002430 const SubobjectDesignator &Sub,
2431 APValue &NewVal) {
2432 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002433 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002434}
2435
Richard Smith84f6dcf2012-02-02 01:16:57 +00002436/// Find the position where two subobject designators diverge, or equivalently
2437/// the length of the common initial subsequence.
2438static unsigned FindDesignatorMismatch(QualType ObjType,
2439 const SubobjectDesignator &A,
2440 const SubobjectDesignator &B,
2441 bool &WasArrayIndex) {
2442 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2443 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002444 if (!ObjType.isNull() &&
2445 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002446 // Next subobject is an array element.
2447 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2448 WasArrayIndex = true;
2449 return I;
2450 }
Richard Smith66c96992012-02-18 22:04:06 +00002451 if (ObjType->isAnyComplexType())
2452 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2453 else
2454 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002455 } else {
2456 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2457 WasArrayIndex = false;
2458 return I;
2459 }
2460 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2461 // Next subobject is a field.
2462 ObjType = FD->getType();
2463 else
2464 // Next subobject is a base class.
2465 ObjType = QualType();
2466 }
2467 }
2468 WasArrayIndex = false;
2469 return I;
2470}
2471
2472/// Determine whether the given subobject designators refer to elements of the
2473/// same array object.
2474static bool AreElementsOfSameArray(QualType ObjType,
2475 const SubobjectDesignator &A,
2476 const SubobjectDesignator &B) {
2477 if (A.Entries.size() != B.Entries.size())
2478 return false;
2479
2480 bool IsArray = A.MostDerivedArraySize != 0;
2481 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2482 // A is a subobject of the array element.
2483 return false;
2484
2485 // If A (and B) designates an array element, the last entry will be the array
2486 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2487 // of length 1' case, and the entire path must match.
2488 bool WasArrayIndex;
2489 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2490 return CommonLength >= A.Entries.size() - IsArray;
2491}
2492
Richard Smith3229b742013-05-05 21:17:10 +00002493/// Find the complete object to which an LValue refers.
2494CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2495 const LValue &LVal, QualType LValType) {
2496 if (!LVal.Base) {
2497 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2498 return CompleteObject();
2499 }
2500
Craig Topper36250ad2014-05-12 05:36:57 +00002501 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002502 if (LVal.CallIndex) {
2503 Frame = Info.getCallFrame(LVal.CallIndex);
2504 if (!Frame) {
2505 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2506 << AK << LVal.Base.is<const ValueDecl*>();
2507 NoteLValueLocation(Info, LVal.Base);
2508 return CompleteObject();
2509 }
Richard Smith3229b742013-05-05 21:17:10 +00002510 }
2511
2512 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2513 // is not a constant expression (even if the object is non-volatile). We also
2514 // apply this rule to C++98, in order to conform to the expected 'volatile'
2515 // semantics.
2516 if (LValType.isVolatileQualified()) {
2517 if (Info.getLangOpts().CPlusPlus)
2518 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2519 << AK << LValType;
2520 else
2521 Info.Diag(E);
2522 return CompleteObject();
2523 }
2524
2525 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002526 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002527 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002528
2529 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2530 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2531 // In C++11, constexpr, non-volatile variables initialized with constant
2532 // expressions are constant expressions too. Inside constexpr functions,
2533 // parameters are constant expressions even if they're non-const.
2534 // In C++1y, objects local to a constant expression (those with a Frame) are
2535 // both readable and writable inside constant expressions.
2536 // In C, such things can also be folded, although they are not ICEs.
2537 const VarDecl *VD = dyn_cast<VarDecl>(D);
2538 if (VD) {
2539 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2540 VD = VDef;
2541 }
2542 if (!VD || VD->isInvalidDecl()) {
2543 Info.Diag(E);
2544 return CompleteObject();
2545 }
2546
2547 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002548 if (BaseType.isVolatileQualified()) {
2549 if (Info.getLangOpts().CPlusPlus) {
2550 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2551 << AK << 1 << VD;
2552 Info.Note(VD->getLocation(), diag::note_declared_at);
2553 } else {
2554 Info.Diag(E);
2555 }
2556 return CompleteObject();
2557 }
2558
2559 // Unless we're looking at a local variable or argument in a constexpr call,
2560 // the variable we're reading must be const.
2561 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002562 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002563 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2564 // OK, we can read and modify an object if we're in the process of
2565 // evaluating its initializer, because its lifetime began in this
2566 // evaluation.
2567 } else if (AK != AK_Read) {
2568 // All the remaining cases only permit reading.
2569 Info.Diag(E, diag::note_constexpr_modify_global);
2570 return CompleteObject();
2571 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002572 // OK, we can read this variable.
2573 } else if (BaseType->isIntegralOrEnumerationType()) {
2574 if (!BaseType.isConstQualified()) {
2575 if (Info.getLangOpts().CPlusPlus) {
2576 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2577 Info.Note(VD->getLocation(), diag::note_declared_at);
2578 } else {
2579 Info.Diag(E);
2580 }
2581 return CompleteObject();
2582 }
2583 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2584 // We support folding of const floating-point types, in order to make
2585 // static const data members of such types (supported as an extension)
2586 // more useful.
2587 if (Info.getLangOpts().CPlusPlus11) {
2588 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2589 Info.Note(VD->getLocation(), diag::note_declared_at);
2590 } else {
2591 Info.CCEDiag(E);
2592 }
2593 } else {
2594 // FIXME: Allow folding of values of any literal type in all languages.
2595 if (Info.getLangOpts().CPlusPlus11) {
2596 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2597 Info.Note(VD->getLocation(), diag::note_declared_at);
2598 } else {
2599 Info.Diag(E);
2600 }
2601 return CompleteObject();
2602 }
2603 }
2604
2605 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2606 return CompleteObject();
2607 } else {
2608 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2609
2610 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002611 if (const MaterializeTemporaryExpr *MTE =
2612 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2613 assert(MTE->getStorageDuration() == SD_Static &&
2614 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002615
Richard Smithe6c01442013-06-05 00:46:14 +00002616 // Per C++1y [expr.const]p2:
2617 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2618 // - a [...] glvalue of integral or enumeration type that refers to
2619 // a non-volatile const object [...]
2620 // [...]
2621 // - a [...] glvalue of literal type that refers to a non-volatile
2622 // object whose lifetime began within the evaluation of e.
2623 //
2624 // C++11 misses the 'began within the evaluation of e' check and
2625 // instead allows all temporaries, including things like:
2626 // int &&r = 1;
2627 // int x = ++r;
2628 // constexpr int k = r;
2629 // Therefore we use the C++1y rules in C++11 too.
2630 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2631 const ValueDecl *ED = MTE->getExtendingDecl();
2632 if (!(BaseType.isConstQualified() &&
2633 BaseType->isIntegralOrEnumerationType()) &&
2634 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2635 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2636 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2637 return CompleteObject();
2638 }
2639
2640 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2641 assert(BaseVal && "got reference to unevaluated temporary");
2642 } else {
2643 Info.Diag(E);
2644 return CompleteObject();
2645 }
2646 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002647 BaseVal = Frame->getTemporary(Base);
2648 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002649 }
Richard Smith3229b742013-05-05 21:17:10 +00002650
2651 // Volatile temporary objects cannot be accessed in constant expressions.
2652 if (BaseType.isVolatileQualified()) {
2653 if (Info.getLangOpts().CPlusPlus) {
2654 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2655 << AK << 0;
2656 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2657 } else {
2658 Info.Diag(E);
2659 }
2660 return CompleteObject();
2661 }
2662 }
2663
Richard Smith7525ff62013-05-09 07:14:00 +00002664 // During the construction of an object, it is not yet 'const'.
2665 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2666 // and this doesn't do quite the right thing for const subobjects of the
2667 // object under construction.
2668 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2669 BaseType = Info.Ctx.getCanonicalType(BaseType);
2670 BaseType.removeLocalConst();
2671 }
2672
Richard Smith6d4c6582013-11-05 22:18:15 +00002673 // In C++1y, we can't safely access any mutable state when we might be
2674 // evaluating after an unmodeled side effect or an evaluation failure.
2675 //
2676 // FIXME: Not all local state is mutable. Allow local constant subobjects
2677 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002678 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002679 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002680 return CompleteObject();
2681
2682 return CompleteObject(BaseVal, BaseType);
2683}
2684
Richard Smith243ef902013-05-05 23:31:59 +00002685/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2686/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2687/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002688///
2689/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002690/// \param Conv - The expression for which we are performing the conversion.
2691/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002692/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2693/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002694/// \param LVal - The glvalue on which we are attempting to perform this action.
2695/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002696static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002697 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002698 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002699 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002700 return false;
2701
Richard Smith3229b742013-05-05 21:17:10 +00002702 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002703 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002704 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2705 !Type.isVolatileQualified()) {
2706 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2707 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2708 // initializer until now for such expressions. Such an expression can't be
2709 // an ICE in C, so this only matters for fold.
2710 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2711 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002712 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002713 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002714 }
Richard Smith3229b742013-05-05 21:17:10 +00002715 APValue Lit;
2716 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2717 return false;
2718 CompleteObject LitObj(&Lit, Base->getType());
2719 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002720 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002721 // We represent a string literal array as an lvalue pointing at the
2722 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002723 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002724 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2725 CompleteObject StrObj(&Str, Base->getType());
2726 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002727 }
Richard Smith11562c52011-10-28 17:51:58 +00002728 }
2729
Richard Smith3229b742013-05-05 21:17:10 +00002730 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2731 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002732}
2733
2734/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002735static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002736 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002737 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002738 return false;
2739
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002740 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002741 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002742 return false;
2743 }
2744
Richard Smith3229b742013-05-05 21:17:10 +00002745 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2746 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002747}
2748
Richard Smith243ef902013-05-05 23:31:59 +00002749static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2750 return T->isSignedIntegerType() &&
2751 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2752}
2753
2754namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002755struct CompoundAssignSubobjectHandler {
2756 EvalInfo &Info;
2757 const Expr *E;
2758 QualType PromotedLHSType;
2759 BinaryOperatorKind Opcode;
2760 const APValue &RHS;
2761
2762 static const AccessKinds AccessKind = AK_Assign;
2763
2764 typedef bool result_type;
2765
2766 bool checkConst(QualType QT) {
2767 // Assigning to a const object has undefined behavior.
2768 if (QT.isConstQualified()) {
2769 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2770 return false;
2771 }
2772 return true;
2773 }
2774
2775 bool failed() { return false; }
2776 bool found(APValue &Subobj, QualType SubobjType) {
2777 switch (Subobj.getKind()) {
2778 case APValue::Int:
2779 return found(Subobj.getInt(), SubobjType);
2780 case APValue::Float:
2781 return found(Subobj.getFloat(), SubobjType);
2782 case APValue::ComplexInt:
2783 case APValue::ComplexFloat:
2784 // FIXME: Implement complex compound assignment.
2785 Info.Diag(E);
2786 return false;
2787 case APValue::LValue:
2788 return foundPointer(Subobj, SubobjType);
2789 default:
2790 // FIXME: can this happen?
2791 Info.Diag(E);
2792 return false;
2793 }
2794 }
2795 bool found(APSInt &Value, QualType SubobjType) {
2796 if (!checkConst(SubobjType))
2797 return false;
2798
2799 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2800 // We don't support compound assignment on integer-cast-to-pointer
2801 // values.
2802 Info.Diag(E);
2803 return false;
2804 }
2805
2806 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2807 SubobjType, Value);
2808 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2809 return false;
2810 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2811 return true;
2812 }
2813 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002814 return checkConst(SubobjType) &&
2815 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2816 Value) &&
2817 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2818 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002819 }
2820 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2821 if (!checkConst(SubobjType))
2822 return false;
2823
2824 QualType PointeeType;
2825 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2826 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002827
2828 if (PointeeType.isNull() || !RHS.isInt() ||
2829 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002830 Info.Diag(E);
2831 return false;
2832 }
2833
Richard Smith861b5b52013-05-07 23:34:45 +00002834 int64_t Offset = getExtValue(RHS.getInt());
2835 if (Opcode == BO_Sub)
2836 Offset = -Offset;
2837
2838 LValue LVal;
2839 LVal.setFrom(Info.Ctx, Subobj);
2840 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2841 return false;
2842 LVal.moveInto(Subobj);
2843 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002844 }
2845 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2846 llvm_unreachable("shouldn't encounter string elements here");
2847 }
2848};
2849} // end anonymous namespace
2850
2851const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2852
2853/// Perform a compound assignment of LVal <op>= RVal.
2854static bool handleCompoundAssignment(
2855 EvalInfo &Info, const Expr *E,
2856 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2857 BinaryOperatorKind Opcode, const APValue &RVal) {
2858 if (LVal.Designator.Invalid)
2859 return false;
2860
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002861 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002862 Info.Diag(E);
2863 return false;
2864 }
2865
2866 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2867 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2868 RVal };
2869 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2870}
2871
2872namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002873struct IncDecSubobjectHandler {
2874 EvalInfo &Info;
2875 const Expr *E;
2876 AccessKinds AccessKind;
2877 APValue *Old;
2878
2879 typedef bool result_type;
2880
2881 bool checkConst(QualType QT) {
2882 // Assigning to a const object has undefined behavior.
2883 if (QT.isConstQualified()) {
2884 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2885 return false;
2886 }
2887 return true;
2888 }
2889
2890 bool failed() { return false; }
2891 bool found(APValue &Subobj, QualType SubobjType) {
2892 // Stash the old value. Also clear Old, so we don't clobber it later
2893 // if we're post-incrementing a complex.
2894 if (Old) {
2895 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002896 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002897 }
2898
2899 switch (Subobj.getKind()) {
2900 case APValue::Int:
2901 return found(Subobj.getInt(), SubobjType);
2902 case APValue::Float:
2903 return found(Subobj.getFloat(), SubobjType);
2904 case APValue::ComplexInt:
2905 return found(Subobj.getComplexIntReal(),
2906 SubobjType->castAs<ComplexType>()->getElementType()
2907 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2908 case APValue::ComplexFloat:
2909 return found(Subobj.getComplexFloatReal(),
2910 SubobjType->castAs<ComplexType>()->getElementType()
2911 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2912 case APValue::LValue:
2913 return foundPointer(Subobj, SubobjType);
2914 default:
2915 // FIXME: can this happen?
2916 Info.Diag(E);
2917 return false;
2918 }
2919 }
2920 bool found(APSInt &Value, QualType SubobjType) {
2921 if (!checkConst(SubobjType))
2922 return false;
2923
2924 if (!SubobjType->isIntegerType()) {
2925 // We don't support increment / decrement on integer-cast-to-pointer
2926 // values.
2927 Info.Diag(E);
2928 return false;
2929 }
2930
2931 if (Old) *Old = APValue(Value);
2932
2933 // bool arithmetic promotes to int, and the conversion back to bool
2934 // doesn't reduce mod 2^n, so special-case it.
2935 if (SubobjType->isBooleanType()) {
2936 if (AccessKind == AK_Increment)
2937 Value = 1;
2938 else
2939 Value = !Value;
2940 return true;
2941 }
2942
2943 bool WasNegative = Value.isNegative();
2944 if (AccessKind == AK_Increment) {
2945 ++Value;
2946
2947 if (!WasNegative && Value.isNegative() &&
2948 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2949 APSInt ActualValue(Value, /*IsUnsigned*/true);
2950 HandleOverflow(Info, E, ActualValue, SubobjType);
2951 }
2952 } else {
2953 --Value;
2954
2955 if (WasNegative && !Value.isNegative() &&
2956 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2957 unsigned BitWidth = Value.getBitWidth();
2958 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2959 ActualValue.setBit(BitWidth);
2960 HandleOverflow(Info, E, ActualValue, SubobjType);
2961 }
2962 }
2963 return true;
2964 }
2965 bool found(APFloat &Value, QualType SubobjType) {
2966 if (!checkConst(SubobjType))
2967 return false;
2968
2969 if (Old) *Old = APValue(Value);
2970
2971 APFloat One(Value.getSemantics(), 1);
2972 if (AccessKind == AK_Increment)
2973 Value.add(One, APFloat::rmNearestTiesToEven);
2974 else
2975 Value.subtract(One, APFloat::rmNearestTiesToEven);
2976 return true;
2977 }
2978 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2979 if (!checkConst(SubobjType))
2980 return false;
2981
2982 QualType PointeeType;
2983 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2984 PointeeType = PT->getPointeeType();
2985 else {
2986 Info.Diag(E);
2987 return false;
2988 }
2989
2990 LValue LVal;
2991 LVal.setFrom(Info.Ctx, Subobj);
2992 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2993 AccessKind == AK_Increment ? 1 : -1))
2994 return false;
2995 LVal.moveInto(Subobj);
2996 return true;
2997 }
2998 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2999 llvm_unreachable("shouldn't encounter string elements here");
3000 }
3001};
3002} // end anonymous namespace
3003
3004/// Perform an increment or decrement on LVal.
3005static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3006 QualType LValType, bool IsIncrement, APValue *Old) {
3007 if (LVal.Designator.Invalid)
3008 return false;
3009
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003010 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003011 Info.Diag(E);
3012 return false;
3013 }
3014
3015 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3016 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3017 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3018 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3019}
3020
Richard Smithe97cbd72011-11-11 04:05:33 +00003021/// Build an lvalue for the object argument of a member function call.
3022static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3023 LValue &This) {
3024 if (Object->getType()->isPointerType())
3025 return EvaluatePointer(Object, This, Info);
3026
3027 if (Object->isGLValue())
3028 return EvaluateLValue(Object, This, Info);
3029
Richard Smithd9f663b2013-04-22 15:31:51 +00003030 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003031 return EvaluateTemporary(Object, This, Info);
3032
Richard Smith3e79a572014-06-11 19:53:12 +00003033 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003034 return false;
3035}
3036
3037/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3038/// lvalue referring to the result.
3039///
3040/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003041/// \param LV - An lvalue referring to the base of the member pointer.
3042/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003043/// \param IncludeMember - Specifies whether the member itself is included in
3044/// the resulting LValue subobject designator. This is not possible when
3045/// creating a bound member function.
3046/// \return The field or method declaration to which the member pointer refers,
3047/// or 0 if evaluation fails.
3048static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003049 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003050 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003051 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003052 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003053 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003054 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003055 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003056
3057 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3058 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003059 if (!MemPtr.getDecl()) {
3060 // FIXME: Specific diagnostic.
3061 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003062 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003063 }
Richard Smith253c2a32012-01-27 01:14:48 +00003064
Richard Smith027bf112011-11-17 22:56:20 +00003065 if (MemPtr.isDerivedMember()) {
3066 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003067 // The end of the derived-to-base path for the base object must match the
3068 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003069 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003070 LV.Designator.Entries.size()) {
3071 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003072 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003073 }
Richard Smith027bf112011-11-17 22:56:20 +00003074 unsigned PathLengthToMember =
3075 LV.Designator.Entries.size() - MemPtr.Path.size();
3076 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3077 const CXXRecordDecl *LVDecl = getAsBaseClass(
3078 LV.Designator.Entries[PathLengthToMember + I]);
3079 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003080 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3081 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003082 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003083 }
Richard Smith027bf112011-11-17 22:56:20 +00003084 }
3085
3086 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003087 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003088 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003089 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003090 } else if (!MemPtr.Path.empty()) {
3091 // Extend the LValue path with the member pointer's path.
3092 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3093 MemPtr.Path.size() + IncludeMember);
3094
3095 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003096 if (const PointerType *PT = LVType->getAs<PointerType>())
3097 LVType = PT->getPointeeType();
3098 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3099 assert(RD && "member pointer access on non-class-type expression");
3100 // The first class in the path is that of the lvalue.
3101 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3102 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003103 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003104 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003105 RD = Base;
3106 }
3107 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003108 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3109 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003110 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003111 }
3112
3113 // Add the member. Note that we cannot build bound member functions here.
3114 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003115 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003116 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003117 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003118 } else if (const IndirectFieldDecl *IFD =
3119 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003120 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003121 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003122 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003123 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003124 }
Richard Smith027bf112011-11-17 22:56:20 +00003125 }
3126
3127 return MemPtr.getDecl();
3128}
3129
Richard Smith84401042013-06-03 05:03:02 +00003130static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3131 const BinaryOperator *BO,
3132 LValue &LV,
3133 bool IncludeMember = true) {
3134 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3135
3136 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3137 if (Info.keepEvaluatingAfterFailure()) {
3138 MemberPtr MemPtr;
3139 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3140 }
Craig Topper36250ad2014-05-12 05:36:57 +00003141 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003142 }
3143
3144 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3145 BO->getRHS(), IncludeMember);
3146}
3147
Richard Smith027bf112011-11-17 22:56:20 +00003148/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3149/// the provided lvalue, which currently refers to the base object.
3150static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3151 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003152 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003153 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003154 return false;
3155
Richard Smitha8105bc2012-01-06 16:39:00 +00003156 QualType TargetQT = E->getType();
3157 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3158 TargetQT = PT->getPointeeType();
3159
3160 // Check this cast lands within the final derived-to-base subobject path.
3161 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003162 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003163 << D.MostDerivedType << TargetQT;
3164 return false;
3165 }
3166
Richard Smith027bf112011-11-17 22:56:20 +00003167 // Check the type of the final cast. We don't need to check the path,
3168 // since a cast can only be formed if the path is unique.
3169 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003170 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3171 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003172 if (NewEntriesSize == D.MostDerivedPathLength)
3173 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3174 else
Richard Smith027bf112011-11-17 22:56:20 +00003175 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003176 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003177 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003178 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003179 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003180 }
Richard Smith027bf112011-11-17 22:56:20 +00003181
3182 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003183 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003184}
3185
Mike Stump876387b2009-10-27 22:09:17 +00003186namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003187enum EvalStmtResult {
3188 /// Evaluation failed.
3189 ESR_Failed,
3190 /// Hit a 'return' statement.
3191 ESR_Returned,
3192 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003193 ESR_Succeeded,
3194 /// Hit a 'continue' statement.
3195 ESR_Continue,
3196 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003197 ESR_Break,
3198 /// Still scanning for 'case' or 'default' statement.
3199 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003200};
3201}
3202
Richard Smithd9f663b2013-04-22 15:31:51 +00003203static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3204 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3205 // We don't need to evaluate the initializer for a static local.
3206 if (!VD->hasLocalStorage())
3207 return true;
3208
3209 LValue Result;
3210 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003211 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003212
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003213 const Expr *InitE = VD->getInit();
3214 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003215 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3216 << false << VD->getType();
3217 Val = APValue();
3218 return false;
3219 }
3220
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003221 if (InitE->isValueDependent())
3222 return false;
3223
3224 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003225 // Wipe out any partially-computed value, to allow tracking that this
3226 // evaluation failed.
3227 Val = APValue();
3228 return false;
3229 }
3230 }
3231
3232 return true;
3233}
3234
Richard Smith4e18ca52013-05-06 05:56:11 +00003235/// Evaluate a condition (either a variable declaration or an expression).
3236static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3237 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003238 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003239 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3240 return false;
3241 return EvaluateAsBooleanCondition(Cond, Result, Info);
3242}
3243
3244static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003245 const Stmt *S,
3246 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003247
3248/// Evaluate the body of a loop, and translate the result as appropriate.
3249static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003250 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003251 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003252 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003253 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003254 case ESR_Break:
3255 return ESR_Succeeded;
3256 case ESR_Succeeded:
3257 case ESR_Continue:
3258 return ESR_Continue;
3259 case ESR_Failed:
3260 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003261 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003262 return ESR;
3263 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003264 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003265}
3266
Richard Smith496ddcf2013-05-12 17:32:42 +00003267/// Evaluate a switch statement.
3268static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3269 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003270 BlockScopeRAII Scope(Info);
3271
Richard Smith496ddcf2013-05-12 17:32:42 +00003272 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003273 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003274 {
3275 FullExpressionRAII Scope(Info);
3276 if (SS->getConditionVariable() &&
3277 !EvaluateDecl(Info, SS->getConditionVariable()))
3278 return ESR_Failed;
3279 if (!EvaluateInteger(SS->getCond(), Value, Info))
3280 return ESR_Failed;
3281 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003282
3283 // Find the switch case corresponding to the value of the condition.
3284 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003285 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003286 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3287 SC = SC->getNextSwitchCase()) {
3288 if (isa<DefaultStmt>(SC)) {
3289 Found = SC;
3290 continue;
3291 }
3292
3293 const CaseStmt *CS = cast<CaseStmt>(SC);
3294 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3295 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3296 : LHS;
3297 if (LHS <= Value && Value <= RHS) {
3298 Found = SC;
3299 break;
3300 }
3301 }
3302
3303 if (!Found)
3304 return ESR_Succeeded;
3305
3306 // Search the switch body for the switch case and evaluate it from there.
3307 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3308 case ESR_Break:
3309 return ESR_Succeeded;
3310 case ESR_Succeeded:
3311 case ESR_Continue:
3312 case ESR_Failed:
3313 case ESR_Returned:
3314 return ESR;
3315 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003316 // This can only happen if the switch case is nested within a statement
3317 // expression. We have no intention of supporting that.
3318 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3319 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003320 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003321 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003322}
3323
Richard Smith254a73d2011-10-28 22:34:42 +00003324// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003325static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003326 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003327 if (!Info.nextStep(S))
3328 return ESR_Failed;
3329
Richard Smith496ddcf2013-05-12 17:32:42 +00003330 // If we're hunting down a 'case' or 'default' label, recurse through
3331 // substatements until we hit the label.
3332 if (Case) {
3333 // FIXME: We don't start the lifetime of objects whose initialization we
3334 // jump over. However, such objects must be of class type with a trivial
3335 // default constructor that initialize all subobjects, so must be empty,
3336 // so this almost never matters.
3337 switch (S->getStmtClass()) {
3338 case Stmt::CompoundStmtClass:
3339 // FIXME: Precompute which substatement of a compound statement we
3340 // would jump to, and go straight there rather than performing a
3341 // linear scan each time.
3342 case Stmt::LabelStmtClass:
3343 case Stmt::AttributedStmtClass:
3344 case Stmt::DoStmtClass:
3345 break;
3346
3347 case Stmt::CaseStmtClass:
3348 case Stmt::DefaultStmtClass:
3349 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003350 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003351 break;
3352
3353 case Stmt::IfStmtClass: {
3354 // FIXME: Precompute which side of an 'if' we would jump to, and go
3355 // straight there rather than scanning both sides.
3356 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003357
3358 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3359 // preceded by our switch label.
3360 BlockScopeRAII Scope(Info);
3361
Richard Smith496ddcf2013-05-12 17:32:42 +00003362 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3363 if (ESR != ESR_CaseNotFound || !IS->getElse())
3364 return ESR;
3365 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3366 }
3367
3368 case Stmt::WhileStmtClass: {
3369 EvalStmtResult ESR =
3370 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3371 if (ESR != ESR_Continue)
3372 return ESR;
3373 break;
3374 }
3375
3376 case Stmt::ForStmtClass: {
3377 const ForStmt *FS = cast<ForStmt>(S);
3378 EvalStmtResult ESR =
3379 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3380 if (ESR != ESR_Continue)
3381 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003382 if (FS->getInc()) {
3383 FullExpressionRAII IncScope(Info);
3384 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3385 return ESR_Failed;
3386 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003387 break;
3388 }
3389
3390 case Stmt::DeclStmtClass:
3391 // FIXME: If the variable has initialization that can't be jumped over,
3392 // bail out of any immediately-surrounding compound-statement too.
3393 default:
3394 return ESR_CaseNotFound;
3395 }
3396 }
3397
Richard Smith254a73d2011-10-28 22:34:42 +00003398 switch (S->getStmtClass()) {
3399 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003400 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003401 // Don't bother evaluating beyond an expression-statement which couldn't
3402 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003403 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003404 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003405 return ESR_Failed;
3406 return ESR_Succeeded;
3407 }
3408
3409 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003410 return ESR_Failed;
3411
3412 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003413 return ESR_Succeeded;
3414
Richard Smithd9f663b2013-04-22 15:31:51 +00003415 case Stmt::DeclStmtClass: {
3416 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003417 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003418 // Each declaration initialization is its own full-expression.
3419 // FIXME: This isn't quite right; if we're performing aggregate
3420 // initialization, each braced subexpression is its own full-expression.
3421 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003422 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003423 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003424 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003425 return ESR_Succeeded;
3426 }
3427
Richard Smith357362d2011-12-13 06:39:58 +00003428 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003429 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003430 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003431 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003432 return ESR_Failed;
3433 return ESR_Returned;
3434 }
Richard Smith254a73d2011-10-28 22:34:42 +00003435
3436 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003437 BlockScopeRAII Scope(Info);
3438
Richard Smith254a73d2011-10-28 22:34:42 +00003439 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003440 for (const auto *BI : CS->body()) {
3441 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003442 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003443 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003444 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003445 return ESR;
3446 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003447 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003448 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003449
3450 case Stmt::IfStmtClass: {
3451 const IfStmt *IS = cast<IfStmt>(S);
3452
3453 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003454 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003455 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003456 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003457 return ESR_Failed;
3458
3459 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3460 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3461 if (ESR != ESR_Succeeded)
3462 return ESR;
3463 }
3464 return ESR_Succeeded;
3465 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003466
3467 case Stmt::WhileStmtClass: {
3468 const WhileStmt *WS = cast<WhileStmt>(S);
3469 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003470 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003471 bool Continue;
3472 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3473 Continue))
3474 return ESR_Failed;
3475 if (!Continue)
3476 break;
3477
3478 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3479 if (ESR != ESR_Continue)
3480 return ESR;
3481 }
3482 return ESR_Succeeded;
3483 }
3484
3485 case Stmt::DoStmtClass: {
3486 const DoStmt *DS = cast<DoStmt>(S);
3487 bool Continue;
3488 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003489 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003490 if (ESR != ESR_Continue)
3491 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003492 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003493
Richard Smith08d6a2c2013-07-24 07:11:57 +00003494 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003495 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3496 return ESR_Failed;
3497 } while (Continue);
3498 return ESR_Succeeded;
3499 }
3500
3501 case Stmt::ForStmtClass: {
3502 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003503 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003504 if (FS->getInit()) {
3505 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3506 if (ESR != ESR_Succeeded)
3507 return ESR;
3508 }
3509 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003510 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003511 bool Continue = true;
3512 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3513 FS->getCond(), Continue))
3514 return ESR_Failed;
3515 if (!Continue)
3516 break;
3517
3518 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3519 if (ESR != ESR_Continue)
3520 return ESR;
3521
Richard Smith08d6a2c2013-07-24 07:11:57 +00003522 if (FS->getInc()) {
3523 FullExpressionRAII IncScope(Info);
3524 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3525 return ESR_Failed;
3526 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003527 }
3528 return ESR_Succeeded;
3529 }
3530
Richard Smith896e0d72013-05-06 06:51:17 +00003531 case Stmt::CXXForRangeStmtClass: {
3532 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003533 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003534
3535 // Initialize the __range variable.
3536 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3537 if (ESR != ESR_Succeeded)
3538 return ESR;
3539
3540 // Create the __begin and __end iterators.
3541 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3542 if (ESR != ESR_Succeeded)
3543 return ESR;
3544
3545 while (true) {
3546 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003547 {
3548 bool Continue = true;
3549 FullExpressionRAII CondExpr(Info);
3550 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3551 return ESR_Failed;
3552 if (!Continue)
3553 break;
3554 }
Richard Smith896e0d72013-05-06 06:51:17 +00003555
3556 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003557 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003558 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3559 if (ESR != ESR_Succeeded)
3560 return ESR;
3561
3562 // Loop body.
3563 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3564 if (ESR != ESR_Continue)
3565 return ESR;
3566
3567 // Increment: ++__begin
3568 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3569 return ESR_Failed;
3570 }
3571
3572 return ESR_Succeeded;
3573 }
3574
Richard Smith496ddcf2013-05-12 17:32:42 +00003575 case Stmt::SwitchStmtClass:
3576 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3577
Richard Smith4e18ca52013-05-06 05:56:11 +00003578 case Stmt::ContinueStmtClass:
3579 return ESR_Continue;
3580
3581 case Stmt::BreakStmtClass:
3582 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003583
3584 case Stmt::LabelStmtClass:
3585 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3586
3587 case Stmt::AttributedStmtClass:
3588 // As a general principle, C++11 attributes can be ignored without
3589 // any semantic impact.
3590 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3591 Case);
3592
3593 case Stmt::CaseStmtClass:
3594 case Stmt::DefaultStmtClass:
3595 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003596 }
3597}
3598
Richard Smithcc36f692011-12-22 02:22:31 +00003599/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3600/// default constructor. If so, we'll fold it whether or not it's marked as
3601/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3602/// so we need special handling.
3603static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003604 const CXXConstructorDecl *CD,
3605 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003606 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3607 return false;
3608
Richard Smith66e05fe2012-01-18 05:21:49 +00003609 // Value-initialization does not call a trivial default constructor, so such a
3610 // call is a core constant expression whether or not the constructor is
3611 // constexpr.
3612 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003613 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003614 // FIXME: If DiagDecl is an implicitly-declared special member function,
3615 // we should be much more explicit about why it's not constexpr.
3616 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3617 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3618 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003619 } else {
3620 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3621 }
3622 }
3623 return true;
3624}
3625
Richard Smith357362d2011-12-13 06:39:58 +00003626/// CheckConstexprFunction - Check that a function can be called in a constant
3627/// expression.
3628static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3629 const FunctionDecl *Declaration,
3630 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003631 // Potential constant expressions can contain calls to declared, but not yet
3632 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003633 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003634 Declaration->isConstexpr())
3635 return false;
3636
Richard Smith0838f3a2013-05-14 05:18:44 +00003637 // Bail out with no diagnostic if the function declaration itself is invalid.
3638 // We will have produced a relevant diagnostic while parsing it.
3639 if (Declaration->isInvalidDecl())
3640 return false;
3641
Richard Smith357362d2011-12-13 06:39:58 +00003642 // Can we evaluate this function call?
3643 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3644 return true;
3645
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003646 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003647 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003648 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3649 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003650 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3651 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3652 << DiagDecl;
3653 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3654 } else {
3655 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3656 }
3657 return false;
3658}
3659
Richard Smithd62306a2011-11-10 06:34:14 +00003660namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003661typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003662}
3663
3664/// EvaluateArgs - Evaluate the arguments to a function call.
3665static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3666 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003667 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003668 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003669 I != E; ++I) {
3670 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3671 // If we're checking for a potential constant expression, evaluate all
3672 // initializers even if some of them fail.
3673 if (!Info.keepEvaluatingAfterFailure())
3674 return false;
3675 Success = false;
3676 }
3677 }
3678 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003679}
3680
Richard Smith254a73d2011-10-28 22:34:42 +00003681/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003682static bool HandleFunctionCall(SourceLocation CallLoc,
3683 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003684 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003685 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003686 ArgVector ArgValues(Args.size());
3687 if (!EvaluateArgs(Args, ArgValues, Info))
3688 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003689
Richard Smith253c2a32012-01-27 01:14:48 +00003690 if (!Info.CheckCallLimit(CallLoc))
3691 return false;
3692
3693 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003694
3695 // For a trivial copy or move assignment, perform an APValue copy. This is
3696 // essential for unions, where the operations performed by the assignment
3697 // operator cannot be represented as statements.
3698 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3699 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3700 assert(This &&
3701 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3702 LValue RHS;
3703 RHS.setFrom(Info.Ctx, ArgValues[0]);
3704 APValue RHSValue;
3705 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3706 RHS, RHSValue))
3707 return false;
3708 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3709 RHSValue))
3710 return false;
3711 This->moveInto(Result);
3712 return true;
3713 }
3714
Richard Smithd9f663b2013-04-22 15:31:51 +00003715 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003716 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003717 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003718 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003719 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003720 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003721 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003722}
3723
Richard Smithd62306a2011-11-10 06:34:14 +00003724/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003725static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003726 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003727 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003728 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003729 ArgVector ArgValues(Args.size());
3730 if (!EvaluateArgs(Args, ArgValues, Info))
3731 return false;
3732
Richard Smith253c2a32012-01-27 01:14:48 +00003733 if (!Info.CheckCallLimit(CallLoc))
3734 return false;
3735
Richard Smith3607ffe2012-02-13 03:54:03 +00003736 const CXXRecordDecl *RD = Definition->getParent();
3737 if (RD->getNumVBases()) {
3738 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3739 return false;
3740 }
3741
Richard Smith253c2a32012-01-27 01:14:48 +00003742 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003743
3744 // If it's a delegating constructor, just delegate.
3745 if (Definition->isDelegatingConstructor()) {
3746 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003747 {
3748 FullExpressionRAII InitScope(Info);
3749 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3750 return false;
3751 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003752 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003753 }
3754
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003755 // For a trivial copy or move constructor, perform an APValue copy. This is
3756 // essential for unions, where the operations performed by the constructor
3757 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003758 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003759 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3760 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003761 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003762 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003763 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003764 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003765 }
3766
3767 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003768 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003769 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003770 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003771
John McCalld7bca762012-05-01 00:38:49 +00003772 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003773 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3774
Richard Smith08d6a2c2013-07-24 07:11:57 +00003775 // A scope for temporaries lifetime-extended by reference members.
3776 BlockScopeRAII LifetimeExtendedScope(Info);
3777
Richard Smith253c2a32012-01-27 01:14:48 +00003778 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003779 unsigned BasesSeen = 0;
3780#ifndef NDEBUG
3781 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3782#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003783 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003784 LValue Subobject = This;
3785 APValue *Value = &Result;
3786
3787 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003788 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003789 if (I->isBaseInitializer()) {
3790 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003791#ifndef NDEBUG
3792 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003793 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003794 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3795 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3796 "base class initializers not in expected order");
3797 ++BaseIt;
3798#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003799 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003800 BaseType->getAsCXXRecordDecl(), &Layout))
3801 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003802 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003803 } else if ((FD = I->getMember())) {
3804 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003805 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003806 if (RD->isUnion()) {
3807 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003808 Value = &Result.getUnionValue();
3809 } else {
3810 Value = &Result.getStructField(FD->getFieldIndex());
3811 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003812 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003813 // Walk the indirect field decl's chain to find the object to initialize,
3814 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003815 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003816 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003817 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3818 // Switch the union field if it differs. This happens if we had
3819 // preceding zero-initialization, and we're now initializing a union
3820 // subobject other than the first.
3821 // FIXME: In this case, the values of the other subobjects are
3822 // specified, since zero-initialization sets all padding bits to zero.
3823 if (Value->isUninit() ||
3824 (Value->isUnion() && Value->getUnionField() != FD)) {
3825 if (CD->isUnion())
3826 *Value = APValue(FD);
3827 else
3828 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003829 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003830 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003831 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003832 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003833 if (CD->isUnion())
3834 Value = &Value->getUnionValue();
3835 else
3836 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003837 }
Richard Smithd62306a2011-11-10 06:34:14 +00003838 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003839 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003840 }
Richard Smith253c2a32012-01-27 01:14:48 +00003841
Richard Smith08d6a2c2013-07-24 07:11:57 +00003842 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003843 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3844 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003845 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003846 // If we're checking for a potential constant expression, evaluate all
3847 // initializers even if some of them fail.
3848 if (!Info.keepEvaluatingAfterFailure())
3849 return false;
3850 Success = false;
3851 }
Richard Smithd62306a2011-11-10 06:34:14 +00003852 }
3853
Richard Smithd9f663b2013-04-22 15:31:51 +00003854 return Success &&
3855 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003856}
3857
Eli Friedman9a156e52008-11-12 09:44:48 +00003858//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003859// Generic Evaluation
3860//===----------------------------------------------------------------------===//
3861namespace {
3862
Aaron Ballman68af21c2014-01-03 19:26:43 +00003863template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003864class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003865 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003866private:
Aaron Ballman68af21c2014-01-03 19:26:43 +00003867 bool DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003868 return static_cast<Derived*>(this)->Success(V, E);
3869 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003870 bool DerivedZeroInitialization(const Expr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003871 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003872 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003873
Richard Smith17100ba2012-02-16 02:46:34 +00003874 // Check whether a conditional operator with a non-constant condition is a
3875 // potential constant expression. If neither arm is a potential constant
3876 // expression, then the conditional operator is not either.
3877 template<typename ConditionalOperator>
3878 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003879 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003880
3881 // Speculatively evaluate both arms.
3882 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003883 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003884 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3885
3886 StmtVisitorTy::Visit(E->getFalseExpr());
3887 if (Diag.empty())
3888 return;
3889
3890 Diag.clear();
3891 StmtVisitorTy::Visit(E->getTrueExpr());
3892 if (Diag.empty())
3893 return;
3894 }
3895
3896 Error(E, diag::note_constexpr_conditional_never_const);
3897 }
3898
3899
3900 template<typename ConditionalOperator>
3901 bool HandleConditionalOperator(const ConditionalOperator *E) {
3902 bool BoolResult;
3903 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003904 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003905 CheckPotentialConstantConditional(E);
3906 return false;
3907 }
3908
3909 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3910 return StmtVisitorTy::Visit(EvalExpr);
3911 }
3912
Peter Collingbournee9200682011-05-13 03:29:01 +00003913protected:
3914 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00003915 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00003916 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3917
Richard Smith92b1ce02011-12-12 09:28:41 +00003918 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003919 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003920 }
3921
Aaron Ballman68af21c2014-01-03 19:26:43 +00003922 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003923
3924public:
3925 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3926
3927 EvalInfo &getEvalInfo() { return Info; }
3928
Richard Smithf57d8cb2011-12-09 22:58:01 +00003929 /// Report an evaluation error. This should only be called when an error is
3930 /// first discovered. When propagating an error, just return false.
3931 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003932 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003933 return false;
3934 }
3935 bool Error(const Expr *E) {
3936 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3937 }
3938
Aaron Ballman68af21c2014-01-03 19:26:43 +00003939 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003940 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003941 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003942 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003943 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003944 }
3945
Aaron Ballman68af21c2014-01-03 19:26:43 +00003946 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003947 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003948 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003949 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003950 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003951 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003952 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003953 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003954 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003955 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003956 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00003957 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003958 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00003959 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003960 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00003961 // The initializer may not have been parsed yet, or might be erroneous.
3962 if (!E->getExpr())
3963 return Error(E);
3964 return StmtVisitorTy::Visit(E->getExpr());
3965 }
Richard Smith5894a912011-12-19 22:12:41 +00003966 // We cannot create any objects for which cleanups are required, so there is
3967 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00003968 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00003969 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003970
Aaron Ballman68af21c2014-01-03 19:26:43 +00003971 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003972 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3973 return static_cast<Derived*>(this)->VisitCastExpr(E);
3974 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003975 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003976 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3977 return static_cast<Derived*>(this)->VisitCastExpr(E);
3978 }
3979
Aaron Ballman68af21c2014-01-03 19:26:43 +00003980 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003981 switch (E->getOpcode()) {
3982 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003983 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003984
3985 case BO_Comma:
3986 VisitIgnoredValue(E->getLHS());
3987 return StmtVisitorTy::Visit(E->getRHS());
3988
3989 case BO_PtrMemD:
3990 case BO_PtrMemI: {
3991 LValue Obj;
3992 if (!HandleMemberPointerAccess(Info, E, Obj))
3993 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003994 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003995 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003996 return false;
3997 return DerivedSuccess(Result, E);
3998 }
3999 }
4000 }
4001
Aaron Ballman68af21c2014-01-03 19:26:43 +00004002 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004003 // Evaluate and cache the common expression. We treat it as a temporary,
4004 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004005 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004006 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004007 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004008
Richard Smith17100ba2012-02-16 02:46:34 +00004009 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004010 }
4011
Aaron Ballman68af21c2014-01-03 19:26:43 +00004012 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004013 bool IsBcpCall = false;
4014 // If the condition (ignoring parens) is a __builtin_constant_p call,
4015 // the result is a constant expression if it can be folded without
4016 // side-effects. This is an important GNU extension. See GCC PR38377
4017 // for discussion.
4018 if (const CallExpr *CallCE =
4019 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004020 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004021 IsBcpCall = true;
4022
4023 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4024 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004025 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004026 return false;
4027
Richard Smith6d4c6582013-11-05 22:18:15 +00004028 FoldConstant Fold(Info, IsBcpCall);
4029 if (!HandleConditionalOperator(E)) {
4030 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004031 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004032 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004033
4034 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004035 }
4036
Aaron Ballman68af21c2014-01-03 19:26:43 +00004037 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004038 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4039 return DerivedSuccess(*Value, E);
4040
4041 const Expr *Source = E->getSourceExpr();
4042 if (!Source)
4043 return Error(E);
4044 if (Source == E) { // sanity checking.
4045 assert(0 && "OpaqueValueExpr recursively refers to itself");
4046 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004047 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004048 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004049 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004050
Aaron Ballman68af21c2014-01-03 19:26:43 +00004051 bool VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004052 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004053 QualType CalleeType = Callee->getType();
4054
Craig Topper36250ad2014-05-12 05:36:57 +00004055 const FunctionDecl *FD = nullptr;
4056 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004057 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004058 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004059
Richard Smithe97cbd72011-11-11 04:05:33 +00004060 // Extract function decl and 'this' pointer from the callee.
4061 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004062 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004063 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4064 // Explicit bound member calls, such as x.f() or p->g();
4065 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004066 return false;
4067 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004068 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004069 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004070 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4071 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004072 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4073 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004074 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004075 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004076 return Error(Callee);
4077
4078 FD = dyn_cast<FunctionDecl>(Member);
4079 if (!FD)
4080 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004081 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004082 LValue Call;
4083 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004084 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004085
Richard Smitha8105bc2012-01-06 16:39:00 +00004086 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004087 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004088 FD = dyn_cast_or_null<FunctionDecl>(
4089 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004090 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004091 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004092
4093 // Overloaded operator calls to member functions are represented as normal
4094 // calls with '*this' as the first argument.
4095 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4096 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004097 // FIXME: When selecting an implicit conversion for an overloaded
4098 // operator delete, we sometimes try to evaluate calls to conversion
4099 // operators without a 'this' parameter!
4100 if (Args.empty())
4101 return Error(E);
4102
Richard Smithe97cbd72011-11-11 04:05:33 +00004103 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4104 return false;
4105 This = &ThisVal;
4106 Args = Args.slice(1);
4107 }
4108
4109 // Don't call function pointers which have been cast to some other type.
4110 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004111 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004112 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004113 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004114
Richard Smith47b34932012-02-01 02:39:43 +00004115 if (This && !This->checkSubobject(Info, E, CSK_This))
4116 return false;
4117
Richard Smith3607ffe2012-02-13 03:54:03 +00004118 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4119 // calls to such functions in constant expressions.
4120 if (This && !HasQualifier &&
4121 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4122 return Error(E, diag::note_constexpr_virtual_call);
4123
Craig Topper36250ad2014-05-12 05:36:57 +00004124 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004125 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004126 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004127
Richard Smith357362d2011-12-13 06:39:58 +00004128 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004129 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4130 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004131 return false;
4132
Richard Smithb228a862012-02-15 02:18:13 +00004133 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004134 }
4135
Aaron Ballman68af21c2014-01-03 19:26:43 +00004136 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004137 return StmtVisitorTy::Visit(E->getInitializer());
4138 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004139 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004140 if (E->getNumInits() == 0)
4141 return DerivedZeroInitialization(E);
4142 if (E->getNumInits() == 1)
4143 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004144 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004145 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004146 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004147 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004148 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004149 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004150 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004151 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004152 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004153 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004154 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004155
Richard Smithd62306a2011-11-10 06:34:14 +00004156 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004157 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004158 assert(!E->isArrow() && "missing call to bound member function?");
4159
Richard Smith2e312c82012-03-03 22:46:17 +00004160 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004161 if (!Evaluate(Val, Info, E->getBase()))
4162 return false;
4163
4164 QualType BaseTy = E->getBase()->getType();
4165
4166 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004167 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004168 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004169 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004170 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4171
Richard Smith3229b742013-05-05 21:17:10 +00004172 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004173 SubobjectDesignator Designator(BaseTy);
4174 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004175
Richard Smith3229b742013-05-05 21:17:10 +00004176 APValue Result;
4177 return extractSubobject(Info, E, Obj, Designator, Result) &&
4178 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004179 }
4180
Aaron Ballman68af21c2014-01-03 19:26:43 +00004181 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004182 switch (E->getCastKind()) {
4183 default:
4184 break;
4185
Richard Smitha23ab512013-05-23 00:30:41 +00004186 case CK_AtomicToNonAtomic: {
4187 APValue AtomicVal;
4188 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4189 return false;
4190 return DerivedSuccess(AtomicVal, E);
4191 }
4192
Richard Smith11562c52011-10-28 17:51:58 +00004193 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004194 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004195 return StmtVisitorTy::Visit(E->getSubExpr());
4196
4197 case CK_LValueToRValue: {
4198 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004199 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4200 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004201 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004202 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004203 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004204 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004205 return false;
4206 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004207 }
4208 }
4209
Richard Smithf57d8cb2011-12-09 22:58:01 +00004210 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004211 }
4212
Aaron Ballman68af21c2014-01-03 19:26:43 +00004213 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004214 return VisitUnaryPostIncDec(UO);
4215 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004216 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004217 return VisitUnaryPostIncDec(UO);
4218 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004219 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004220 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004221 return Error(UO);
4222
4223 LValue LVal;
4224 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4225 return false;
4226 APValue RVal;
4227 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4228 UO->isIncrementOp(), &RVal))
4229 return false;
4230 return DerivedSuccess(RVal, UO);
4231 }
4232
Aaron Ballman68af21c2014-01-03 19:26:43 +00004233 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004234 // We will have checked the full-expressions inside the statement expression
4235 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004236 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004237 return Error(E);
4238
Richard Smith08d6a2c2013-07-24 07:11:57 +00004239 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004240 const CompoundStmt *CS = E->getSubStmt();
4241 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4242 BE = CS->body_end();
4243 /**/; ++BI) {
4244 if (BI + 1 == BE) {
4245 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4246 if (!FinalExpr) {
4247 Info.Diag((*BI)->getLocStart(),
4248 diag::note_constexpr_stmt_expr_unsupported);
4249 return false;
4250 }
4251 return this->Visit(FinalExpr);
4252 }
4253
4254 APValue ReturnValue;
4255 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4256 if (ESR != ESR_Succeeded) {
4257 // FIXME: If the statement-expression terminated due to 'return',
4258 // 'break', or 'continue', it would be nice to propagate that to
4259 // the outer statement evaluation rather than bailing out.
4260 if (ESR != ESR_Failed)
4261 Info.Diag((*BI)->getLocStart(),
4262 diag::note_constexpr_stmt_expr_unsupported);
4263 return false;
4264 }
4265 }
4266 }
4267
Richard Smith4a678122011-10-24 18:44:57 +00004268 /// Visit a value which is evaluated, but whose value is ignored.
4269 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004270 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004271 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004272};
4273
4274}
4275
4276//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004277// Common base class for lvalue and temporary evaluation.
4278//===----------------------------------------------------------------------===//
4279namespace {
4280template<class Derived>
4281class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004282 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004283protected:
4284 LValue &Result;
4285 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004286 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004287
4288 bool Success(APValue::LValueBase B) {
4289 Result.set(B);
4290 return true;
4291 }
4292
4293public:
4294 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4295 ExprEvaluatorBaseTy(Info), Result(Result) {}
4296
Richard Smith2e312c82012-03-03 22:46:17 +00004297 bool Success(const APValue &V, const Expr *E) {
4298 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004299 return true;
4300 }
Richard Smith027bf112011-11-17 22:56:20 +00004301
Richard Smith027bf112011-11-17 22:56:20 +00004302 bool VisitMemberExpr(const MemberExpr *E) {
4303 // Handle non-static data members.
4304 QualType BaseTy;
4305 if (E->isArrow()) {
4306 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4307 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004308 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004309 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004310 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004311 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4312 return false;
4313 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004314 } else {
4315 if (!this->Visit(E->getBase()))
4316 return false;
4317 BaseTy = E->getBase()->getType();
4318 }
Richard Smith027bf112011-11-17 22:56:20 +00004319
Richard Smith1b78b3d2012-01-25 22:15:11 +00004320 const ValueDecl *MD = E->getMemberDecl();
4321 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4322 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4323 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4324 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004325 if (!HandleLValueMember(this->Info, E, Result, FD))
4326 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004327 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004328 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4329 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004330 } else
4331 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004332
Richard Smith1b78b3d2012-01-25 22:15:11 +00004333 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004334 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004335 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004336 RefValue))
4337 return false;
4338 return Success(RefValue, E);
4339 }
4340 return true;
4341 }
4342
4343 bool VisitBinaryOperator(const BinaryOperator *E) {
4344 switch (E->getOpcode()) {
4345 default:
4346 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4347
4348 case BO_PtrMemD:
4349 case BO_PtrMemI:
4350 return HandleMemberPointerAccess(this->Info, E, Result);
4351 }
4352 }
4353
4354 bool VisitCastExpr(const CastExpr *E) {
4355 switch (E->getCastKind()) {
4356 default:
4357 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4358
4359 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004360 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004361 if (!this->Visit(E->getSubExpr()))
4362 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004363
4364 // Now figure out the necessary offset to add to the base LV to get from
4365 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004366 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4367 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004368 }
4369 }
4370};
4371}
4372
4373//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004374// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004375//
4376// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4377// function designators (in C), decl references to void objects (in C), and
4378// temporaries (if building with -Wno-address-of-temporary).
4379//
4380// LValue evaluation produces values comprising a base expression of one of the
4381// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004382// - Declarations
4383// * VarDecl
4384// * FunctionDecl
4385// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004386// * CompoundLiteralExpr in C
4387// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004388// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004389// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004390// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004391// * ObjCEncodeExpr
4392// * AddrLabelExpr
4393// * BlockExpr
4394// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004395// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004396// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004397// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004398// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4399// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004400// * A MaterializeTemporaryExpr that has static storage duration, with no
4401// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004402// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004403//===----------------------------------------------------------------------===//
4404namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004405class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004406 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004407public:
Richard Smith027bf112011-11-17 22:56:20 +00004408 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4409 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004410
Richard Smith11562c52011-10-28 17:51:58 +00004411 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004412 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004413
Peter Collingbournee9200682011-05-13 03:29:01 +00004414 bool VisitDeclRefExpr(const DeclRefExpr *E);
4415 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004416 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004417 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4418 bool VisitMemberExpr(const MemberExpr *E);
4419 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4420 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004421 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004422 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004423 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4424 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004425 bool VisitUnaryReal(const UnaryOperator *E);
4426 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004427 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4428 return VisitUnaryPreIncDec(UO);
4429 }
4430 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4431 return VisitUnaryPreIncDec(UO);
4432 }
Richard Smith3229b742013-05-05 21:17:10 +00004433 bool VisitBinAssign(const BinaryOperator *BO);
4434 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004435
Peter Collingbournee9200682011-05-13 03:29:01 +00004436 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004437 switch (E->getCastKind()) {
4438 default:
Richard Smith027bf112011-11-17 22:56:20 +00004439 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004440
Eli Friedmance3e02a2011-10-11 00:13:24 +00004441 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004442 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004443 if (!Visit(E->getSubExpr()))
4444 return false;
4445 Result.Designator.setInvalid();
4446 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004447
Richard Smith027bf112011-11-17 22:56:20 +00004448 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004449 if (!Visit(E->getSubExpr()))
4450 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004451 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004452 }
4453 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004454};
4455} // end anonymous namespace
4456
Richard Smith11562c52011-10-28 17:51:58 +00004457/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004458/// expressions which are not glvalues, in two cases:
4459/// * function designators in C, and
4460/// * "extern void" objects
4461static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4462 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4463 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004464 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004465}
4466
Peter Collingbournee9200682011-05-13 03:29:01 +00004467bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004468 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004469 return Success(FD);
4470 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004471 return VisitVarDecl(E, VD);
4472 return Error(E);
4473}
Richard Smith733237d2011-10-24 23:14:33 +00004474
Richard Smith11562c52011-10-28 17:51:58 +00004475bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004476 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004477 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4478 Frame = Info.CurrentCall;
4479
Richard Smithfec09922011-11-01 16:57:24 +00004480 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004481 if (Frame) {
4482 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004483 return true;
4484 }
Richard Smithce40ad62011-11-12 22:28:03 +00004485 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004486 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004487
Richard Smith3229b742013-05-05 21:17:10 +00004488 APValue *V;
4489 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004490 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004491 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004492 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004493 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4494 return false;
4495 }
Richard Smith3229b742013-05-05 21:17:10 +00004496 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004497}
4498
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004499bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4500 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004501 // Walk through the expression to find the materialized temporary itself.
4502 SmallVector<const Expr *, 2> CommaLHSs;
4503 SmallVector<SubobjectAdjustment, 2> Adjustments;
4504 const Expr *Inner = E->GetTemporaryExpr()->
4505 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004506
Richard Smith84401042013-06-03 05:03:02 +00004507 // If we passed any comma operators, evaluate their LHSs.
4508 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4509 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4510 return false;
4511
Richard Smithe6c01442013-06-05 00:46:14 +00004512 // A materialized temporary with static storage duration can appear within the
4513 // result of a constant expression evaluation, so we need to preserve its
4514 // value for use outside this evaluation.
4515 APValue *Value;
4516 if (E->getStorageDuration() == SD_Static) {
4517 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004518 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004519 Result.set(E);
4520 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004521 Value = &Info.CurrentCall->
4522 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004523 Result.set(E, Info.CurrentCall->Index);
4524 }
4525
Richard Smithea4ad5d2013-06-06 08:19:16 +00004526 QualType Type = Inner->getType();
4527
Richard Smith84401042013-06-03 05:03:02 +00004528 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004529 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4530 (E->getStorageDuration() == SD_Static &&
4531 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4532 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004533 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004534 }
Richard Smith84401042013-06-03 05:03:02 +00004535
4536 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004537 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4538 --I;
4539 switch (Adjustments[I].Kind) {
4540 case SubobjectAdjustment::DerivedToBaseAdjustment:
4541 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4542 Type, Result))
4543 return false;
4544 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4545 break;
4546
4547 case SubobjectAdjustment::FieldAdjustment:
4548 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4549 return false;
4550 Type = Adjustments[I].Field->getType();
4551 break;
4552
4553 case SubobjectAdjustment::MemberPointerAdjustment:
4554 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4555 Adjustments[I].Ptr.RHS))
4556 return false;
4557 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4558 break;
4559 }
4560 }
4561
4562 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004563}
4564
Peter Collingbournee9200682011-05-13 03:29:01 +00004565bool
4566LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004567 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4568 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4569 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004570 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004571}
4572
Richard Smith6e525142011-12-27 12:18:28 +00004573bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004574 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004575 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004576
4577 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4578 << E->getExprOperand()->getType()
4579 << E->getExprOperand()->getSourceRange();
4580 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004581}
4582
Francois Pichet0066db92012-04-16 04:08:35 +00004583bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4584 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004585}
Francois Pichet0066db92012-04-16 04:08:35 +00004586
Peter Collingbournee9200682011-05-13 03:29:01 +00004587bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004588 // Handle static data members.
4589 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4590 VisitIgnoredValue(E->getBase());
4591 return VisitVarDecl(E, VD);
4592 }
4593
Richard Smith254a73d2011-10-28 22:34:42 +00004594 // Handle static member functions.
4595 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4596 if (MD->isStatic()) {
4597 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004598 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004599 }
4600 }
4601
Richard Smithd62306a2011-11-10 06:34:14 +00004602 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004603 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004604}
4605
Peter Collingbournee9200682011-05-13 03:29:01 +00004606bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004607 // FIXME: Deal with vectors as array subscript bases.
4608 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004609 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004610
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004611 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004612 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004613
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004614 APSInt Index;
4615 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004616 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004617
Richard Smith861b5b52013-05-07 23:34:45 +00004618 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4619 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004620}
Eli Friedman9a156e52008-11-12 09:44:48 +00004621
Peter Collingbournee9200682011-05-13 03:29:01 +00004622bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004623 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004624}
4625
Richard Smith66c96992012-02-18 22:04:06 +00004626bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4627 if (!Visit(E->getSubExpr()))
4628 return false;
4629 // __real is a no-op on scalar lvalues.
4630 if (E->getSubExpr()->getType()->isAnyComplexType())
4631 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4632 return true;
4633}
4634
4635bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4636 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4637 "lvalue __imag__ on scalar?");
4638 if (!Visit(E->getSubExpr()))
4639 return false;
4640 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4641 return true;
4642}
4643
Richard Smith243ef902013-05-05 23:31:59 +00004644bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004645 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004646 return Error(UO);
4647
4648 if (!this->Visit(UO->getSubExpr()))
4649 return false;
4650
Richard Smith243ef902013-05-05 23:31:59 +00004651 return handleIncDec(
4652 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004653 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004654}
4655
4656bool LValueExprEvaluator::VisitCompoundAssignOperator(
4657 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004658 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004659 return Error(CAO);
4660
Richard Smith3229b742013-05-05 21:17:10 +00004661 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004662
4663 // The overall lvalue result is the result of evaluating the LHS.
4664 if (!this->Visit(CAO->getLHS())) {
4665 if (Info.keepEvaluatingAfterFailure())
4666 Evaluate(RHS, this->Info, CAO->getRHS());
4667 return false;
4668 }
4669
Richard Smith3229b742013-05-05 21:17:10 +00004670 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4671 return false;
4672
Richard Smith43e77732013-05-07 04:50:00 +00004673 return handleCompoundAssignment(
4674 this->Info, CAO,
4675 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4676 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004677}
4678
4679bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004680 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004681 return Error(E);
4682
Richard Smith3229b742013-05-05 21:17:10 +00004683 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004684
4685 if (!this->Visit(E->getLHS())) {
4686 if (Info.keepEvaluatingAfterFailure())
4687 Evaluate(NewVal, this->Info, E->getRHS());
4688 return false;
4689 }
4690
Richard Smith3229b742013-05-05 21:17:10 +00004691 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4692 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004693
4694 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004695 NewVal);
4696}
4697
Eli Friedman9a156e52008-11-12 09:44:48 +00004698//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004699// Pointer Evaluation
4700//===----------------------------------------------------------------------===//
4701
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004702namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004703class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004704 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004705 LValue &Result;
4706
Peter Collingbournee9200682011-05-13 03:29:01 +00004707 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004708 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004709 return true;
4710 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004711public:
Mike Stump11289f42009-09-09 15:08:12 +00004712
John McCall45d55e42010-05-07 21:00:08 +00004713 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004714 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004715
Richard Smith2e312c82012-03-03 22:46:17 +00004716 bool Success(const APValue &V, const Expr *E) {
4717 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004718 return true;
4719 }
Richard Smithfddd3842011-12-30 21:15:51 +00004720 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004721 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004722 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004723
John McCall45d55e42010-05-07 21:00:08 +00004724 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004725 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004726 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004727 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004728 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004729 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004730 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004731 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004732 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004733 bool VisitCallExpr(const CallExpr *E);
4734 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004735 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004736 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004737 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004738 }
Richard Smithd62306a2011-11-10 06:34:14 +00004739 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004740 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004741 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004742 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004743 if (!Info.CurrentCall->This) {
4744 if (Info.getLangOpts().CPlusPlus11)
4745 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4746 else
4747 Info.Diag(E);
4748 return false;
4749 }
Richard Smithd62306a2011-11-10 06:34:14 +00004750 Result = *Info.CurrentCall->This;
4751 return true;
4752 }
John McCallc07a0c72011-02-17 10:25:35 +00004753
Eli Friedman449fe542009-03-23 04:56:01 +00004754 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004755};
Chris Lattner05706e882008-07-11 18:11:29 +00004756} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004757
John McCall45d55e42010-05-07 21:00:08 +00004758static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004759 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004760 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004761}
4762
John McCall45d55e42010-05-07 21:00:08 +00004763bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004764 if (E->getOpcode() != BO_Add &&
4765 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004766 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004767
Chris Lattner05706e882008-07-11 18:11:29 +00004768 const Expr *PExp = E->getLHS();
4769 const Expr *IExp = E->getRHS();
4770 if (IExp->getType()->isPointerType())
4771 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004772
Richard Smith253c2a32012-01-27 01:14:48 +00004773 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4774 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004775 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004776
John McCall45d55e42010-05-07 21:00:08 +00004777 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004778 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004779 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004780
4781 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004782 if (E->getOpcode() == BO_Sub)
4783 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004784
Ted Kremenek28831752012-08-23 20:46:57 +00004785 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004786 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4787 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004788}
Eli Friedman9a156e52008-11-12 09:44:48 +00004789
John McCall45d55e42010-05-07 21:00:08 +00004790bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4791 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004792}
Mike Stump11289f42009-09-09 15:08:12 +00004793
Peter Collingbournee9200682011-05-13 03:29:01 +00004794bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4795 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004796
Eli Friedman847a2bc2009-12-27 05:43:15 +00004797 switch (E->getCastKind()) {
4798 default:
4799 break;
4800
John McCalle3027922010-08-25 11:45:40 +00004801 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004802 case CK_CPointerToObjCPointerCast:
4803 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004804 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004805 if (!Visit(SubExpr))
4806 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004807 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4808 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4809 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004810 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004811 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004812 if (SubExpr->getType()->isVoidPointerType())
4813 CCEDiag(E, diag::note_constexpr_invalid_cast)
4814 << 3 << SubExpr->getType();
4815 else
4816 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4817 }
Richard Smith96e0c102011-11-04 02:25:55 +00004818 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004819
Anders Carlsson18275092010-10-31 20:41:46 +00004820 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004821 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004822 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004823 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004824 if (!Result.Base && Result.Offset.isZero())
4825 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004826
Richard Smithd62306a2011-11-10 06:34:14 +00004827 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004828 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004829 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4830 castAs<PointerType>()->getPointeeType(),
4831 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004832
Richard Smith027bf112011-11-17 22:56:20 +00004833 case CK_BaseToDerived:
4834 if (!Visit(E->getSubExpr()))
4835 return false;
4836 if (!Result.Base && Result.Offset.isZero())
4837 return true;
4838 return HandleBaseToDerivedCast(Info, E, Result);
4839
Richard Smith0b0a0b62011-10-29 20:57:55 +00004840 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004841 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004842 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004843
John McCalle3027922010-08-25 11:45:40 +00004844 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004845 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4846
Richard Smith2e312c82012-03-03 22:46:17 +00004847 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004848 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004849 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004850
John McCall45d55e42010-05-07 21:00:08 +00004851 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004852 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4853 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004854 Result.Base = (Expr*)nullptr;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004855 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004856 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004857 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004858 return true;
4859 } else {
4860 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004861 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004862 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004863 }
4864 }
John McCalle3027922010-08-25 11:45:40 +00004865 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004866 if (SubExpr->isGLValue()) {
4867 if (!EvaluateLValue(SubExpr, Result, Info))
4868 return false;
4869 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004870 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004871 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004872 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004873 return false;
4874 }
Richard Smith96e0c102011-11-04 02:25:55 +00004875 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004876 if (const ConstantArrayType *CAT
4877 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4878 Result.addArray(Info, E, CAT);
4879 else
4880 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004881 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004882
John McCalle3027922010-08-25 11:45:40 +00004883 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004884 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004885 }
4886
Richard Smith11562c52011-10-28 17:51:58 +00004887 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004888}
Chris Lattner05706e882008-07-11 18:11:29 +00004889
Hal Finkel0dd05d42014-10-03 17:18:37 +00004890static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
4891 // C++ [expr.alignof]p3:
4892 // When alignof is applied to a reference type, the result is the
4893 // alignment of the referenced type.
4894 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4895 T = Ref->getPointeeType();
4896
4897 // __alignof is defined to return the preferred alignment.
4898 return Info.Ctx.toCharUnitsFromBits(
4899 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4900}
4901
4902static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
4903 E = E->IgnoreParens();
4904
4905 // The kinds of expressions that we have special-case logic here for
4906 // should be kept up to date with the special checks for those
4907 // expressions in Sema.
4908
4909 // alignof decl is always accepted, even if it doesn't make sense: we default
4910 // to 1 in those cases.
4911 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4912 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4913 /*RefAsPointee*/true);
4914
4915 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4916 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4917 /*RefAsPointee*/true);
4918
4919 return GetAlignOfType(Info, E->getType());
4920}
4921
Peter Collingbournee9200682011-05-13 03:29:01 +00004922bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004923 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004924 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004925
Alp Tokera724cff2013-12-28 21:59:02 +00004926 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004927 case Builtin::BI__builtin_addressof:
4928 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00004929 case Builtin::BI__builtin_assume_aligned: {
4930 // We need to be very careful here because: if the pointer does not have the
4931 // asserted alignment, then the behavior is undefined, and undefined
4932 // behavior is non-constant.
4933 if (!EvaluatePointer(E->getArg(0), Result, Info))
4934 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00004935
Hal Finkel0dd05d42014-10-03 17:18:37 +00004936 LValue OffsetResult(Result);
4937 APSInt Alignment;
4938 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
4939 return false;
4940 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
4941
4942 if (E->getNumArgs() > 2) {
4943 APSInt Offset;
4944 if (!EvaluateInteger(E->getArg(2), Offset, Info))
4945 return false;
4946
4947 int64_t AdditionalOffset = -getExtValue(Offset);
4948 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
4949 }
4950
4951 // If there is a base object, then it must have the correct alignment.
4952 if (OffsetResult.Base) {
4953 CharUnits BaseAlignment;
4954 if (const ValueDecl *VD =
4955 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
4956 BaseAlignment = Info.Ctx.getDeclAlign(VD);
4957 } else {
4958 BaseAlignment =
4959 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
4960 }
4961
4962 if (BaseAlignment < Align) {
4963 Result.Designator.setInvalid();
4964 // FIXME: Quantities here cast to integers because the plural modifier
4965 // does not work on APSInts yet.
4966 CCEDiag(E->getArg(0),
4967 diag::note_constexpr_baa_insufficient_alignment) << 0
4968 << (int) BaseAlignment.getQuantity()
4969 << (unsigned) getExtValue(Alignment);
4970 return false;
4971 }
4972 }
4973
4974 // The offset must also have the correct alignment.
4975 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
4976 Result.Designator.setInvalid();
4977 APSInt Offset(64, false);
4978 Offset = OffsetResult.Offset.getQuantity();
4979
4980 if (OffsetResult.Base)
4981 CCEDiag(E->getArg(0),
4982 diag::note_constexpr_baa_insufficient_alignment) << 1
4983 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
4984 else
4985 CCEDiag(E->getArg(0),
4986 diag::note_constexpr_baa_value_insufficient_alignment)
4987 << Offset << (unsigned) getExtValue(Alignment);
4988
4989 return false;
4990 }
4991
4992 return true;
4993 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00004994 default:
4995 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4996 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004997}
Chris Lattner05706e882008-07-11 18:11:29 +00004998
4999//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005000// Member Pointer Evaluation
5001//===----------------------------------------------------------------------===//
5002
5003namespace {
5004class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005005 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005006 MemberPtr &Result;
5007
5008 bool Success(const ValueDecl *D) {
5009 Result = MemberPtr(D);
5010 return true;
5011 }
5012public:
5013
5014 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5015 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5016
Richard Smith2e312c82012-03-03 22:46:17 +00005017 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005018 Result.setFrom(V);
5019 return true;
5020 }
Richard Smithfddd3842011-12-30 21:15:51 +00005021 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005022 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005023 }
5024
5025 bool VisitCastExpr(const CastExpr *E);
5026 bool VisitUnaryAddrOf(const UnaryOperator *E);
5027};
5028} // end anonymous namespace
5029
5030static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5031 EvalInfo &Info) {
5032 assert(E->isRValue() && E->getType()->isMemberPointerType());
5033 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5034}
5035
5036bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5037 switch (E->getCastKind()) {
5038 default:
5039 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5040
5041 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005042 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005043 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005044
5045 case CK_BaseToDerivedMemberPointer: {
5046 if (!Visit(E->getSubExpr()))
5047 return false;
5048 if (E->path_empty())
5049 return true;
5050 // Base-to-derived member pointer casts store the path in derived-to-base
5051 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5052 // the wrong end of the derived->base arc, so stagger the path by one class.
5053 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5054 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5055 PathI != PathE; ++PathI) {
5056 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5057 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5058 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005059 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005060 }
5061 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5062 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005063 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005064 return true;
5065 }
5066
5067 case CK_DerivedToBaseMemberPointer:
5068 if (!Visit(E->getSubExpr()))
5069 return false;
5070 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5071 PathE = E->path_end(); PathI != PathE; ++PathI) {
5072 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5073 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5074 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005075 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005076 }
5077 return true;
5078 }
5079}
5080
5081bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5082 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5083 // member can be formed.
5084 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5085}
5086
5087//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005088// Record Evaluation
5089//===----------------------------------------------------------------------===//
5090
5091namespace {
5092 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005093 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005094 const LValue &This;
5095 APValue &Result;
5096 public:
5097
5098 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5099 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5100
Richard Smith2e312c82012-03-03 22:46:17 +00005101 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005102 Result = V;
5103 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005104 }
Richard Smithfddd3842011-12-30 21:15:51 +00005105 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005106
Richard Smithe97cbd72011-11-11 04:05:33 +00005107 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005108 bool VisitInitListExpr(const InitListExpr *E);
5109 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005110 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005111 };
5112}
5113
Richard Smithfddd3842011-12-30 21:15:51 +00005114/// Perform zero-initialization on an object of non-union class type.
5115/// C++11 [dcl.init]p5:
5116/// To zero-initialize an object or reference of type T means:
5117/// [...]
5118/// -- if T is a (possibly cv-qualified) non-union class type,
5119/// each non-static data member and each base-class subobject is
5120/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005121static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5122 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005123 const LValue &This, APValue &Result) {
5124 assert(!RD->isUnion() && "Expected non-union class type");
5125 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5126 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005127 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005128
John McCalld7bca762012-05-01 00:38:49 +00005129 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005130 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5131
5132 if (CD) {
5133 unsigned Index = 0;
5134 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005135 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005136 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5137 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005138 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5139 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005140 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005141 Result.getStructBase(Index)))
5142 return false;
5143 }
5144 }
5145
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005146 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005147 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005148 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005149 continue;
5150
5151 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005152 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005153 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005154
David Blaikie2d7c57e2012-04-30 02:36:29 +00005155 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005156 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005157 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005158 return false;
5159 }
5160
5161 return true;
5162}
5163
5164bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5165 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005166 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005167 if (RD->isUnion()) {
5168 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5169 // object's first non-static named data member is zero-initialized
5170 RecordDecl::field_iterator I = RD->field_begin();
5171 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005172 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005173 return true;
5174 }
5175
5176 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005177 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005178 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005179 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005180 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005181 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005182 }
5183
Richard Smith5d108602012-02-17 00:44:16 +00005184 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005185 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005186 return false;
5187 }
5188
Richard Smitha8105bc2012-01-06 16:39:00 +00005189 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005190}
5191
Richard Smithe97cbd72011-11-11 04:05:33 +00005192bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5193 switch (E->getCastKind()) {
5194 default:
5195 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5196
5197 case CK_ConstructorConversion:
5198 return Visit(E->getSubExpr());
5199
5200 case CK_DerivedToBase:
5201 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005202 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005203 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005204 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005205 if (!DerivedObject.isStruct())
5206 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005207
5208 // Derived-to-base rvalue conversion: just slice off the derived part.
5209 APValue *Value = &DerivedObject;
5210 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5211 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5212 PathE = E->path_end(); PathI != PathE; ++PathI) {
5213 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5214 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5215 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5216 RD = Base;
5217 }
5218 Result = *Value;
5219 return true;
5220 }
5221 }
5222}
5223
Richard Smithd62306a2011-11-10 06:34:14 +00005224bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5225 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005226 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005227 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5228
5229 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005230 const FieldDecl *Field = E->getInitializedFieldInUnion();
5231 Result = APValue(Field);
5232 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005233 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005234
5235 // If the initializer list for a union does not contain any elements, the
5236 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005237 // FIXME: The element should be initialized from an initializer list.
5238 // Is this difference ever observable for initializer lists which
5239 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005240 ImplicitValueInitExpr VIE(Field->getType());
5241 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5242
Richard Smithd62306a2011-11-10 06:34:14 +00005243 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005244 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5245 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005246
5247 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5248 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5249 isa<CXXDefaultInitExpr>(InitExpr));
5250
Richard Smithb228a862012-02-15 02:18:13 +00005251 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005252 }
5253
5254 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5255 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005256 Result = APValue(APValue::UninitStruct(), 0,
5257 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005258 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005259 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005260 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005261 // Anonymous bit-fields are not considered members of the class for
5262 // purposes of aggregate initialization.
5263 if (Field->isUnnamedBitfield())
5264 continue;
5265
5266 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005267
Richard Smith253c2a32012-01-27 01:14:48 +00005268 bool HaveInit = ElementNo < E->getNumInits();
5269
5270 // FIXME: Diagnostics here should point to the end of the initializer
5271 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005272 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005273 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005274 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005275
5276 // Perform an implicit value-initialization for members beyond the end of
5277 // the initializer list.
5278 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005279 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005280
Richard Smith852c9db2013-04-20 22:23:05 +00005281 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5282 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5283 isa<CXXDefaultInitExpr>(Init));
5284
Richard Smith49ca8aa2013-08-06 07:09:20 +00005285 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5286 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5287 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005288 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005289 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005290 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005291 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005292 }
5293 }
5294
Richard Smith253c2a32012-01-27 01:14:48 +00005295 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005296}
5297
5298bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5299 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005300 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5301
Richard Smithfddd3842011-12-30 21:15:51 +00005302 bool ZeroInit = E->requiresZeroInitialization();
5303 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005304 // If we've already performed zero-initialization, we're already done.
5305 if (!Result.isUninit())
5306 return true;
5307
Richard Smithda3f4fd2014-03-05 23:32:50 +00005308 // We can get here in two different ways:
5309 // 1) We're performing value-initialization, and should zero-initialize
5310 // the object, or
5311 // 2) We're performing default-initialization of an object with a trivial
5312 // constexpr default constructor, in which case we should start the
5313 // lifetimes of all the base subobjects (there can be no data member
5314 // subobjects in this case) per [basic.life]p1.
5315 // Either way, ZeroInitialization is appropriate.
5316 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005317 }
5318
Craig Topper36250ad2014-05-12 05:36:57 +00005319 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005320 FD->getBody(Definition);
5321
Richard Smith357362d2011-12-13 06:39:58 +00005322 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5323 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005324
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005325 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005326 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005327 if (const MaterializeTemporaryExpr *ME
5328 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5329 return Visit(ME->GetTemporaryExpr());
5330
Richard Smithfddd3842011-12-30 21:15:51 +00005331 if (ZeroInit && !ZeroInitialization(E))
5332 return false;
5333
Craig Topper5fc8fc22014-08-27 06:28:36 +00005334 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005335 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005336 cast<CXXConstructorDecl>(Definition), Info,
5337 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005338}
5339
Richard Smithcc1b96d2013-06-12 22:31:48 +00005340bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5341 const CXXStdInitializerListExpr *E) {
5342 const ConstantArrayType *ArrayType =
5343 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5344
5345 LValue Array;
5346 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5347 return false;
5348
5349 // Get a pointer to the first element of the array.
5350 Array.addArray(Info, E, ArrayType);
5351
5352 // FIXME: Perform the checks on the field types in SemaInit.
5353 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5354 RecordDecl::field_iterator Field = Record->field_begin();
5355 if (Field == Record->field_end())
5356 return Error(E);
5357
5358 // Start pointer.
5359 if (!Field->getType()->isPointerType() ||
5360 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5361 ArrayType->getElementType()))
5362 return Error(E);
5363
5364 // FIXME: What if the initializer_list type has base classes, etc?
5365 Result = APValue(APValue::UninitStruct(), 0, 2);
5366 Array.moveInto(Result.getStructField(0));
5367
5368 if (++Field == Record->field_end())
5369 return Error(E);
5370
5371 if (Field->getType()->isPointerType() &&
5372 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5373 ArrayType->getElementType())) {
5374 // End pointer.
5375 if (!HandleLValueArrayAdjustment(Info, E, Array,
5376 ArrayType->getElementType(),
5377 ArrayType->getSize().getZExtValue()))
5378 return false;
5379 Array.moveInto(Result.getStructField(1));
5380 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5381 // Length.
5382 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5383 else
5384 return Error(E);
5385
5386 if (++Field != Record->field_end())
5387 return Error(E);
5388
5389 return true;
5390}
5391
Richard Smithd62306a2011-11-10 06:34:14 +00005392static bool EvaluateRecord(const Expr *E, const LValue &This,
5393 APValue &Result, EvalInfo &Info) {
5394 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005395 "can't evaluate expression as a record rvalue");
5396 return RecordExprEvaluator(Info, This, Result).Visit(E);
5397}
5398
5399//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005400// Temporary Evaluation
5401//
5402// Temporaries are represented in the AST as rvalues, but generally behave like
5403// lvalues. The full-object of which the temporary is a subobject is implicitly
5404// materialized so that a reference can bind to it.
5405//===----------------------------------------------------------------------===//
5406namespace {
5407class TemporaryExprEvaluator
5408 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5409public:
5410 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5411 LValueExprEvaluatorBaseTy(Info, Result) {}
5412
5413 /// Visit an expression which constructs the value of this temporary.
5414 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005415 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005416 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5417 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005418 }
5419
5420 bool VisitCastExpr(const CastExpr *E) {
5421 switch (E->getCastKind()) {
5422 default:
5423 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5424
5425 case CK_ConstructorConversion:
5426 return VisitConstructExpr(E->getSubExpr());
5427 }
5428 }
5429 bool VisitInitListExpr(const InitListExpr *E) {
5430 return VisitConstructExpr(E);
5431 }
5432 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5433 return VisitConstructExpr(E);
5434 }
5435 bool VisitCallExpr(const CallExpr *E) {
5436 return VisitConstructExpr(E);
5437 }
5438};
5439} // end anonymous namespace
5440
5441/// Evaluate an expression of record type as a temporary.
5442static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005443 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005444 return TemporaryExprEvaluator(Info, Result).Visit(E);
5445}
5446
5447//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005448// Vector Evaluation
5449//===----------------------------------------------------------------------===//
5450
5451namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005452 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005453 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005454 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005455 public:
Mike Stump11289f42009-09-09 15:08:12 +00005456
Richard Smith2d406342011-10-22 21:10:00 +00005457 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5458 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005459
Richard Smith2d406342011-10-22 21:10:00 +00005460 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5461 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5462 // FIXME: remove this APValue copy.
5463 Result = APValue(V.data(), V.size());
5464 return true;
5465 }
Richard Smith2e312c82012-03-03 22:46:17 +00005466 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005467 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005468 Result = V;
5469 return true;
5470 }
Richard Smithfddd3842011-12-30 21:15:51 +00005471 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005472
Richard Smith2d406342011-10-22 21:10:00 +00005473 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005474 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005475 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005476 bool VisitInitListExpr(const InitListExpr *E);
5477 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005478 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005479 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005480 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005481 };
5482} // end anonymous namespace
5483
5484static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005485 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005486 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005487}
5488
Richard Smith2d406342011-10-22 21:10:00 +00005489bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5490 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005491 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005492
Richard Smith161f09a2011-12-06 22:44:34 +00005493 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005494 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005495
Eli Friedmanc757de22011-03-25 00:43:55 +00005496 switch (E->getCastKind()) {
5497 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005498 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005499 if (SETy->isIntegerType()) {
5500 APSInt IntResult;
5501 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005502 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005503 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005504 } else if (SETy->isRealFloatingType()) {
5505 APFloat F(0.0);
5506 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005507 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005508 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005509 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005510 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005511 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005512
5513 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005514 SmallVector<APValue, 4> Elts(NElts, Val);
5515 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005516 }
Eli Friedman803acb32011-12-22 03:51:45 +00005517 case CK_BitCast: {
5518 // Evaluate the operand into an APInt we can extract from.
5519 llvm::APInt SValInt;
5520 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5521 return false;
5522 // Extract the elements
5523 QualType EltTy = VTy->getElementType();
5524 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5525 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5526 SmallVector<APValue, 4> Elts;
5527 if (EltTy->isRealFloatingType()) {
5528 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005529 unsigned FloatEltSize = EltSize;
5530 if (&Sem == &APFloat::x87DoubleExtended)
5531 FloatEltSize = 80;
5532 for (unsigned i = 0; i < NElts; i++) {
5533 llvm::APInt Elt;
5534 if (BigEndian)
5535 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5536 else
5537 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005538 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005539 }
5540 } else if (EltTy->isIntegerType()) {
5541 for (unsigned i = 0; i < NElts; i++) {
5542 llvm::APInt Elt;
5543 if (BigEndian)
5544 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5545 else
5546 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5547 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5548 }
5549 } else {
5550 return Error(E);
5551 }
5552 return Success(Elts, E);
5553 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005554 default:
Richard Smith11562c52011-10-28 17:51:58 +00005555 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005556 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005557}
5558
Richard Smith2d406342011-10-22 21:10:00 +00005559bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005560VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005561 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005562 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005563 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005564
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005565 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005566 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005567
Eli Friedmanb9c71292012-01-03 23:24:20 +00005568 // The number of initializers can be less than the number of
5569 // vector elements. For OpenCL, this can be due to nested vector
5570 // initialization. For GCC compatibility, missing trailing elements
5571 // should be initialized with zeroes.
5572 unsigned CountInits = 0, CountElts = 0;
5573 while (CountElts < NumElements) {
5574 // Handle nested vector initialization.
5575 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005576 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005577 APValue v;
5578 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5579 return Error(E);
5580 unsigned vlen = v.getVectorLength();
5581 for (unsigned j = 0; j < vlen; j++)
5582 Elements.push_back(v.getVectorElt(j));
5583 CountElts += vlen;
5584 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005585 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005586 if (CountInits < NumInits) {
5587 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005588 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005589 } else // trailing integer zero.
5590 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5591 Elements.push_back(APValue(sInt));
5592 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005593 } else {
5594 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005595 if (CountInits < NumInits) {
5596 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005597 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005598 } else // trailing float zero.
5599 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5600 Elements.push_back(APValue(f));
5601 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005602 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005603 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005604 }
Richard Smith2d406342011-10-22 21:10:00 +00005605 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005606}
5607
Richard Smith2d406342011-10-22 21:10:00 +00005608bool
Richard Smithfddd3842011-12-30 21:15:51 +00005609VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005610 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005611 QualType EltTy = VT->getElementType();
5612 APValue ZeroElement;
5613 if (EltTy->isIntegerType())
5614 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5615 else
5616 ZeroElement =
5617 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5618
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005619 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005620 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005621}
5622
Richard Smith2d406342011-10-22 21:10:00 +00005623bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005624 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005625 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005626}
5627
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005628//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005629// Array Evaluation
5630//===----------------------------------------------------------------------===//
5631
5632namespace {
5633 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005634 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005635 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005636 APValue &Result;
5637 public:
5638
Richard Smithd62306a2011-11-10 06:34:14 +00005639 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5640 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005641
5642 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005643 assert((V.isArray() || V.isLValue()) &&
5644 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005645 Result = V;
5646 return true;
5647 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005648
Richard Smithfddd3842011-12-30 21:15:51 +00005649 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005650 const ConstantArrayType *CAT =
5651 Info.Ctx.getAsConstantArrayType(E->getType());
5652 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005653 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005654
5655 Result = APValue(APValue::UninitArray(), 0,
5656 CAT->getSize().getZExtValue());
5657 if (!Result.hasArrayFiller()) return true;
5658
Richard Smithfddd3842011-12-30 21:15:51 +00005659 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005660 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005661 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005662 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005663 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005664 }
5665
Richard Smithf3e9e432011-11-07 09:22:26 +00005666 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005667 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005668 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5669 const LValue &Subobject,
5670 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005671 };
5672} // end anonymous namespace
5673
Richard Smithd62306a2011-11-10 06:34:14 +00005674static bool EvaluateArray(const Expr *E, const LValue &This,
5675 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005676 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005677 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005678}
5679
5680bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5681 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5682 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005683 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005684
Richard Smithca2cfbf2011-12-22 01:07:19 +00005685 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5686 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005687 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005688 LValue LV;
5689 if (!EvaluateLValue(E->getInit(0), LV, Info))
5690 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005691 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005692 LV.moveInto(Val);
5693 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005694 }
5695
Richard Smith253c2a32012-01-27 01:14:48 +00005696 bool Success = true;
5697
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005698 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5699 "zero-initialized array shouldn't have any initialized elts");
5700 APValue Filler;
5701 if (Result.isArray() && Result.hasArrayFiller())
5702 Filler = Result.getArrayFiller();
5703
Richard Smith9543c5e2013-04-22 14:44:29 +00005704 unsigned NumEltsToInit = E->getNumInits();
5705 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005706 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005707
5708 // If the initializer might depend on the array index, run it for each
5709 // array element. For now, just whitelist non-class value-initialization.
5710 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5711 NumEltsToInit = NumElts;
5712
5713 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005714
5715 // If the array was previously zero-initialized, preserve the
5716 // zero-initialized values.
5717 if (!Filler.isUninit()) {
5718 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5719 Result.getArrayInitializedElt(I) = Filler;
5720 if (Result.hasArrayFiller())
5721 Result.getArrayFiller() = Filler;
5722 }
5723
Richard Smithd62306a2011-11-10 06:34:14 +00005724 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005725 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005726 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5727 const Expr *Init =
5728 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005729 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005730 Info, Subobject, Init) ||
5731 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005732 CAT->getElementType(), 1)) {
5733 if (!Info.keepEvaluatingAfterFailure())
5734 return false;
5735 Success = false;
5736 }
Richard Smithd62306a2011-11-10 06:34:14 +00005737 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005738
Richard Smith9543c5e2013-04-22 14:44:29 +00005739 if (!Result.hasArrayFiller())
5740 return Success;
5741
5742 // If we get here, we have a trivial filler, which we can just evaluate
5743 // once and splat over the rest of the array elements.
5744 assert(FillerExpr && "no array filler for incomplete init list");
5745 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5746 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005747}
5748
Richard Smith027bf112011-11-17 22:56:20 +00005749bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005750 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5751}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005752
Richard Smith9543c5e2013-04-22 14:44:29 +00005753bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5754 const LValue &Subobject,
5755 APValue *Value,
5756 QualType Type) {
5757 bool HadZeroInit = !Value->isUninit();
5758
5759 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5760 unsigned N = CAT->getSize().getZExtValue();
5761
5762 // Preserve the array filler if we had prior zero-initialization.
5763 APValue Filler =
5764 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5765 : APValue();
5766
5767 *Value = APValue(APValue::UninitArray(), N, N);
5768
5769 if (HadZeroInit)
5770 for (unsigned I = 0; I != N; ++I)
5771 Value->getArrayInitializedElt(I) = Filler;
5772
5773 // Initialize the elements.
5774 LValue ArrayElt = Subobject;
5775 ArrayElt.addArray(Info, E, CAT);
5776 for (unsigned I = 0; I != N; ++I)
5777 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5778 CAT->getElementType()) ||
5779 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5780 CAT->getElementType(), 1))
5781 return false;
5782
5783 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005784 }
Richard Smith027bf112011-11-17 22:56:20 +00005785
Richard Smith9543c5e2013-04-22 14:44:29 +00005786 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005787 return Error(E);
5788
Richard Smith027bf112011-11-17 22:56:20 +00005789 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005790
Richard Smithfddd3842011-12-30 21:15:51 +00005791 bool ZeroInit = E->requiresZeroInitialization();
5792 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005793 if (HadZeroInit)
5794 return true;
5795
Richard Smithda3f4fd2014-03-05 23:32:50 +00005796 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5797 ImplicitValueInitExpr VIE(Type);
5798 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005799 }
5800
Craig Topper36250ad2014-05-12 05:36:57 +00005801 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005802 FD->getBody(Definition);
5803
Richard Smith357362d2011-12-13 06:39:58 +00005804 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5805 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005806
Richard Smith9eae7232012-01-12 18:54:33 +00005807 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005808 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005809 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005810 return false;
5811 }
5812
Craig Topper5fc8fc22014-08-27 06:28:36 +00005813 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005814 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005815 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005816 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005817}
5818
Richard Smithf3e9e432011-11-07 09:22:26 +00005819//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005820// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005821//
5822// As a GNU extension, we support casting pointers to sufficiently-wide integer
5823// types and back in constant folding. Integer values are thus represented
5824// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005825//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005826
5827namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005828class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005829 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005830 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005831public:
Richard Smith2e312c82012-03-03 22:46:17 +00005832 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005833 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005834
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005835 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005836 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005837 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005838 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005839 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005840 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005841 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005842 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005843 return true;
5844 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005845 bool Success(const llvm::APSInt &SI, const Expr *E) {
5846 return Success(SI, E, Result);
5847 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005848
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005849 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005850 assert(E->getType()->isIntegralOrEnumerationType() &&
5851 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005852 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005853 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005854 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005855 Result.getInt().setIsUnsigned(
5856 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005857 return true;
5858 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005859 bool Success(const llvm::APInt &I, const Expr *E) {
5860 return Success(I, E, Result);
5861 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005862
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005863 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005864 assert(E->getType()->isIntegralOrEnumerationType() &&
5865 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005866 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005867 return true;
5868 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005869 bool Success(uint64_t Value, const Expr *E) {
5870 return Success(Value, E, Result);
5871 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005872
Ken Dyckdbc01912011-03-11 02:13:43 +00005873 bool Success(CharUnits Size, const Expr *E) {
5874 return Success(Size.getQuantity(), E);
5875 }
5876
Richard Smith2e312c82012-03-03 22:46:17 +00005877 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005878 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005879 Result = V;
5880 return true;
5881 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005882 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005883 }
Mike Stump11289f42009-09-09 15:08:12 +00005884
Richard Smithfddd3842011-12-30 21:15:51 +00005885 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005886
Peter Collingbournee9200682011-05-13 03:29:01 +00005887 //===--------------------------------------------------------------------===//
5888 // Visitor Methods
5889 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005890
Chris Lattner7174bf32008-07-12 00:38:25 +00005891 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005892 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005893 }
5894 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005895 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005896 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005897
5898 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5899 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005900 if (CheckReferencedDecl(E, E->getDecl()))
5901 return true;
5902
5903 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005904 }
5905 bool VisitMemberExpr(const MemberExpr *E) {
5906 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005907 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005908 return true;
5909 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005910
5911 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005912 }
5913
Peter Collingbournee9200682011-05-13 03:29:01 +00005914 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005915 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005916 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005917 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005918
Peter Collingbournee9200682011-05-13 03:29:01 +00005919 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005920 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005921
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005922 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005923 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005924 }
Mike Stump11289f42009-09-09 15:08:12 +00005925
Ted Kremeneke65b0862012-03-06 20:05:56 +00005926 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5927 return Success(E->getValue(), E);
5928 }
5929
Richard Smith4ce706a2011-10-11 21:43:33 +00005930 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005931 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005932 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005933 }
5934
Douglas Gregor29c42f22012-02-24 07:38:34 +00005935 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5936 return Success(E->getValue(), E);
5937 }
5938
John Wiegley6242b6a2011-04-28 00:16:57 +00005939 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5940 return Success(E->getValue(), E);
5941 }
5942
John Wiegleyf9f65842011-04-25 06:54:41 +00005943 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5944 return Success(E->getValue(), E);
5945 }
5946
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005947 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005948 bool VisitUnaryImag(const UnaryOperator *E);
5949
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005950 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005951 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005952
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005953private:
Richard Smithce40ad62011-11-12 22:28:03 +00005954 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005955 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005956 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005957};
Chris Lattner05706e882008-07-11 18:11:29 +00005958} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005959
Richard Smith11562c52011-10-28 17:51:58 +00005960/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5961/// produce either the integer value or a pointer.
5962///
5963/// GCC has a heinous extension which folds casts between pointer types and
5964/// pointer-sized integral types. We support this by allowing the evaluation of
5965/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5966/// Some simple arithmetic on such values is supported (they are treated much
5967/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005968static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005969 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005970 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005971 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005972}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005973
Richard Smithf57d8cb2011-12-09 22:58:01 +00005974static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005975 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005976 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005977 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005978 if (!Val.isInt()) {
5979 // FIXME: It would be better to produce the diagnostic for casting
5980 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005981 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005982 return false;
5983 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005984 Result = Val.getInt();
5985 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005986}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005987
Richard Smithf57d8cb2011-12-09 22:58:01 +00005988/// Check whether the given declaration can be directly converted to an integral
5989/// rvalue. If not, no diagnostic is produced; there are other things we can
5990/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005991bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005992 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005993 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005994 // Check for signedness/width mismatches between E type and ECD value.
5995 bool SameSign = (ECD->getInitVal().isSigned()
5996 == E->getType()->isSignedIntegerOrEnumerationType());
5997 bool SameWidth = (ECD->getInitVal().getBitWidth()
5998 == Info.Ctx.getIntWidth(E->getType()));
5999 if (SameSign && SameWidth)
6000 return Success(ECD->getInitVal(), E);
6001 else {
6002 // Get rid of mismatch (otherwise Success assertions will fail)
6003 // by computing a new value matching the type of E.
6004 llvm::APSInt Val = ECD->getInitVal();
6005 if (!SameSign)
6006 Val.setIsSigned(!ECD->getInitVal().isSigned());
6007 if (!SameWidth)
6008 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6009 return Success(Val, E);
6010 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006011 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006012 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006013}
6014
Chris Lattner86ee2862008-10-06 06:40:35 +00006015/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6016/// as GCC.
6017static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6018 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006019 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006020 enum gcc_type_class {
6021 no_type_class = -1,
6022 void_type_class, integer_type_class, char_type_class,
6023 enumeral_type_class, boolean_type_class,
6024 pointer_type_class, reference_type_class, offset_type_class,
6025 real_type_class, complex_type_class,
6026 function_type_class, method_type_class,
6027 record_type_class, union_type_class,
6028 array_type_class, string_type_class,
6029 lang_type_class
6030 };
Mike Stump11289f42009-09-09 15:08:12 +00006031
6032 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006033 // ideal, however it is what gcc does.
6034 if (E->getNumArgs() == 0)
6035 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006036
Chris Lattner86ee2862008-10-06 06:40:35 +00006037 QualType ArgTy = E->getArg(0)->getType();
6038 if (ArgTy->isVoidType())
6039 return void_type_class;
6040 else if (ArgTy->isEnumeralType())
6041 return enumeral_type_class;
6042 else if (ArgTy->isBooleanType())
6043 return boolean_type_class;
6044 else if (ArgTy->isCharType())
6045 return string_type_class; // gcc doesn't appear to use char_type_class
6046 else if (ArgTy->isIntegerType())
6047 return integer_type_class;
6048 else if (ArgTy->isPointerType())
6049 return pointer_type_class;
6050 else if (ArgTy->isReferenceType())
6051 return reference_type_class;
6052 else if (ArgTy->isRealType())
6053 return real_type_class;
6054 else if (ArgTy->isComplexType())
6055 return complex_type_class;
6056 else if (ArgTy->isFunctionType())
6057 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00006058 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00006059 return record_type_class;
6060 else if (ArgTy->isUnionType())
6061 return union_type_class;
6062 else if (ArgTy->isArrayType())
6063 return array_type_class;
6064 else if (ArgTy->isUnionType())
6065 return union_type_class;
6066 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00006067 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006068}
6069
Richard Smith5fab0c92011-12-28 19:48:30 +00006070/// EvaluateBuiltinConstantPForLValue - Determine the result of
6071/// __builtin_constant_p when applied to the given lvalue.
6072///
6073/// An lvalue is only "constant" if it is a pointer or reference to the first
6074/// character of a string literal.
6075template<typename LValue>
6076static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006077 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006078 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6079}
6080
6081/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6082/// GCC as we can manage.
6083static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6084 QualType ArgType = Arg->getType();
6085
6086 // __builtin_constant_p always has one operand. The rules which gcc follows
6087 // are not precisely documented, but are as follows:
6088 //
6089 // - If the operand is of integral, floating, complex or enumeration type,
6090 // and can be folded to a known value of that type, it returns 1.
6091 // - If the operand and can be folded to a pointer to the first character
6092 // of a string literal (or such a pointer cast to an integral type), it
6093 // returns 1.
6094 //
6095 // Otherwise, it returns 0.
6096 //
6097 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6098 // its support for this does not currently work.
6099 if (ArgType->isIntegralOrEnumerationType()) {
6100 Expr::EvalResult Result;
6101 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6102 return false;
6103
6104 APValue &V = Result.Val;
6105 if (V.getKind() == APValue::Int)
6106 return true;
6107
6108 return EvaluateBuiltinConstantPForLValue(V);
6109 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6110 return Arg->isEvaluatable(Ctx);
6111 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6112 LValue LV;
6113 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006114 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006115 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6116 : EvaluatePointer(Arg, LV, Info)) &&
6117 !Status.HasSideEffects)
6118 return EvaluateBuiltinConstantPForLValue(LV);
6119 }
6120
6121 // Anything else isn't considered to be sufficiently constant.
6122 return false;
6123}
6124
John McCall95007602010-05-10 23:27:23 +00006125/// Retrieves the "underlying object type" of the given expression,
6126/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00006127QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
6128 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6129 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006130 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006131 } else if (const Expr *E = B.get<const Expr*>()) {
6132 if (isa<CompoundLiteralExpr>(E))
6133 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006134 }
6135
6136 return QualType();
6137}
6138
Peter Collingbournee9200682011-05-13 03:29:01 +00006139bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00006140 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006141
6142 {
6143 // The operand of __builtin_object_size is never evaluated for side-effects.
6144 // If there are any, but we can determine the pointed-to object anyway, then
6145 // ignore the side-effects.
6146 SpeculativeEvaluationRAII SpeculativeEval(Info);
6147 if (!EvaluatePointer(E->getArg(0), Base, Info))
6148 return false;
6149 }
John McCall95007602010-05-10 23:27:23 +00006150
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006151 if (!Base.getLValueBase()) {
6152 // It is not possible to determine which objects ptr points to at compile time,
6153 // __builtin_object_size should return (size_t) -1 for type 0 or 1
6154 // and (size_t) 0 for type 2 or 3.
6155 llvm::APSInt TypeIntVaue;
6156 const Expr *ExprType = E->getArg(1);
6157 if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
6158 return false;
6159 if (TypeIntVaue == 0 || TypeIntVaue == 1)
6160 return Success(-1, E);
6161 if (TypeIntVaue == 2 || TypeIntVaue == 3)
6162 return Success(0, E);
6163 return Error(E);
6164 }
John McCall95007602010-05-10 23:27:23 +00006165
Richard Smithce40ad62011-11-12 22:28:03 +00006166 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00006167 if (T.isNull() ||
6168 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00006169 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00006170 T->isVariablyModifiedType() ||
6171 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006172 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006173
6174 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
6175 CharUnits Offset = Base.getLValueOffset();
6176
6177 if (!Offset.isNegative() && Offset <= Size)
6178 Size -= Offset;
6179 else
6180 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00006181 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00006182}
6183
Peter Collingbournee9200682011-05-13 03:29:01 +00006184bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006185 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006186 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006187 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006188
6189 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00006190 if (TryEvaluateBuiltinObjectSize(E))
6191 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006192
Richard Smith0421ce72012-08-07 04:16:51 +00006193 // If evaluating the argument has side-effects, we can't determine the size
6194 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6195 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00006196 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00006197 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00006198 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00006199 return Success(0, E);
6200 }
Mike Stump876387b2009-10-27 22:09:17 +00006201
Richard Smith01ade172012-05-23 04:13:20 +00006202 // Expression had no side effects, but we couldn't statically determine the
6203 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006204 switch (Info.EvalMode) {
6205 case EvalInfo::EM_ConstantExpression:
6206 case EvalInfo::EM_PotentialConstantExpression:
6207 case EvalInfo::EM_ConstantFold:
6208 case EvalInfo::EM_EvaluateForOverflow:
6209 case EvalInfo::EM_IgnoreSideEffects:
6210 return Error(E);
6211 case EvalInfo::EM_ConstantExpressionUnevaluated:
6212 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6213 return Success(-1ULL, E);
6214 }
Mike Stump722cedf2009-10-26 18:35:08 +00006215 }
6216
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006217 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006218 case Builtin::BI__builtin_bswap32:
6219 case Builtin::BI__builtin_bswap64: {
6220 APSInt Val;
6221 if (!EvaluateInteger(E->getArg(0), Val, Info))
6222 return false;
6223
6224 return Success(Val.byteSwap(), E);
6225 }
6226
Richard Smith8889a3d2013-06-13 06:26:32 +00006227 case Builtin::BI__builtin_classify_type:
6228 return Success(EvaluateBuiltinClassifyType(E), E);
6229
6230 // FIXME: BI__builtin_clrsb
6231 // FIXME: BI__builtin_clrsbl
6232 // FIXME: BI__builtin_clrsbll
6233
Richard Smith80b3c8e2013-06-13 05:04:16 +00006234 case Builtin::BI__builtin_clz:
6235 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006236 case Builtin::BI__builtin_clzll:
6237 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006238 APSInt Val;
6239 if (!EvaluateInteger(E->getArg(0), Val, Info))
6240 return false;
6241 if (!Val)
6242 return Error(E);
6243
6244 return Success(Val.countLeadingZeros(), E);
6245 }
6246
Richard Smith8889a3d2013-06-13 06:26:32 +00006247 case Builtin::BI__builtin_constant_p:
6248 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6249
Richard Smith80b3c8e2013-06-13 05:04:16 +00006250 case Builtin::BI__builtin_ctz:
6251 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006252 case Builtin::BI__builtin_ctzll:
6253 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006254 APSInt Val;
6255 if (!EvaluateInteger(E->getArg(0), Val, Info))
6256 return false;
6257 if (!Val)
6258 return Error(E);
6259
6260 return Success(Val.countTrailingZeros(), E);
6261 }
6262
Richard Smith8889a3d2013-06-13 06:26:32 +00006263 case Builtin::BI__builtin_eh_return_data_regno: {
6264 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6265 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6266 return Success(Operand, E);
6267 }
6268
6269 case Builtin::BI__builtin_expect:
6270 return Visit(E->getArg(0));
6271
6272 case Builtin::BI__builtin_ffs:
6273 case Builtin::BI__builtin_ffsl:
6274 case Builtin::BI__builtin_ffsll: {
6275 APSInt Val;
6276 if (!EvaluateInteger(E->getArg(0), Val, Info))
6277 return false;
6278
6279 unsigned N = Val.countTrailingZeros();
6280 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6281 }
6282
6283 case Builtin::BI__builtin_fpclassify: {
6284 APFloat Val(0.0);
6285 if (!EvaluateFloat(E->getArg(5), Val, Info))
6286 return false;
6287 unsigned Arg;
6288 switch (Val.getCategory()) {
6289 case APFloat::fcNaN: Arg = 0; break;
6290 case APFloat::fcInfinity: Arg = 1; break;
6291 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6292 case APFloat::fcZero: Arg = 4; break;
6293 }
6294 return Visit(E->getArg(Arg));
6295 }
6296
6297 case Builtin::BI__builtin_isinf_sign: {
6298 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006299 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006300 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6301 }
6302
Richard Smithea3019d2013-10-15 19:07:14 +00006303 case Builtin::BI__builtin_isinf: {
6304 APFloat Val(0.0);
6305 return EvaluateFloat(E->getArg(0), Val, Info) &&
6306 Success(Val.isInfinity() ? 1 : 0, E);
6307 }
6308
6309 case Builtin::BI__builtin_isfinite: {
6310 APFloat Val(0.0);
6311 return EvaluateFloat(E->getArg(0), Val, Info) &&
6312 Success(Val.isFinite() ? 1 : 0, E);
6313 }
6314
6315 case Builtin::BI__builtin_isnan: {
6316 APFloat Val(0.0);
6317 return EvaluateFloat(E->getArg(0), Val, Info) &&
6318 Success(Val.isNaN() ? 1 : 0, E);
6319 }
6320
6321 case Builtin::BI__builtin_isnormal: {
6322 APFloat Val(0.0);
6323 return EvaluateFloat(E->getArg(0), Val, Info) &&
6324 Success(Val.isNormal() ? 1 : 0, E);
6325 }
6326
Richard Smith8889a3d2013-06-13 06:26:32 +00006327 case Builtin::BI__builtin_parity:
6328 case Builtin::BI__builtin_parityl:
6329 case Builtin::BI__builtin_parityll: {
6330 APSInt Val;
6331 if (!EvaluateInteger(E->getArg(0), Val, Info))
6332 return false;
6333
6334 return Success(Val.countPopulation() % 2, E);
6335 }
6336
Richard Smith80b3c8e2013-06-13 05:04:16 +00006337 case Builtin::BI__builtin_popcount:
6338 case Builtin::BI__builtin_popcountl:
6339 case Builtin::BI__builtin_popcountll: {
6340 APSInt Val;
6341 if (!EvaluateInteger(E->getArg(0), Val, Info))
6342 return false;
6343
6344 return Success(Val.countPopulation(), E);
6345 }
6346
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006347 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006348 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006349 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006350 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006351 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6352 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006353 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006354 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006355 case Builtin::BI__builtin_strlen: {
6356 // As an extension, we support __builtin_strlen() as a constant expression,
6357 // and support folding strlen() to a constant.
6358 LValue String;
6359 if (!EvaluatePointer(E->getArg(0), String, Info))
6360 return false;
6361
6362 // Fast path: if it's a string literal, search the string value.
6363 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6364 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006365 // The string literal may have embedded null characters. Find the first
6366 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006367 StringRef Str = S->getBytes();
6368 int64_t Off = String.Offset.getQuantity();
6369 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6370 S->getCharByteWidth() == 1) {
6371 Str = Str.substr(Off);
6372
6373 StringRef::size_type Pos = Str.find(0);
6374 if (Pos != StringRef::npos)
6375 Str = Str.substr(0, Pos);
6376
6377 return Success(Str.size(), E);
6378 }
6379
6380 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006381 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006382
6383 // Slow path: scan the bytes of the string looking for the terminating 0.
6384 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6385 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6386 APValue Char;
6387 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6388 !Char.isInt())
6389 return false;
6390 if (!Char.getInt())
6391 return Success(Strlen, E);
6392 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6393 return false;
6394 }
6395 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006396
Richard Smith01ba47d2012-04-13 00:45:38 +00006397 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006398 case Builtin::BI__atomic_is_lock_free:
6399 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006400 APSInt SizeVal;
6401 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6402 return false;
6403
6404 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6405 // of two less than the maximum inline atomic width, we know it is
6406 // lock-free. If the size isn't a power of two, or greater than the
6407 // maximum alignment where we promote atomics, we know it is not lock-free
6408 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6409 // the answer can only be determined at runtime; for example, 16-byte
6410 // atomics have lock-free implementations on some, but not all,
6411 // x86-64 processors.
6412
6413 // Check power-of-two.
6414 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006415 if (Size.isPowerOfTwo()) {
6416 // Check against inlining width.
6417 unsigned InlineWidthBits =
6418 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6419 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6420 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6421 Size == CharUnits::One() ||
6422 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6423 Expr::NPC_NeverValueDependent))
6424 // OK, we will inline appropriately-aligned operations of this size,
6425 // and _Atomic(T) is appropriately-aligned.
6426 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006427
Richard Smith01ba47d2012-04-13 00:45:38 +00006428 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6429 castAs<PointerType>()->getPointeeType();
6430 if (!PointeeType->isIncompleteType() &&
6431 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6432 // OK, we will inline operations on this object.
6433 return Success(1, E);
6434 }
6435 }
6436 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006437
Richard Smith01ba47d2012-04-13 00:45:38 +00006438 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6439 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006440 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006441 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006442}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006443
Richard Smith8b3497e2011-10-31 01:37:14 +00006444static bool HasSameBase(const LValue &A, const LValue &B) {
6445 if (!A.getLValueBase())
6446 return !B.getLValueBase();
6447 if (!B.getLValueBase())
6448 return false;
6449
Richard Smithce40ad62011-11-12 22:28:03 +00006450 if (A.getLValueBase().getOpaqueValue() !=
6451 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006452 const Decl *ADecl = GetLValueBaseDecl(A);
6453 if (!ADecl)
6454 return false;
6455 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006456 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006457 return false;
6458 }
6459
6460 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006461 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006462}
6463
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006464namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006465
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006466/// \brief Data recursive integer evaluator of certain binary operators.
6467///
6468/// We use a data recursive algorithm for binary operators so that we are able
6469/// to handle extreme cases of chained binary operators without causing stack
6470/// overflow.
6471class DataRecursiveIntBinOpEvaluator {
6472 struct EvalResult {
6473 APValue Val;
6474 bool Failed;
6475
6476 EvalResult() : Failed(false) { }
6477
6478 void swap(EvalResult &RHS) {
6479 Val.swap(RHS.Val);
6480 Failed = RHS.Failed;
6481 RHS.Failed = false;
6482 }
6483 };
6484
6485 struct Job {
6486 const Expr *E;
6487 EvalResult LHSResult; // meaningful only for binary operator expression.
6488 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006489
6490 Job() : StoredInfo(nullptr) {}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006491 void startSpeculativeEval(EvalInfo &Info) {
6492 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006493 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006494 StoredInfo = &Info;
6495 }
6496 ~Job() {
6497 if (StoredInfo) {
6498 StoredInfo->EvalStatus = OldEvalStatus;
6499 }
6500 }
6501 private:
6502 EvalInfo *StoredInfo; // non-null if status changed.
6503 Expr::EvalStatus OldEvalStatus;
6504 };
6505
6506 SmallVector<Job, 16> Queue;
6507
6508 IntExprEvaluator &IntEval;
6509 EvalInfo &Info;
6510 APValue &FinalResult;
6511
6512public:
6513 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6514 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6515
6516 /// \brief True if \param E is a binary operator that we are going to handle
6517 /// data recursively.
6518 /// We handle binary operators that are comma, logical, or that have operands
6519 /// with integral or enumeration type.
6520 static bool shouldEnqueue(const BinaryOperator *E) {
6521 return E->getOpcode() == BO_Comma ||
6522 E->isLogicalOp() ||
6523 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6524 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006525 }
6526
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006527 bool Traverse(const BinaryOperator *E) {
6528 enqueue(E);
6529 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006530 while (!Queue.empty())
6531 process(PrevResult);
6532
6533 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006534
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006535 FinalResult.swap(PrevResult.Val);
6536 return true;
6537 }
6538
6539private:
6540 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6541 return IntEval.Success(Value, E, Result);
6542 }
6543 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6544 return IntEval.Success(Value, E, Result);
6545 }
6546 bool Error(const Expr *E) {
6547 return IntEval.Error(E);
6548 }
6549 bool Error(const Expr *E, diag::kind D) {
6550 return IntEval.Error(E, D);
6551 }
6552
6553 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6554 return Info.CCEDiag(E, D);
6555 }
6556
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006557 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6558 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006559 bool &SuppressRHSDiags);
6560
6561 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6562 const BinaryOperator *E, APValue &Result);
6563
6564 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6565 Result.Failed = !Evaluate(Result.Val, Info, E);
6566 if (Result.Failed)
6567 Result.Val = APValue();
6568 }
6569
Richard Trieuba4d0872012-03-21 23:30:30 +00006570 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006571
6572 void enqueue(const Expr *E) {
6573 E = E->IgnoreParens();
6574 Queue.resize(Queue.size()+1);
6575 Queue.back().E = E;
6576 Queue.back().Kind = Job::AnyExprKind;
6577 }
6578};
6579
6580}
6581
6582bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006583 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006584 bool &SuppressRHSDiags) {
6585 if (E->getOpcode() == BO_Comma) {
6586 // Ignore LHS but note if we could not evaluate it.
6587 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006588 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006589 return true;
6590 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006591
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006592 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006593 bool LHSAsBool;
6594 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006595 // We were able to evaluate the LHS, see if we can get away with not
6596 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006597 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6598 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006599 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006600 }
6601 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006602 LHSResult.Failed = true;
6603
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006604 // Since we weren't able to evaluate the left hand side, it
6605 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006606 if (!Info.noteSideEffect())
6607 return false;
6608
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006609 // We can't evaluate the LHS; however, sometimes the result
6610 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6611 // Don't ignore RHS and suppress diagnostics from this arm.
6612 SuppressRHSDiags = true;
6613 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006614
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006615 return true;
6616 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006617
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006618 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6619 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006620
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006621 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006622 return false; // Ignore RHS;
6623
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006624 return true;
6625}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006626
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006627bool DataRecursiveIntBinOpEvaluator::
6628 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6629 const BinaryOperator *E, APValue &Result) {
6630 if (E->getOpcode() == BO_Comma) {
6631 if (RHSResult.Failed)
6632 return false;
6633 Result = RHSResult.Val;
6634 return true;
6635 }
6636
6637 if (E->isLogicalOp()) {
6638 bool lhsResult, rhsResult;
6639 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6640 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6641
6642 if (LHSIsOK) {
6643 if (RHSIsOK) {
6644 if (E->getOpcode() == BO_LOr)
6645 return Success(lhsResult || rhsResult, E, Result);
6646 else
6647 return Success(lhsResult && rhsResult, E, Result);
6648 }
6649 } else {
6650 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006651 // We can't evaluate the LHS; however, sometimes the result
6652 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6653 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006654 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006655 }
6656 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006657
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006658 return false;
6659 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006660
6661 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6662 E->getRHS()->getType()->isIntegralOrEnumerationType());
6663
6664 if (LHSResult.Failed || RHSResult.Failed)
6665 return false;
6666
6667 const APValue &LHSVal = LHSResult.Val;
6668 const APValue &RHSVal = RHSResult.Val;
6669
6670 // Handle cases like (unsigned long)&a + 4.
6671 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6672 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006673 CharUnits AdditionalOffset =
6674 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006675 if (E->getOpcode() == BO_Add)
6676 Result.getLValueOffset() += AdditionalOffset;
6677 else
6678 Result.getLValueOffset() -= AdditionalOffset;
6679 return true;
6680 }
6681
6682 // Handle cases like 4 + (unsigned long)&a
6683 if (E->getOpcode() == BO_Add &&
6684 RHSVal.isLValue() && LHSVal.isInt()) {
6685 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006686 Result.getLValueOffset() +=
6687 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006688 return true;
6689 }
6690
6691 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6692 // Handle (intptr_t)&&A - (intptr_t)&&B.
6693 if (!LHSVal.getLValueOffset().isZero() ||
6694 !RHSVal.getLValueOffset().isZero())
6695 return false;
6696 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6697 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6698 if (!LHSExpr || !RHSExpr)
6699 return false;
6700 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6701 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6702 if (!LHSAddrExpr || !RHSAddrExpr)
6703 return false;
6704 // Make sure both labels come from the same function.
6705 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6706 RHSAddrExpr->getLabel()->getDeclContext())
6707 return false;
6708 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6709 return true;
6710 }
Richard Smith43e77732013-05-07 04:50:00 +00006711
6712 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006713 if (!LHSVal.isInt() || !RHSVal.isInt())
6714 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006715
6716 // Set up the width and signedness manually, in case it can't be deduced
6717 // from the operation we're performing.
6718 // FIXME: Don't do this in the cases where we can deduce it.
6719 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6720 E->getType()->isUnsignedIntegerOrEnumerationType());
6721 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6722 RHSVal.getInt(), Value))
6723 return false;
6724 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006725}
6726
Richard Trieuba4d0872012-03-21 23:30:30 +00006727void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006728 Job &job = Queue.back();
6729
6730 switch (job.Kind) {
6731 case Job::AnyExprKind: {
6732 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6733 if (shouldEnqueue(Bop)) {
6734 job.Kind = Job::BinOpKind;
6735 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006736 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006737 }
6738 }
6739
6740 EvaluateExpr(job.E, Result);
6741 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006742 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006743 }
6744
6745 case Job::BinOpKind: {
6746 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006747 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006748 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006749 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006750 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006751 }
6752 if (SuppressRHSDiags)
6753 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006754 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006755 job.Kind = Job::BinOpVisitedLHSKind;
6756 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006757 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006758 }
6759
6760 case Job::BinOpVisitedLHSKind: {
6761 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6762 EvalResult RHS;
6763 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006764 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006765 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006766 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006767 }
6768 }
6769
6770 llvm_unreachable("Invalid Job::Kind!");
6771}
6772
6773bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6774 if (E->isAssignmentOp())
6775 return Error(E);
6776
6777 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6778 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006779
Anders Carlssonacc79812008-11-16 07:17:21 +00006780 QualType LHSTy = E->getLHS()->getType();
6781 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006782
6783 if (LHSTy->isAnyComplexType()) {
6784 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006785 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006786
Richard Smith253c2a32012-01-27 01:14:48 +00006787 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6788 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006789 return false;
6790
Richard Smith253c2a32012-01-27 01:14:48 +00006791 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006792 return false;
6793
6794 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006795 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006796 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006797 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006798 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6799
John McCalle3027922010-08-25 11:45:40 +00006800 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006801 return Success((CR_r == APFloat::cmpEqual &&
6802 CR_i == APFloat::cmpEqual), E);
6803 else {
John McCalle3027922010-08-25 11:45:40 +00006804 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006805 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006806 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006807 CR_r == APFloat::cmpLessThan ||
6808 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006809 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006810 CR_i == APFloat::cmpLessThan ||
6811 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006812 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006813 } else {
John McCalle3027922010-08-25 11:45:40 +00006814 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006815 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6816 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6817 else {
John McCalle3027922010-08-25 11:45:40 +00006818 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006819 "Invalid compex comparison.");
6820 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6821 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6822 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006823 }
6824 }
Mike Stump11289f42009-09-09 15:08:12 +00006825
Anders Carlssonacc79812008-11-16 07:17:21 +00006826 if (LHSTy->isRealFloatingType() &&
6827 RHSTy->isRealFloatingType()) {
6828 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006829
Richard Smith253c2a32012-01-27 01:14:48 +00006830 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6831 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006832 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006833
Richard Smith253c2a32012-01-27 01:14:48 +00006834 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006835 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006836
Anders Carlssonacc79812008-11-16 07:17:21 +00006837 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006838
Anders Carlssonacc79812008-11-16 07:17:21 +00006839 switch (E->getOpcode()) {
6840 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006841 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006842 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006843 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006844 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006845 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006846 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006847 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006848 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006849 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006850 E);
John McCalle3027922010-08-25 11:45:40 +00006851 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006852 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006853 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006854 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006855 || CR == APFloat::cmpLessThan
6856 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006857 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006858 }
Mike Stump11289f42009-09-09 15:08:12 +00006859
Eli Friedmana38da572009-04-28 19:17:36 +00006860 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006861 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006862 LValue LHSValue, RHSValue;
6863
6864 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6865 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006866 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006867
Richard Smith253c2a32012-01-27 01:14:48 +00006868 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006869 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006870
Richard Smith8b3497e2011-10-31 01:37:14 +00006871 // Reject differing bases from the normal codepath; we special-case
6872 // comparisons to null.
6873 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006874 if (E->getOpcode() == BO_Sub) {
6875 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006876 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6877 return false;
6878 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006879 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006880 if (!LHSExpr || !RHSExpr)
6881 return false;
6882 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6883 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6884 if (!LHSAddrExpr || !RHSAddrExpr)
6885 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006886 // Make sure both labels come from the same function.
6887 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6888 RHSAddrExpr->getLabel()->getDeclContext())
6889 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006890 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006891 return true;
6892 }
Richard Smith83c68212011-10-31 05:11:32 +00006893 // Inequalities and subtractions between unrelated pointers have
6894 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006895 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006896 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006897 // A constant address may compare equal to the address of a symbol.
6898 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006899 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006900 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6901 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006902 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006903 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006904 // distinct addresses. In clang, the result of such a comparison is
6905 // unspecified, so it is not a constant expression. However, we do know
6906 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006907 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6908 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006909 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006910 // We can't tell whether weak symbols will end up pointing to the same
6911 // object.
6912 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006913 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006914 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006915 // (Note that clang defaults to -fmerge-all-constants, which can
6916 // lead to inconsistent results for comparisons involving the address
6917 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006918 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006919 }
Eli Friedman64004332009-03-23 04:38:34 +00006920
Richard Smith1b470412012-02-01 08:10:20 +00006921 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6922 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6923
Richard Smith84f6dcf2012-02-02 01:16:57 +00006924 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6925 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6926
John McCalle3027922010-08-25 11:45:40 +00006927 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006928 // C++11 [expr.add]p6:
6929 // Unless both pointers point to elements of the same array object, or
6930 // one past the last element of the array object, the behavior is
6931 // undefined.
6932 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6933 !AreElementsOfSameArray(getType(LHSValue.Base),
6934 LHSDesignator, RHSDesignator))
6935 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6936
Chris Lattner882bdf22010-04-20 17:13:14 +00006937 QualType Type = E->getLHS()->getType();
6938 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006939
Richard Smithd62306a2011-11-10 06:34:14 +00006940 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006941 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006942 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006943
Richard Smith84c6b3d2013-09-10 21:34:14 +00006944 // As an extension, a type may have zero size (empty struct or union in
6945 // C, array of zero length). Pointer subtraction in such cases has
6946 // undefined behavior, so is not constant.
6947 if (ElementSize.isZero()) {
6948 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6949 << ElementType;
6950 return false;
6951 }
6952
Richard Smith1b470412012-02-01 08:10:20 +00006953 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6954 // and produce incorrect results when it overflows. Such behavior
6955 // appears to be non-conforming, but is common, so perhaps we should
6956 // assume the standard intended for such cases to be undefined behavior
6957 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006958
Richard Smith1b470412012-02-01 08:10:20 +00006959 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6960 // overflow in the final conversion to ptrdiff_t.
6961 APSInt LHS(
6962 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6963 APSInt RHS(
6964 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6965 APSInt ElemSize(
6966 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6967 APSInt TrueResult = (LHS - RHS) / ElemSize;
6968 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6969
6970 if (Result.extend(65) != TrueResult)
6971 HandleOverflow(Info, E, TrueResult, E->getType());
6972 return Success(Result, E);
6973 }
Richard Smithde21b242012-01-31 06:41:30 +00006974
6975 // C++11 [expr.rel]p3:
6976 // Pointers to void (after pointer conversions) can be compared, with a
6977 // result defined as follows: If both pointers represent the same
6978 // address or are both the null pointer value, the result is true if the
6979 // operator is <= or >= and false otherwise; otherwise the result is
6980 // unspecified.
6981 // We interpret this as applying to pointers to *cv* void.
6982 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006983 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006984 CCEDiag(E, diag::note_constexpr_void_comparison);
6985
Richard Smith84f6dcf2012-02-02 01:16:57 +00006986 // C++11 [expr.rel]p2:
6987 // - If two pointers point to non-static data members of the same object,
6988 // or to subobjects or array elements fo such members, recursively, the
6989 // pointer to the later declared member compares greater provided the
6990 // two members have the same access control and provided their class is
6991 // not a union.
6992 // [...]
6993 // - Otherwise pointer comparisons are unspecified.
6994 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6995 E->isRelationalOp()) {
6996 bool WasArrayIndex;
6997 unsigned Mismatch =
6998 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6999 RHSDesignator, WasArrayIndex);
7000 // At the point where the designators diverge, the comparison has a
7001 // specified value if:
7002 // - we are comparing array indices
7003 // - we are comparing fields of a union, or fields with the same access
7004 // Otherwise, the result is unspecified and thus the comparison is not a
7005 // constant expression.
7006 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7007 Mismatch < RHSDesignator.Entries.size()) {
7008 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7009 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7010 if (!LF && !RF)
7011 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7012 else if (!LF)
7013 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7014 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7015 << RF->getParent() << RF;
7016 else if (!RF)
7017 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7018 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7019 << LF->getParent() << LF;
7020 else if (!LF->getParent()->isUnion() &&
7021 LF->getAccess() != RF->getAccess())
7022 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7023 << LF << LF->getAccess() << RF << RF->getAccess()
7024 << LF->getParent();
7025 }
7026 }
7027
Eli Friedman6c31cb42012-04-16 04:30:08 +00007028 // The comparison here must be unsigned, and performed with the same
7029 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007030 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7031 uint64_t CompareLHS = LHSOffset.getQuantity();
7032 uint64_t CompareRHS = RHSOffset.getQuantity();
7033 assert(PtrSize <= 64 && "Unexpected pointer width");
7034 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7035 CompareLHS &= Mask;
7036 CompareRHS &= Mask;
7037
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007038 // If there is a base and this is a relational operator, we can only
7039 // compare pointers within the object in question; otherwise, the result
7040 // depends on where the object is located in memory.
7041 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7042 QualType BaseTy = getType(LHSValue.Base);
7043 if (BaseTy->isIncompleteType())
7044 return Error(E);
7045 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7046 uint64_t OffsetLimit = Size.getQuantity();
7047 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7048 return Error(E);
7049 }
7050
Richard Smith8b3497e2011-10-31 01:37:14 +00007051 switch (E->getOpcode()) {
7052 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007053 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7054 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7055 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7056 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7057 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7058 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007059 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007060 }
7061 }
Richard Smith7bb00672012-02-01 01:42:44 +00007062
7063 if (LHSTy->isMemberPointerType()) {
7064 assert(E->isEqualityOp() && "unexpected member pointer operation");
7065 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7066
7067 MemberPtr LHSValue, RHSValue;
7068
7069 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7070 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7071 return false;
7072
7073 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7074 return false;
7075
7076 // C++11 [expr.eq]p2:
7077 // If both operands are null, they compare equal. Otherwise if only one is
7078 // null, they compare unequal.
7079 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7080 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7081 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7082 }
7083
7084 // Otherwise if either is a pointer to a virtual member function, the
7085 // result is unspecified.
7086 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7087 if (MD->isVirtual())
7088 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7089 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7090 if (MD->isVirtual())
7091 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7092
7093 // Otherwise they compare equal if and only if they would refer to the
7094 // same member of the same most derived object or the same subobject if
7095 // they were dereferenced with a hypothetical object of the associated
7096 // class type.
7097 bool Equal = LHSValue == RHSValue;
7098 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7099 }
7100
Richard Smithab44d9b2012-02-14 22:35:28 +00007101 if (LHSTy->isNullPtrType()) {
7102 assert(E->isComparisonOp() && "unexpected nullptr operation");
7103 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7104 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7105 // are compared, the result is true of the operator is <=, >= or ==, and
7106 // false otherwise.
7107 BinaryOperator::Opcode Opcode = E->getOpcode();
7108 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7109 }
7110
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007111 assert((!LHSTy->isIntegralOrEnumerationType() ||
7112 !RHSTy->isIntegralOrEnumerationType()) &&
7113 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7114 // We can't continue from here for non-integral types.
7115 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007116}
7117
Peter Collingbournee190dee2011-03-11 19:24:49 +00007118/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7119/// a result as the expression's type.
7120bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7121 const UnaryExprOrTypeTraitExpr *E) {
7122 switch(E->getKind()) {
7123 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007124 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007125 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007126 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007127 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007128 }
Eli Friedman64004332009-03-23 04:38:34 +00007129
Peter Collingbournee190dee2011-03-11 19:24:49 +00007130 case UETT_VecStep: {
7131 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007132
Peter Collingbournee190dee2011-03-11 19:24:49 +00007133 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007134 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007135
Peter Collingbournee190dee2011-03-11 19:24:49 +00007136 // The vec_step built-in functions that take a 3-component
7137 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7138 if (n == 3)
7139 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007140
Peter Collingbournee190dee2011-03-11 19:24:49 +00007141 return Success(n, E);
7142 } else
7143 return Success(1, E);
7144 }
7145
7146 case UETT_SizeOf: {
7147 QualType SrcTy = E->getTypeOfArgument();
7148 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7149 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007150 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7151 SrcTy = Ref->getPointeeType();
7152
Richard Smithd62306a2011-11-10 06:34:14 +00007153 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007154 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007155 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007156 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007157 }
7158 }
7159
7160 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007161}
7162
Peter Collingbournee9200682011-05-13 03:29:01 +00007163bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007164 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007165 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007166 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007167 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007168 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007169 for (unsigned i = 0; i != n; ++i) {
7170 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7171 switch (ON.getKind()) {
7172 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007173 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007174 APSInt IdxResult;
7175 if (!EvaluateInteger(Idx, IdxResult, Info))
7176 return false;
7177 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7178 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007179 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007180 CurrentType = AT->getElementType();
7181 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7182 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007183 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007184 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007185
Douglas Gregor882211c2010-04-28 22:16:22 +00007186 case OffsetOfExpr::OffsetOfNode::Field: {
7187 FieldDecl *MemberDecl = ON.getField();
7188 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007189 if (!RT)
7190 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007191 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007192 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007193 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007194 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007195 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007196 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007197 CurrentType = MemberDecl->getType().getNonReferenceType();
7198 break;
7199 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007200
Douglas Gregor882211c2010-04-28 22:16:22 +00007201 case OffsetOfExpr::OffsetOfNode::Identifier:
7202 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007203
Douglas Gregord1702062010-04-29 00:18:15 +00007204 case OffsetOfExpr::OffsetOfNode::Base: {
7205 CXXBaseSpecifier *BaseSpec = ON.getBase();
7206 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007207 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007208
7209 // Find the layout of the class whose base we are looking into.
7210 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007211 if (!RT)
7212 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007213 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007214 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007215 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7216
7217 // Find the base class itself.
7218 CurrentType = BaseSpec->getType();
7219 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7220 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007221 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007222
7223 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007224 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007225 break;
7226 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007227 }
7228 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007229 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007230}
7231
Chris Lattnere13042c2008-07-11 19:10:17 +00007232bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007233 switch (E->getOpcode()) {
7234 default:
7235 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7236 // See C99 6.6p3.
7237 return Error(E);
7238 case UO_Extension:
7239 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7240 // If so, we could clear the diagnostic ID.
7241 return Visit(E->getSubExpr());
7242 case UO_Plus:
7243 // The result is just the value.
7244 return Visit(E->getSubExpr());
7245 case UO_Minus: {
7246 if (!Visit(E->getSubExpr()))
7247 return false;
7248 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007249 const APSInt &Value = Result.getInt();
7250 if (Value.isSigned() && Value.isMinSignedValue())
7251 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7252 E->getType());
7253 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007254 }
7255 case UO_Not: {
7256 if (!Visit(E->getSubExpr()))
7257 return false;
7258 if (!Result.isInt()) return Error(E);
7259 return Success(~Result.getInt(), E);
7260 }
7261 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007262 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007263 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007264 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007265 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007266 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007267 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007268}
Mike Stump11289f42009-09-09 15:08:12 +00007269
Chris Lattner477c4be2008-07-12 01:15:53 +00007270/// HandleCast - This is used to evaluate implicit or explicit casts where the
7271/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007272bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7273 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007274 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007275 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007276
Eli Friedmanc757de22011-03-25 00:43:55 +00007277 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007278 case CK_BaseToDerived:
7279 case CK_DerivedToBase:
7280 case CK_UncheckedDerivedToBase:
7281 case CK_Dynamic:
7282 case CK_ToUnion:
7283 case CK_ArrayToPointerDecay:
7284 case CK_FunctionToPointerDecay:
7285 case CK_NullToPointer:
7286 case CK_NullToMemberPointer:
7287 case CK_BaseToDerivedMemberPointer:
7288 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007289 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007290 case CK_ConstructorConversion:
7291 case CK_IntegralToPointer:
7292 case CK_ToVoid:
7293 case CK_VectorSplat:
7294 case CK_IntegralToFloating:
7295 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007296 case CK_CPointerToObjCPointerCast:
7297 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007298 case CK_AnyPointerToBlockPointerCast:
7299 case CK_ObjCObjectLValueCast:
7300 case CK_FloatingRealToComplex:
7301 case CK_FloatingComplexToReal:
7302 case CK_FloatingComplexCast:
7303 case CK_FloatingComplexToIntegralComplex:
7304 case CK_IntegralRealToComplex:
7305 case CK_IntegralComplexCast:
7306 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007307 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007308 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007309 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007310 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007311 llvm_unreachable("invalid cast kind for integral value");
7312
Eli Friedman9faf2f92011-03-25 19:07:11 +00007313 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007314 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007315 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007316 case CK_ARCProduceObject:
7317 case CK_ARCConsumeObject:
7318 case CK_ARCReclaimReturnedObject:
7319 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007320 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007321 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007322
Richard Smith4ef685b2012-01-17 21:17:26 +00007323 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007324 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007325 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007326 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007327 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007328
7329 case CK_MemberPointerToBoolean:
7330 case CK_PointerToBoolean:
7331 case CK_IntegralToBoolean:
7332 case CK_FloatingToBoolean:
7333 case CK_FloatingComplexToBoolean:
7334 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007335 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007336 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007337 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007338 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007339 }
7340
Eli Friedmanc757de22011-03-25 00:43:55 +00007341 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007342 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007343 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007344
Eli Friedman742421e2009-02-20 01:15:07 +00007345 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007346 // Allow casts of address-of-label differences if they are no-ops
7347 // or narrowing. (The narrowing case isn't actually guaranteed to
7348 // be constant-evaluatable except in some narrow cases which are hard
7349 // to detect here. We let it through on the assumption the user knows
7350 // what they are doing.)
7351 if (Result.isAddrLabelDiff())
7352 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007353 // Only allow casts of lvalues if they are lossless.
7354 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7355 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007356
Richard Smith911e1422012-01-30 22:27:01 +00007357 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7358 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007359 }
Mike Stump11289f42009-09-09 15:08:12 +00007360
Eli Friedmanc757de22011-03-25 00:43:55 +00007361 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007362 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7363
John McCall45d55e42010-05-07 21:00:08 +00007364 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007365 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007366 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007367
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007368 if (LV.getLValueBase()) {
7369 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007370 // FIXME: Allow a larger integer size than the pointer size, and allow
7371 // narrowing back down to pointer width in subsequent integral casts.
7372 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007373 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007374 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007375
Richard Smithcf74da72011-11-16 07:18:12 +00007376 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007377 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007378 return true;
7379 }
7380
Ken Dyck02990832010-01-15 12:37:54 +00007381 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7382 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007383 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007384 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007385
Eli Friedmanc757de22011-03-25 00:43:55 +00007386 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007387 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007388 if (!EvaluateComplex(SubExpr, C, Info))
7389 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007390 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007391 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007392
Eli Friedmanc757de22011-03-25 00:43:55 +00007393 case CK_FloatingToIntegral: {
7394 APFloat F(0.0);
7395 if (!EvaluateFloat(SubExpr, F, Info))
7396 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007397
Richard Smith357362d2011-12-13 06:39:58 +00007398 APSInt Value;
7399 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7400 return false;
7401 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007402 }
7403 }
Mike Stump11289f42009-09-09 15:08:12 +00007404
Eli Friedmanc757de22011-03-25 00:43:55 +00007405 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007406}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007407
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007408bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7409 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007410 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007411 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7412 return false;
7413 if (!LV.isComplexInt())
7414 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007415 return Success(LV.getComplexIntReal(), E);
7416 }
7417
7418 return Visit(E->getSubExpr());
7419}
7420
Eli Friedman4e7a2412009-02-27 04:45:43 +00007421bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007422 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007423 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007424 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7425 return false;
7426 if (!LV.isComplexInt())
7427 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007428 return Success(LV.getComplexIntImag(), E);
7429 }
7430
Richard Smith4a678122011-10-24 18:44:57 +00007431 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007432 return Success(0, E);
7433}
7434
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007435bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7436 return Success(E->getPackLength(), E);
7437}
7438
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007439bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7440 return Success(E->getValue(), E);
7441}
7442
Chris Lattner05706e882008-07-11 18:11:29 +00007443//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007444// Float Evaluation
7445//===----------------------------------------------------------------------===//
7446
7447namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007448class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007449 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007450 APFloat &Result;
7451public:
7452 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007453 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007454
Richard Smith2e312c82012-03-03 22:46:17 +00007455 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007456 Result = V.getFloat();
7457 return true;
7458 }
Eli Friedman24c01542008-08-22 00:06:13 +00007459
Richard Smithfddd3842011-12-30 21:15:51 +00007460 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007461 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7462 return true;
7463 }
7464
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007465 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007466
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007467 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007468 bool VisitBinaryOperator(const BinaryOperator *E);
7469 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007470 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007471
John McCallb1fb0d32010-05-07 22:08:54 +00007472 bool VisitUnaryReal(const UnaryOperator *E);
7473 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007474
Richard Smithfddd3842011-12-30 21:15:51 +00007475 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007476};
7477} // end anonymous namespace
7478
7479static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007480 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007481 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007482}
7483
Jay Foad39c79802011-01-12 09:06:06 +00007484static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007485 QualType ResultTy,
7486 const Expr *Arg,
7487 bool SNaN,
7488 llvm::APFloat &Result) {
7489 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7490 if (!S) return false;
7491
7492 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7493
7494 llvm::APInt fill;
7495
7496 // Treat empty strings as if they were zero.
7497 if (S->getString().empty())
7498 fill = llvm::APInt(32, 0);
7499 else if (S->getString().getAsInteger(0, fill))
7500 return false;
7501
7502 if (SNaN)
7503 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7504 else
7505 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7506 return true;
7507}
7508
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007509bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007510 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007511 default:
7512 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7513
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007514 case Builtin::BI__builtin_huge_val:
7515 case Builtin::BI__builtin_huge_valf:
7516 case Builtin::BI__builtin_huge_vall:
7517 case Builtin::BI__builtin_inf:
7518 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007519 case Builtin::BI__builtin_infl: {
7520 const llvm::fltSemantics &Sem =
7521 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007522 Result = llvm::APFloat::getInf(Sem);
7523 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007524 }
Mike Stump11289f42009-09-09 15:08:12 +00007525
John McCall16291492010-02-28 13:00:19 +00007526 case Builtin::BI__builtin_nans:
7527 case Builtin::BI__builtin_nansf:
7528 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007529 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7530 true, Result))
7531 return Error(E);
7532 return true;
John McCall16291492010-02-28 13:00:19 +00007533
Chris Lattner0b7282e2008-10-06 06:31:58 +00007534 case Builtin::BI__builtin_nan:
7535 case Builtin::BI__builtin_nanf:
7536 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007537 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007538 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007539 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7540 false, Result))
7541 return Error(E);
7542 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007543
7544 case Builtin::BI__builtin_fabs:
7545 case Builtin::BI__builtin_fabsf:
7546 case Builtin::BI__builtin_fabsl:
7547 if (!EvaluateFloat(E->getArg(0), Result, Info))
7548 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007549
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007550 if (Result.isNegative())
7551 Result.changeSign();
7552 return true;
7553
Richard Smith8889a3d2013-06-13 06:26:32 +00007554 // FIXME: Builtin::BI__builtin_powi
7555 // FIXME: Builtin::BI__builtin_powif
7556 // FIXME: Builtin::BI__builtin_powil
7557
Mike Stump11289f42009-09-09 15:08:12 +00007558 case Builtin::BI__builtin_copysign:
7559 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007560 case Builtin::BI__builtin_copysignl: {
7561 APFloat RHS(0.);
7562 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7563 !EvaluateFloat(E->getArg(1), RHS, Info))
7564 return false;
7565 Result.copySign(RHS);
7566 return true;
7567 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007568 }
7569}
7570
John McCallb1fb0d32010-05-07 22:08:54 +00007571bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007572 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7573 ComplexValue CV;
7574 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7575 return false;
7576 Result = CV.FloatReal;
7577 return true;
7578 }
7579
7580 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007581}
7582
7583bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007584 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7585 ComplexValue CV;
7586 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7587 return false;
7588 Result = CV.FloatImag;
7589 return true;
7590 }
7591
Richard Smith4a678122011-10-24 18:44:57 +00007592 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007593 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7594 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007595 return true;
7596}
7597
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007598bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007599 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007600 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007601 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007602 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007603 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007604 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7605 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007606 Result.changeSign();
7607 return true;
7608 }
7609}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007610
Eli Friedman24c01542008-08-22 00:06:13 +00007611bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007612 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7613 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007614
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007615 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007616 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7617 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007618 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007619 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7620 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007621}
7622
7623bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7624 Result = E->getValue();
7625 return true;
7626}
7627
Peter Collingbournee9200682011-05-13 03:29:01 +00007628bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7629 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007630
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007631 switch (E->getCastKind()) {
7632 default:
Richard Smith11562c52011-10-28 17:51:58 +00007633 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007634
7635 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007636 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007637 return EvaluateInteger(SubExpr, IntResult, Info) &&
7638 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7639 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007640 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007641
7642 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007643 if (!Visit(SubExpr))
7644 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007645 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7646 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007647 }
John McCalld7646252010-11-14 08:17:51 +00007648
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007649 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007650 ComplexValue V;
7651 if (!EvaluateComplex(SubExpr, V, Info))
7652 return false;
7653 Result = V.getComplexFloatReal();
7654 return true;
7655 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007656 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007657}
7658
Eli Friedman24c01542008-08-22 00:06:13 +00007659//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007660// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007661//===----------------------------------------------------------------------===//
7662
7663namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007664class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007665 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007666 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007667
Anders Carlsson537969c2008-11-16 20:27:53 +00007668public:
John McCall93d91dc2010-05-07 17:22:02 +00007669 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007670 : ExprEvaluatorBaseTy(info), Result(Result) {}
7671
Richard Smith2e312c82012-03-03 22:46:17 +00007672 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007673 Result.setFrom(V);
7674 return true;
7675 }
Mike Stump11289f42009-09-09 15:08:12 +00007676
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007677 bool ZeroInitialization(const Expr *E);
7678
Anders Carlsson537969c2008-11-16 20:27:53 +00007679 //===--------------------------------------------------------------------===//
7680 // Visitor Methods
7681 //===--------------------------------------------------------------------===//
7682
Peter Collingbournee9200682011-05-13 03:29:01 +00007683 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007684 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007685 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007686 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007687 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007688};
7689} // end anonymous namespace
7690
John McCall93d91dc2010-05-07 17:22:02 +00007691static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7692 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007693 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007694 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007695}
7696
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007697bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007698 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007699 if (ElemTy->isRealFloatingType()) {
7700 Result.makeComplexFloat();
7701 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7702 Result.FloatReal = Zero;
7703 Result.FloatImag = Zero;
7704 } else {
7705 Result.makeComplexInt();
7706 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7707 Result.IntReal = Zero;
7708 Result.IntImag = Zero;
7709 }
7710 return true;
7711}
7712
Peter Collingbournee9200682011-05-13 03:29:01 +00007713bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7714 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007715
7716 if (SubExpr->getType()->isRealFloatingType()) {
7717 Result.makeComplexFloat();
7718 APFloat &Imag = Result.FloatImag;
7719 if (!EvaluateFloat(SubExpr, Imag, Info))
7720 return false;
7721
7722 Result.FloatReal = APFloat(Imag.getSemantics());
7723 return true;
7724 } else {
7725 assert(SubExpr->getType()->isIntegerType() &&
7726 "Unexpected imaginary literal.");
7727
7728 Result.makeComplexInt();
7729 APSInt &Imag = Result.IntImag;
7730 if (!EvaluateInteger(SubExpr, Imag, Info))
7731 return false;
7732
7733 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7734 return true;
7735 }
7736}
7737
Peter Collingbournee9200682011-05-13 03:29:01 +00007738bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007739
John McCallfcef3cf2010-12-14 17:51:41 +00007740 switch (E->getCastKind()) {
7741 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007742 case CK_BaseToDerived:
7743 case CK_DerivedToBase:
7744 case CK_UncheckedDerivedToBase:
7745 case CK_Dynamic:
7746 case CK_ToUnion:
7747 case CK_ArrayToPointerDecay:
7748 case CK_FunctionToPointerDecay:
7749 case CK_NullToPointer:
7750 case CK_NullToMemberPointer:
7751 case CK_BaseToDerivedMemberPointer:
7752 case CK_DerivedToBaseMemberPointer:
7753 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007754 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007755 case CK_ConstructorConversion:
7756 case CK_IntegralToPointer:
7757 case CK_PointerToIntegral:
7758 case CK_PointerToBoolean:
7759 case CK_ToVoid:
7760 case CK_VectorSplat:
7761 case CK_IntegralCast:
7762 case CK_IntegralToBoolean:
7763 case CK_IntegralToFloating:
7764 case CK_FloatingToIntegral:
7765 case CK_FloatingToBoolean:
7766 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007767 case CK_CPointerToObjCPointerCast:
7768 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007769 case CK_AnyPointerToBlockPointerCast:
7770 case CK_ObjCObjectLValueCast:
7771 case CK_FloatingComplexToReal:
7772 case CK_FloatingComplexToBoolean:
7773 case CK_IntegralComplexToReal:
7774 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007775 case CK_ARCProduceObject:
7776 case CK_ARCConsumeObject:
7777 case CK_ARCReclaimReturnedObject:
7778 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007779 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007780 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007781 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007782 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007783 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007784 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007785
John McCallfcef3cf2010-12-14 17:51:41 +00007786 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007787 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007788 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007789 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007790
7791 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007792 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007793 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007794 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007795
7796 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007797 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007798 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007799 return false;
7800
John McCallfcef3cf2010-12-14 17:51:41 +00007801 Result.makeComplexFloat();
7802 Result.FloatImag = APFloat(Real.getSemantics());
7803 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007804 }
7805
John McCallfcef3cf2010-12-14 17:51:41 +00007806 case CK_FloatingComplexCast: {
7807 if (!Visit(E->getSubExpr()))
7808 return false;
7809
7810 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7811 QualType From
7812 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7813
Richard Smith357362d2011-12-13 06:39:58 +00007814 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7815 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007816 }
7817
7818 case CK_FloatingComplexToIntegralComplex: {
7819 if (!Visit(E->getSubExpr()))
7820 return false;
7821
7822 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7823 QualType From
7824 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7825 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007826 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7827 To, Result.IntReal) &&
7828 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7829 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007830 }
7831
7832 case CK_IntegralRealToComplex: {
7833 APSInt &Real = Result.IntReal;
7834 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7835 return false;
7836
7837 Result.makeComplexInt();
7838 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7839 return true;
7840 }
7841
7842 case CK_IntegralComplexCast: {
7843 if (!Visit(E->getSubExpr()))
7844 return false;
7845
7846 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7847 QualType From
7848 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7849
Richard Smith911e1422012-01-30 22:27:01 +00007850 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7851 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007852 return true;
7853 }
7854
7855 case CK_IntegralComplexToFloatingComplex: {
7856 if (!Visit(E->getSubExpr()))
7857 return false;
7858
Ted Kremenek28831752012-08-23 20:46:57 +00007859 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007860 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007861 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007862 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007863 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7864 To, Result.FloatReal) &&
7865 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7866 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007867 }
7868 }
7869
7870 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007871}
7872
John McCall93d91dc2010-05-07 17:22:02 +00007873bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007874 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007875 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7876
Chandler Carrutha216cad2014-10-11 00:57:18 +00007877 // Track whether the LHS or RHS is real at the type system level. When this is
7878 // the case we can simplify our evaluation strategy.
7879 bool LHSReal = false, RHSReal = false;
7880
7881 bool LHSOK;
7882 if (E->getLHS()->getType()->isRealFloatingType()) {
7883 LHSReal = true;
7884 APFloat &Real = Result.FloatReal;
7885 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
7886 if (LHSOK) {
7887 Result.makeComplexFloat();
7888 Result.FloatImag = APFloat(Real.getSemantics());
7889 }
7890 } else {
7891 LHSOK = Visit(E->getLHS());
7892 }
Richard Smith253c2a32012-01-27 01:14:48 +00007893 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007894 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007895
John McCall93d91dc2010-05-07 17:22:02 +00007896 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00007897 if (E->getRHS()->getType()->isRealFloatingType()) {
7898 RHSReal = true;
7899 APFloat &Real = RHS.FloatReal;
7900 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
7901 return false;
7902 RHS.makeComplexFloat();
7903 RHS.FloatImag = APFloat(Real.getSemantics());
7904 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007905 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007906
Chandler Carrutha216cad2014-10-11 00:57:18 +00007907 assert(!(LHSReal && RHSReal) &&
7908 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007909 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007910 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007911 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007912 if (Result.isComplexFloat()) {
7913 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7914 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00007915 if (LHSReal)
7916 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
7917 else if (!RHSReal)
7918 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7919 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007920 } else {
7921 Result.getComplexIntReal() += RHS.getComplexIntReal();
7922 Result.getComplexIntImag() += RHS.getComplexIntImag();
7923 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007924 break;
John McCalle3027922010-08-25 11:45:40 +00007925 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007926 if (Result.isComplexFloat()) {
7927 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7928 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00007929 if (LHSReal) {
7930 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
7931 Result.getComplexFloatImag().changeSign();
7932 } else if (!RHSReal) {
7933 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7934 APFloat::rmNearestTiesToEven);
7935 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007936 } else {
7937 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7938 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7939 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007940 break;
John McCalle3027922010-08-25 11:45:40 +00007941 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007942 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00007943 // This is an implementation of complex multiplication according to the
7944 // constraints laid out in C11 Annex G. The implemantion uses the
7945 // following naming scheme:
7946 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00007947 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00007948 APFloat &A = LHS.getComplexFloatReal();
7949 APFloat &B = LHS.getComplexFloatImag();
7950 APFloat &C = RHS.getComplexFloatReal();
7951 APFloat &D = RHS.getComplexFloatImag();
7952 APFloat &ResR = Result.getComplexFloatReal();
7953 APFloat &ResI = Result.getComplexFloatImag();
7954 if (LHSReal) {
7955 assert(!RHSReal && "Cannot have two real operands for a complex op!");
7956 ResR = A * C;
7957 ResI = A * D;
7958 } else if (RHSReal) {
7959 ResR = C * A;
7960 ResI = C * B;
7961 } else {
7962 // In the fully general case, we need to handle NaNs and infinities
7963 // robustly.
7964 APFloat AC = A * C;
7965 APFloat BD = B * D;
7966 APFloat AD = A * D;
7967 APFloat BC = B * C;
7968 ResR = AC - BD;
7969 ResI = AD + BC;
7970 if (ResR.isNaN() && ResI.isNaN()) {
7971 bool Recalc = false;
7972 if (A.isInfinity() || B.isInfinity()) {
7973 A = APFloat::copySign(
7974 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
7975 B = APFloat::copySign(
7976 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
7977 if (C.isNaN())
7978 C = APFloat::copySign(APFloat(C.getSemantics()), C);
7979 if (D.isNaN())
7980 D = APFloat::copySign(APFloat(D.getSemantics()), D);
7981 Recalc = true;
7982 }
7983 if (C.isInfinity() || D.isInfinity()) {
7984 C = APFloat::copySign(
7985 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
7986 D = APFloat::copySign(
7987 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
7988 if (A.isNaN())
7989 A = APFloat::copySign(APFloat(A.getSemantics()), A);
7990 if (B.isNaN())
7991 B = APFloat::copySign(APFloat(B.getSemantics()), B);
7992 Recalc = true;
7993 }
7994 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
7995 AD.isInfinity() || BC.isInfinity())) {
7996 if (A.isNaN())
7997 A = APFloat::copySign(APFloat(A.getSemantics()), A);
7998 if (B.isNaN())
7999 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8000 if (C.isNaN())
8001 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8002 if (D.isNaN())
8003 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8004 Recalc = true;
8005 }
8006 if (Recalc) {
8007 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8008 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8009 }
8010 }
8011 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008012 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008013 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008014 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008015 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8016 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008017 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008018 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8019 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8020 }
8021 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008022 case BO_Div:
8023 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008024 // This is an implementation of complex division according to the
8025 // constraints laid out in C11 Annex G. The implemantion uses the
8026 // following naming scheme:
8027 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008028 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008029 APFloat &A = LHS.getComplexFloatReal();
8030 APFloat &B = LHS.getComplexFloatImag();
8031 APFloat &C = RHS.getComplexFloatReal();
8032 APFloat &D = RHS.getComplexFloatImag();
8033 APFloat &ResR = Result.getComplexFloatReal();
8034 APFloat &ResI = Result.getComplexFloatImag();
8035 if (RHSReal) {
8036 ResR = A / C;
8037 ResI = B / C;
8038 } else {
8039 if (LHSReal) {
8040 // No real optimizations we can do here, stub out with zero.
8041 B = APFloat::getZero(A.getSemantics());
8042 }
8043 int DenomLogB = 0;
8044 APFloat MaxCD = maxnum(abs(C), abs(D));
8045 if (MaxCD.isFinite()) {
8046 DenomLogB = ilogb(MaxCD);
8047 C = scalbn(C, -DenomLogB);
8048 D = scalbn(D, -DenomLogB);
8049 }
8050 APFloat Denom = C * C + D * D;
8051 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8052 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8053 if (ResR.isNaN() && ResI.isNaN()) {
8054 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8055 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8056 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8057 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8058 D.isFinite()) {
8059 A = APFloat::copySign(
8060 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8061 B = APFloat::copySign(
8062 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8063 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8064 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8065 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8066 C = APFloat::copySign(
8067 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8068 D = APFloat::copySign(
8069 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8070 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8071 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8072 }
8073 }
8074 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008075 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008076 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8077 return Error(E, diag::note_expr_divide_by_zero);
8078
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008079 ComplexValue LHS = Result;
8080 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8081 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8082 Result.getComplexIntReal() =
8083 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8084 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8085 Result.getComplexIntImag() =
8086 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8087 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8088 }
8089 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008090 }
8091
John McCall93d91dc2010-05-07 17:22:02 +00008092 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008093}
8094
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008095bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8096 // Get the operand value into 'Result'.
8097 if (!Visit(E->getSubExpr()))
8098 return false;
8099
8100 switch (E->getOpcode()) {
8101 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008102 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008103 case UO_Extension:
8104 return true;
8105 case UO_Plus:
8106 // The result is always just the subexpr.
8107 return true;
8108 case UO_Minus:
8109 if (Result.isComplexFloat()) {
8110 Result.getComplexFloatReal().changeSign();
8111 Result.getComplexFloatImag().changeSign();
8112 }
8113 else {
8114 Result.getComplexIntReal() = -Result.getComplexIntReal();
8115 Result.getComplexIntImag() = -Result.getComplexIntImag();
8116 }
8117 return true;
8118 case UO_Not:
8119 if (Result.isComplexFloat())
8120 Result.getComplexFloatImag().changeSign();
8121 else
8122 Result.getComplexIntImag() = -Result.getComplexIntImag();
8123 return true;
8124 }
8125}
8126
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008127bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8128 if (E->getNumInits() == 2) {
8129 if (E->getType()->isComplexType()) {
8130 Result.makeComplexFloat();
8131 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8132 return false;
8133 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8134 return false;
8135 } else {
8136 Result.makeComplexInt();
8137 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8138 return false;
8139 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8140 return false;
8141 }
8142 return true;
8143 }
8144 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8145}
8146
Anders Carlsson537969c2008-11-16 20:27:53 +00008147//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008148// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8149// implicit conversion.
8150//===----------------------------------------------------------------------===//
8151
8152namespace {
8153class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008154 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008155 APValue &Result;
8156public:
8157 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8158 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8159
8160 bool Success(const APValue &V, const Expr *E) {
8161 Result = V;
8162 return true;
8163 }
8164
8165 bool ZeroInitialization(const Expr *E) {
8166 ImplicitValueInitExpr VIE(
8167 E->getType()->castAs<AtomicType>()->getValueType());
8168 return Evaluate(Result, Info, &VIE);
8169 }
8170
8171 bool VisitCastExpr(const CastExpr *E) {
8172 switch (E->getCastKind()) {
8173 default:
8174 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8175 case CK_NonAtomicToAtomic:
8176 return Evaluate(Result, Info, E->getSubExpr());
8177 }
8178 }
8179};
8180} // end anonymous namespace
8181
8182static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8183 assert(E->isRValue() && E->getType()->isAtomicType());
8184 return AtomicExprEvaluator(Info, Result).Visit(E);
8185}
8186
8187//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008188// Void expression evaluation, primarily for a cast to void on the LHS of a
8189// comma operator
8190//===----------------------------------------------------------------------===//
8191
8192namespace {
8193class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008194 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008195public:
8196 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8197
Richard Smith2e312c82012-03-03 22:46:17 +00008198 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008199
8200 bool VisitCastExpr(const CastExpr *E) {
8201 switch (E->getCastKind()) {
8202 default:
8203 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8204 case CK_ToVoid:
8205 VisitIgnoredValue(E->getSubExpr());
8206 return true;
8207 }
8208 }
Hal Finkela8443c32014-07-17 14:49:58 +00008209
8210 bool VisitCallExpr(const CallExpr *E) {
8211 switch (E->getBuiltinCallee()) {
8212 default:
8213 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8214 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008215 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008216 // The argument is not evaluated!
8217 return true;
8218 }
8219 }
Richard Smith42d3af92011-12-07 00:43:50 +00008220};
8221} // end anonymous namespace
8222
8223static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8224 assert(E->isRValue() && E->getType()->isVoidType());
8225 return VoidExprEvaluator(Info).Visit(E);
8226}
8227
8228//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008229// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008230//===----------------------------------------------------------------------===//
8231
Richard Smith2e312c82012-03-03 22:46:17 +00008232static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008233 // In C, function designators are not lvalues, but we evaluate them as if they
8234 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008235 QualType T = E->getType();
8236 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008237 LValue LV;
8238 if (!EvaluateLValue(E, LV, Info))
8239 return false;
8240 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008241 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008242 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008243 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008244 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008245 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008246 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008247 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008248 LValue LV;
8249 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008250 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008251 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008252 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008253 llvm::APFloat F(0.0);
8254 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008255 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008256 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008257 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008258 ComplexValue C;
8259 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008260 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008261 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008262 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008263 MemberPtr P;
8264 if (!EvaluateMemberPointer(E, P, Info))
8265 return false;
8266 P.moveInto(Result);
8267 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008268 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008269 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008270 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008271 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8272 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008273 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008274 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008275 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008276 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008277 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008278 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8279 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008280 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008281 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008282 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008283 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008284 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008285 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008286 if (!EvaluateVoid(E, Info))
8287 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008288 } else if (T->isAtomicType()) {
8289 if (!EvaluateAtomic(E, Result, Info))
8290 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008291 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008292 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008293 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008294 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008295 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008296 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008297 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008298
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008299 return true;
8300}
8301
Richard Smithb228a862012-02-15 02:18:13 +00008302/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8303/// cases, the in-place evaluation is essential, since later initializers for
8304/// an object can indirectly refer to subobjects which were initialized earlier.
8305static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008306 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008307 assert(!E->isValueDependent());
8308
Richard Smith7525ff62013-05-09 07:14:00 +00008309 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008310 return false;
8311
8312 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008313 // Evaluate arrays and record types in-place, so that later initializers can
8314 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008315 if (E->getType()->isArrayType())
8316 return EvaluateArray(E, This, Result, Info);
8317 else if (E->getType()->isRecordType())
8318 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008319 }
8320
8321 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008322 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008323}
8324
Richard Smithf57d8cb2011-12-09 22:58:01 +00008325/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8326/// lvalue-to-rvalue cast if it is an lvalue.
8327static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008328 if (E->getType().isNull())
8329 return false;
8330
Richard Smithfddd3842011-12-30 21:15:51 +00008331 if (!CheckLiteralType(Info, E))
8332 return false;
8333
Richard Smith2e312c82012-03-03 22:46:17 +00008334 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008335 return false;
8336
8337 if (E->isGLValue()) {
8338 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008339 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008340 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008341 return false;
8342 }
8343
Richard Smith2e312c82012-03-03 22:46:17 +00008344 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008345 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008346}
Richard Smith11562c52011-10-28 17:51:58 +00008347
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008348static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8349 const ASTContext &Ctx, bool &IsConst) {
8350 // Fast-path evaluations of integer literals, since we sometimes see files
8351 // containing vast quantities of these.
8352 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8353 Result.Val = APValue(APSInt(L->getValue(),
8354 L->getType()->isUnsignedIntegerType()));
8355 IsConst = true;
8356 return true;
8357 }
James Dennett0492ef02014-03-14 17:44:10 +00008358
8359 // This case should be rare, but we need to check it before we check on
8360 // the type below.
8361 if (Exp->getType().isNull()) {
8362 IsConst = false;
8363 return true;
8364 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008365
8366 // FIXME: Evaluating values of large array and record types can cause
8367 // performance problems. Only do so in C++11 for now.
8368 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8369 Exp->getType()->isRecordType()) &&
8370 !Ctx.getLangOpts().CPlusPlus11) {
8371 IsConst = false;
8372 return true;
8373 }
8374 return false;
8375}
8376
8377
Richard Smith7b553f12011-10-29 00:50:52 +00008378/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008379/// any crazy technique (that has nothing to do with language standards) that
8380/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008381/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8382/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008383bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008384 bool IsConst;
8385 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8386 return IsConst;
8387
Richard Smith6d4c6582013-11-05 22:18:15 +00008388 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008389 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008390}
8391
Jay Foad39c79802011-01-12 09:06:06 +00008392bool Expr::EvaluateAsBooleanCondition(bool &Result,
8393 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008394 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008395 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008396 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008397}
8398
Richard Smith5fab0c92011-12-28 19:48:30 +00008399bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8400 SideEffectsKind AllowSideEffects) const {
8401 if (!getType()->isIntegralOrEnumerationType())
8402 return false;
8403
Richard Smith11562c52011-10-28 17:51:58 +00008404 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008405 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8406 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008407 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008408
Richard Smith11562c52011-10-28 17:51:58 +00008409 Result = ExprResult.Val.getInt();
8410 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008411}
8412
Jay Foad39c79802011-01-12 09:06:06 +00008413bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008414 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008415
John McCall45d55e42010-05-07 21:00:08 +00008416 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008417 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8418 !CheckLValueConstantExpression(Info, getExprLoc(),
8419 Ctx.getLValueReferenceType(getType()), LV))
8420 return false;
8421
Richard Smith2e312c82012-03-03 22:46:17 +00008422 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008423 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008424}
8425
Richard Smithd0b4dd62011-12-19 06:19:21 +00008426bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8427 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008428 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008429 // FIXME: Evaluating initializers for large array and record types can cause
8430 // performance problems. Only do so in C++11 for now.
8431 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008432 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008433 return false;
8434
Richard Smithd0b4dd62011-12-19 06:19:21 +00008435 Expr::EvalStatus EStatus;
8436 EStatus.Diag = &Notes;
8437
Richard Smith6d4c6582013-11-05 22:18:15 +00008438 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008439 InitInfo.setEvaluatingDecl(VD, Value);
8440
8441 LValue LVal;
8442 LVal.set(VD);
8443
Richard Smithfddd3842011-12-30 21:15:51 +00008444 // C++11 [basic.start.init]p2:
8445 // Variables with static storage duration or thread storage duration shall be
8446 // zero-initialized before any other initialization takes place.
8447 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008448 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008449 !VD->getType()->isReferenceType()) {
8450 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008451 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008452 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008453 return false;
8454 }
8455
Richard Smith7525ff62013-05-09 07:14:00 +00008456 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8457 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008458 EStatus.HasSideEffects)
8459 return false;
8460
8461 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8462 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008463}
8464
Richard Smith7b553f12011-10-29 00:50:52 +00008465/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8466/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008467bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008468 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008469 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008470}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008471
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008472APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008473 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008474 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008475 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008476 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008477 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008478 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008479 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008480
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008481 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008482}
John McCall864e3962010-05-07 05:32:02 +00008483
Richard Smithe9ff7702013-11-05 22:23:30 +00008484void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008485 bool IsConst;
8486 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008487 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008488 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008489 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8490 }
8491}
8492
Richard Smithe6c01442013-06-05 00:46:14 +00008493bool Expr::EvalResult::isGlobalLValue() const {
8494 assert(Val.isLValue());
8495 return IsGlobalLValue(Val.getLValueBase());
8496}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008497
8498
John McCall864e3962010-05-07 05:32:02 +00008499/// isIntegerConstantExpr - this recursive routine will test if an expression is
8500/// an integer constant expression.
8501
8502/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8503/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008504
8505// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008506// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8507// and a (possibly null) SourceLocation indicating the location of the problem.
8508//
John McCall864e3962010-05-07 05:32:02 +00008509// Note that to reduce code duplication, this helper does no evaluation
8510// itself; the caller checks whether the expression is evaluatable, and
8511// in the rare cases where CheckICE actually cares about the evaluated
8512// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008513
Dan Gohman28ade552010-07-26 21:25:24 +00008514namespace {
8515
Richard Smith9e575da2012-12-28 13:25:52 +00008516enum ICEKind {
8517 /// This expression is an ICE.
8518 IK_ICE,
8519 /// This expression is not an ICE, but if it isn't evaluated, it's
8520 /// a legal subexpression for an ICE. This return value is used to handle
8521 /// the comma operator in C99 mode, and non-constant subexpressions.
8522 IK_ICEIfUnevaluated,
8523 /// This expression is not an ICE, and is not a legal subexpression for one.
8524 IK_NotICE
8525};
8526
John McCall864e3962010-05-07 05:32:02 +00008527struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008528 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008529 SourceLocation Loc;
8530
Richard Smith9e575da2012-12-28 13:25:52 +00008531 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008532};
8533
Dan Gohman28ade552010-07-26 21:25:24 +00008534}
8535
Richard Smith9e575da2012-12-28 13:25:52 +00008536static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8537
8538static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008539
Craig Toppera31a8822013-08-22 07:09:37 +00008540static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008541 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008542 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008543 !EVResult.Val.isInt())
8544 return ICEDiag(IK_NotICE, E->getLocStart());
8545
John McCall864e3962010-05-07 05:32:02 +00008546 return NoDiag();
8547}
8548
Craig Toppera31a8822013-08-22 07:09:37 +00008549static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008550 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008551 if (!E->getType()->isIntegralOrEnumerationType())
8552 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008553
8554 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008555#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008556#define STMT(Node, Base) case Expr::Node##Class:
8557#define EXPR(Node, Base)
8558#include "clang/AST/StmtNodes.inc"
8559 case Expr::PredefinedExprClass:
8560 case Expr::FloatingLiteralClass:
8561 case Expr::ImaginaryLiteralClass:
8562 case Expr::StringLiteralClass:
8563 case Expr::ArraySubscriptExprClass:
8564 case Expr::MemberExprClass:
8565 case Expr::CompoundAssignOperatorClass:
8566 case Expr::CompoundLiteralExprClass:
8567 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008568 case Expr::DesignatedInitExprClass:
8569 case Expr::ImplicitValueInitExprClass:
8570 case Expr::ParenListExprClass:
8571 case Expr::VAArgExprClass:
8572 case Expr::AddrLabelExprClass:
8573 case Expr::StmtExprClass:
8574 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008575 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008576 case Expr::CXXDynamicCastExprClass:
8577 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008578 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008579 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008580 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008581 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008582 case Expr::CXXThisExprClass:
8583 case Expr::CXXThrowExprClass:
8584 case Expr::CXXNewExprClass:
8585 case Expr::CXXDeleteExprClass:
8586 case Expr::CXXPseudoDestructorExprClass:
8587 case Expr::UnresolvedLookupExprClass:
8588 case Expr::DependentScopeDeclRefExprClass:
8589 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008590 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008591 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008592 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008593 case Expr::CXXTemporaryObjectExprClass:
8594 case Expr::CXXUnresolvedConstructExprClass:
8595 case Expr::CXXDependentScopeMemberExprClass:
8596 case Expr::UnresolvedMemberExprClass:
8597 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008598 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008599 case Expr::ObjCArrayLiteralClass:
8600 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008601 case Expr::ObjCEncodeExprClass:
8602 case Expr::ObjCMessageExprClass:
8603 case Expr::ObjCSelectorExprClass:
8604 case Expr::ObjCProtocolExprClass:
8605 case Expr::ObjCIvarRefExprClass:
8606 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008607 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008608 case Expr::ObjCIsaExprClass:
8609 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008610 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008611 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008612 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008613 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008614 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008615 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008616 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008617 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008618 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008619 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008620 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008621 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008622 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008623 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008624
Richard Smithf137f932014-01-25 20:50:08 +00008625 case Expr::InitListExprClass: {
8626 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8627 // form "T x = { a };" is equivalent to "T x = a;".
8628 // Unless we're initializing a reference, T is a scalar as it is known to be
8629 // of integral or enumeration type.
8630 if (E->isRValue())
8631 if (cast<InitListExpr>(E)->getNumInits() == 1)
8632 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8633 return ICEDiag(IK_NotICE, E->getLocStart());
8634 }
8635
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008636 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008637 case Expr::GNUNullExprClass:
8638 // GCC considers the GNU __null value to be an integral constant expression.
8639 return NoDiag();
8640
John McCall7c454bb2011-07-15 05:09:51 +00008641 case Expr::SubstNonTypeTemplateParmExprClass:
8642 return
8643 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8644
John McCall864e3962010-05-07 05:32:02 +00008645 case Expr::ParenExprClass:
8646 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008647 case Expr::GenericSelectionExprClass:
8648 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008649 case Expr::IntegerLiteralClass:
8650 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008651 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008652 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008653 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008654 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008655 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008656 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008657 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008658 return NoDiag();
8659 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008660 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008661 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8662 // constant expressions, but they can never be ICEs because an ICE cannot
8663 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008664 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008665 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008666 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008667 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008668 }
Richard Smith6365c912012-02-24 22:12:32 +00008669 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008670 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8671 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008672 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008673 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008674 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008675 // Parameter variables are never constants. Without this check,
8676 // getAnyInitializer() can find a default argument, which leads
8677 // to chaos.
8678 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008679 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008680
8681 // C++ 7.1.5.1p2
8682 // A variable of non-volatile const-qualified integral or enumeration
8683 // type initialized by an ICE can be used in ICEs.
8684 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008685 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008686 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008687
Richard Smithd0b4dd62011-12-19 06:19:21 +00008688 const VarDecl *VD;
8689 // Look for a declaration of this variable that has an initializer, and
8690 // check whether it is an ICE.
8691 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8692 return NoDiag();
8693 else
Richard Smith9e575da2012-12-28 13:25:52 +00008694 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008695 }
8696 }
Richard Smith9e575da2012-12-28 13:25:52 +00008697 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008698 }
John McCall864e3962010-05-07 05:32:02 +00008699 case Expr::UnaryOperatorClass: {
8700 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8701 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008702 case UO_PostInc:
8703 case UO_PostDec:
8704 case UO_PreInc:
8705 case UO_PreDec:
8706 case UO_AddrOf:
8707 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008708 // C99 6.6/3 allows increment and decrement within unevaluated
8709 // subexpressions of constant expressions, but they can never be ICEs
8710 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008711 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008712 case UO_Extension:
8713 case UO_LNot:
8714 case UO_Plus:
8715 case UO_Minus:
8716 case UO_Not:
8717 case UO_Real:
8718 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008719 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008720 }
Richard Smith9e575da2012-12-28 13:25:52 +00008721
John McCall864e3962010-05-07 05:32:02 +00008722 // OffsetOf falls through here.
8723 }
8724 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008725 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8726 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8727 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8728 // compliance: we should warn earlier for offsetof expressions with
8729 // array subscripts that aren't ICEs, and if the array subscripts
8730 // are ICEs, the value of the offsetof must be an integer constant.
8731 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008732 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008733 case Expr::UnaryExprOrTypeTraitExprClass: {
8734 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8735 if ((Exp->getKind() == UETT_SizeOf) &&
8736 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008737 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008738 return NoDiag();
8739 }
8740 case Expr::BinaryOperatorClass: {
8741 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8742 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008743 case BO_PtrMemD:
8744 case BO_PtrMemI:
8745 case BO_Assign:
8746 case BO_MulAssign:
8747 case BO_DivAssign:
8748 case BO_RemAssign:
8749 case BO_AddAssign:
8750 case BO_SubAssign:
8751 case BO_ShlAssign:
8752 case BO_ShrAssign:
8753 case BO_AndAssign:
8754 case BO_XorAssign:
8755 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008756 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8757 // constant expressions, but they can never be ICEs because an ICE cannot
8758 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008759 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008760
John McCalle3027922010-08-25 11:45:40 +00008761 case BO_Mul:
8762 case BO_Div:
8763 case BO_Rem:
8764 case BO_Add:
8765 case BO_Sub:
8766 case BO_Shl:
8767 case BO_Shr:
8768 case BO_LT:
8769 case BO_GT:
8770 case BO_LE:
8771 case BO_GE:
8772 case BO_EQ:
8773 case BO_NE:
8774 case BO_And:
8775 case BO_Xor:
8776 case BO_Or:
8777 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008778 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8779 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008780 if (Exp->getOpcode() == BO_Div ||
8781 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008782 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008783 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008784 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008785 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008786 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008787 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008788 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008789 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008790 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008791 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008792 }
8793 }
8794 }
John McCalle3027922010-08-25 11:45:40 +00008795 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008796 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008797 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8798 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008799 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8800 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008801 } else {
8802 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008803 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008804 }
8805 }
Richard Smith9e575da2012-12-28 13:25:52 +00008806 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008807 }
John McCalle3027922010-08-25 11:45:40 +00008808 case BO_LAnd:
8809 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008810 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8811 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008812 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008813 // Rare case where the RHS has a comma "side-effect"; we need
8814 // to actually check the condition to see whether the side
8815 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008816 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008817 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008818 return RHSResult;
8819 return NoDiag();
8820 }
8821
Richard Smith9e575da2012-12-28 13:25:52 +00008822 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008823 }
8824 }
8825 }
8826 case Expr::ImplicitCastExprClass:
8827 case Expr::CStyleCastExprClass:
8828 case Expr::CXXFunctionalCastExprClass:
8829 case Expr::CXXStaticCastExprClass:
8830 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008831 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008832 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008833 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008834 if (isa<ExplicitCastExpr>(E)) {
8835 if (const FloatingLiteral *FL
8836 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8837 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8838 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8839 APSInt IgnoredVal(DestWidth, !DestSigned);
8840 bool Ignored;
8841 // If the value does not fit in the destination type, the behavior is
8842 // undefined, so we are not required to treat it as a constant
8843 // expression.
8844 if (FL->getValue().convertToInteger(IgnoredVal,
8845 llvm::APFloat::rmTowardZero,
8846 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008847 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008848 return NoDiag();
8849 }
8850 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008851 switch (cast<CastExpr>(E)->getCastKind()) {
8852 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008853 case CK_AtomicToNonAtomic:
8854 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008855 case CK_NoOp:
8856 case CK_IntegralToBoolean:
8857 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008858 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008859 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008860 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008861 }
John McCall864e3962010-05-07 05:32:02 +00008862 }
John McCallc07a0c72011-02-17 10:25:35 +00008863 case Expr::BinaryConditionalOperatorClass: {
8864 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8865 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008866 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008867 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008868 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8869 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8870 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008871 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008872 return FalseResult;
8873 }
John McCall864e3962010-05-07 05:32:02 +00008874 case Expr::ConditionalOperatorClass: {
8875 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8876 // If the condition (ignoring parens) is a __builtin_constant_p call,
8877 // then only the true side is actually considered in an integer constant
8878 // expression, and it is fully evaluated. This is an important GNU
8879 // extension. See GCC PR38377 for discussion.
8880 if (const CallExpr *CallCE
8881 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00008882 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00008883 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008884 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008885 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008886 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008887
Richard Smithf57d8cb2011-12-09 22:58:01 +00008888 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8889 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008890
Richard Smith9e575da2012-12-28 13:25:52 +00008891 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008892 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008893 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008894 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008895 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008896 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008897 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008898 return NoDiag();
8899 // Rare case where the diagnostics depend on which side is evaluated
8900 // Note that if we get here, CondResult is 0, and at least one of
8901 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008902 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008903 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008904 return TrueResult;
8905 }
8906 case Expr::CXXDefaultArgExprClass:
8907 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008908 case Expr::CXXDefaultInitExprClass:
8909 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008910 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008911 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008912 }
8913 }
8914
David Blaikiee4d798f2012-01-20 21:50:17 +00008915 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008916}
8917
Richard Smithf57d8cb2011-12-09 22:58:01 +00008918/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008919static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008920 const Expr *E,
8921 llvm::APSInt *Value,
8922 SourceLocation *Loc) {
8923 if (!E->getType()->isIntegralOrEnumerationType()) {
8924 if (Loc) *Loc = E->getExprLoc();
8925 return false;
8926 }
8927
Richard Smith66e05fe2012-01-18 05:21:49 +00008928 APValue Result;
8929 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008930 return false;
8931
Richard Smith66e05fe2012-01-18 05:21:49 +00008932 assert(Result.isInt() && "pointer cast to int is not an ICE");
8933 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008934 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008935}
8936
Craig Toppera31a8822013-08-22 07:09:37 +00008937bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8938 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008939 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00008940 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008941
Richard Smith9e575da2012-12-28 13:25:52 +00008942 ICEDiag D = CheckICE(this, Ctx);
8943 if (D.Kind != IK_ICE) {
8944 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008945 return false;
8946 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008947 return true;
8948}
8949
Craig Toppera31a8822013-08-22 07:09:37 +00008950bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008951 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008952 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008953 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8954
8955 if (!isIntegerConstantExpr(Ctx, Loc))
8956 return false;
8957 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008958 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008959 return true;
8960}
Richard Smith66e05fe2012-01-18 05:21:49 +00008961
Craig Toppera31a8822013-08-22 07:09:37 +00008962bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008963 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008964}
8965
Craig Toppera31a8822013-08-22 07:09:37 +00008966bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008967 SourceLocation *Loc) const {
8968 // We support this checking in C++98 mode in order to diagnose compatibility
8969 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008970 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008971
Richard Smith98a0a492012-02-14 21:38:30 +00008972 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008973 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008974 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008975 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008976 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008977
8978 APValue Scratch;
8979 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8980
8981 if (!Diags.empty()) {
8982 IsConstExpr = false;
8983 if (Loc) *Loc = Diags[0].first;
8984 } else if (!IsConstExpr) {
8985 // FIXME: This shouldn't happen.
8986 if (Loc) *Loc = getExprLoc();
8987 }
8988
8989 return IsConstExpr;
8990}
Richard Smith253c2a32012-01-27 01:14:48 +00008991
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008992bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8993 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00008994 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008995 Expr::EvalStatus Status;
8996 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8997
8998 ArgVector ArgValues(Args.size());
8999 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9000 I != E; ++I) {
9001 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
9002 // If evaluation fails, throw away the argument entirely.
9003 ArgValues[I - Args.begin()] = APValue();
9004 if (Info.EvalStatus.HasSideEffects)
9005 return false;
9006 }
9007
9008 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009009 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009010 ArgValues.data());
9011 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9012}
9013
Richard Smith253c2a32012-01-27 01:14:48 +00009014bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009015 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009016 PartialDiagnosticAt> &Diags) {
9017 // FIXME: It would be useful to check constexpr function templates, but at the
9018 // moment the constant expression evaluator cannot cope with the non-rigorous
9019 // ASTs which we build for dependent expressions.
9020 if (FD->isDependentContext())
9021 return true;
9022
9023 Expr::EvalStatus Status;
9024 Status.Diag = &Diags;
9025
Richard Smith6d4c6582013-11-05 22:18:15 +00009026 EvalInfo Info(FD->getASTContext(), Status,
9027 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009028
9029 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009030 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009031
Richard Smith7525ff62013-05-09 07:14:00 +00009032 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009033 // is a temporary being used as the 'this' pointer.
9034 LValue This;
9035 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009036 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009037
Richard Smith253c2a32012-01-27 01:14:48 +00009038 ArrayRef<const Expr*> Args;
9039
9040 SourceLocation Loc = FD->getLocation();
9041
Richard Smith2e312c82012-03-03 22:46:17 +00009042 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009043 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9044 // Evaluate the call as a constant initializer, to allow the construction
9045 // of objects of non-literal types.
9046 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009047 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009048 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009049 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith253c2a32012-01-27 01:14:48 +00009050 Args, FD->getBody(), Info, Scratch);
9051
9052 return Diags.empty();
9053}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009054
9055bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9056 const FunctionDecl *FD,
9057 SmallVectorImpl<
9058 PartialDiagnosticAt> &Diags) {
9059 Expr::EvalStatus Status;
9060 Status.Diag = &Diags;
9061
9062 EvalInfo Info(FD->getASTContext(), Status,
9063 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9064
9065 // Fabricate a call stack frame to give the arguments a plausible cover story.
9066 ArrayRef<const Expr*> Args;
9067 ArgVector ArgValues(0);
9068 bool Success = EvaluateArgs(Args, ArgValues, Info);
9069 (void)Success;
9070 assert(Success &&
9071 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009072 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009073
9074 APValue ResultScratch;
9075 Evaluate(ResultScratch, Info, E);
9076 return Diags.empty();
9077}