blob: 2fb8c9c137b21a15d64dbe70fec97ba86e79dd04 [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.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000495 EM_PotentialConstantExpressionUnevaluated,
496
497 /// Evaluate as a constant expression. Continue evaluating if we find a
498 /// MemberExpr with a base that can't be evaluated.
499 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000500 } EvalMode;
501
502 /// Are we checking whether the expression is a potential constant
503 /// expression?
504 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000505 return EvalMode == EM_PotentialConstantExpression ||
506 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000507 }
508
509 /// Are we checking an expression for overflow?
510 // FIXME: We should check for any kind of undefined or suspicious behavior
511 // in such constructs, not just overflow.
512 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
513
514 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000515 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000516 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000517 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000518 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
519 EvaluatingDecl((const ValueDecl *)nullptr),
520 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
521 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000522
Richard Smith7525ff62013-05-09 07:14:00 +0000523 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
524 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000525 EvaluatingDeclValue = &Value;
526 }
527
David Blaikiebbafb8a2012-03-11 07:00:24 +0000528 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000529
Richard Smith357362d2011-12-13 06:39:58 +0000530 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000531 // Don't perform any constexpr calls (other than the call we're checking)
532 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000533 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000534 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000535 if (NextCallIndex == 0) {
536 // NextCallIndex has wrapped around.
537 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
538 return false;
539 }
Richard Smith357362d2011-12-13 06:39:58 +0000540 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
541 return true;
542 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
543 << getLangOpts().ConstexprCallDepth;
544 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000545 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000546
Richard Smithb228a862012-02-15 02:18:13 +0000547 CallStackFrame *getCallFrame(unsigned CallIndex) {
548 assert(CallIndex && "no call index in getCallFrame");
549 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
550 // be null in this loop.
551 CallStackFrame *Frame = CurrentCall;
552 while (Frame->Index > CallIndex)
553 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000554 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000555 }
556
Richard Smitha3d3bd22013-05-08 02:12:03 +0000557 bool nextStep(const Stmt *S) {
558 if (!StepsLeft) {
559 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
560 return false;
561 }
562 --StepsLeft;
563 return true;
564 }
565
Richard Smith357362d2011-12-13 06:39:58 +0000566 private:
567 /// Add a diagnostic to the diagnostics list.
568 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
569 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
570 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
571 return EvalStatus.Diag->back().second;
572 }
573
Richard Smithf6f003a2011-12-16 19:06:07 +0000574 /// Add notes containing a call stack to the current point of evaluation.
575 void addCallStack(unsigned Limit);
576
Richard Smith357362d2011-12-13 06:39:58 +0000577 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000578 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000579 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
580 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000581 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000582 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000583 // If we have a prior diagnostic, it will be noting that the expression
584 // isn't a constant expression. This diagnostic is more important,
585 // unless we require this evaluation to produce a constant expression.
586 //
587 // FIXME: We might want to show both diagnostics to the user in
588 // EM_ConstantFold mode.
589 if (!EvalStatus.Diag->empty()) {
590 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000591 case EM_ConstantFold:
592 case EM_IgnoreSideEffects:
593 case EM_EvaluateForOverflow:
594 if (!EvalStatus.HasSideEffects)
595 break;
596 // We've had side-effects; we want the diagnostic from them, not
597 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000598 case EM_ConstantExpression:
599 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000600 case EM_ConstantExpressionUnevaluated:
601 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000602 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000603 HasActiveDiagnostic = false;
604 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000605 }
606 }
607
Richard Smithf6f003a2011-12-16 19:06:07 +0000608 unsigned CallStackNotes = CallStackDepth - 1;
609 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
610 if (Limit)
611 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000612 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000613 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000614
Richard Smith357362d2011-12-13 06:39:58 +0000615 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000616 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000617 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
618 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000619 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000620 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000621 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000622 }
Richard Smith357362d2011-12-13 06:39:58 +0000623 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000624 return OptionalDiagnostic();
625 }
626
Richard Smithce1ec5e2012-03-15 04:53:45 +0000627 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
628 = diag::note_invalid_subexpr_in_const_expr,
629 unsigned ExtraNotes = 0) {
630 if (EvalStatus.Diag)
631 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
632 HasActiveDiagnostic = false;
633 return OptionalDiagnostic();
634 }
635
Richard Smith92b1ce02011-12-12 09:28:41 +0000636 /// Diagnose that the evaluation does not produce a C++11 core constant
637 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000638 ///
639 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
640 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000641 template<typename LocArg>
642 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000643 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000644 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000645 // Don't override a previous diagnostic. Don't bother collecting
646 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000647 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000648 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000649 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000650 }
Richard Smith357362d2011-12-13 06:39:58 +0000651 return Diag(Loc, DiagId, ExtraNotes);
652 }
653
654 /// Add a note to a prior diagnostic.
655 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
656 if (!HasActiveDiagnostic)
657 return OptionalDiagnostic();
658 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000659 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000660
661 /// Add a stack of notes to a prior diagnostic.
662 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
663 if (HasActiveDiagnostic) {
664 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
665 Diags.begin(), Diags.end());
666 }
667 }
Richard Smith253c2a32012-01-27 01:14:48 +0000668
Richard Smith6d4c6582013-11-05 22:18:15 +0000669 /// Should we continue evaluation after encountering a side-effect that we
670 /// couldn't model?
671 bool keepEvaluatingAfterSideEffect() {
672 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000673 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000674 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000675 case EM_EvaluateForOverflow:
676 case EM_IgnoreSideEffects:
677 return true;
678
Richard Smith6d4c6582013-11-05 22:18:15 +0000679 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000680 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000681 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000682 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000683 return false;
684 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000685 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000686 }
687
688 /// Note that we have had a side-effect, and determine whether we should
689 /// keep evaluating.
690 bool noteSideEffect() {
691 EvalStatus.HasSideEffects = true;
692 return keepEvaluatingAfterSideEffect();
693 }
694
Richard Smith253c2a32012-01-27 01:14:48 +0000695 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000696 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000697 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000698 if (!StepsLeft)
699 return false;
700
701 switch (EvalMode) {
702 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000703 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000704 case EM_EvaluateForOverflow:
705 return true;
706
707 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000708 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000709 case EM_ConstantFold:
710 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000711 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000712 return false;
713 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000714 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000715 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000716
717 bool allowInvalidBaseExpr() const {
718 return EvalMode == EM_DesignatorFold;
719 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000720 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000721
722 /// Object used to treat all foldable expressions as constant expressions.
723 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000724 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000725 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000726 bool HadNoPriorDiags;
727 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000728
Richard Smith6d4c6582013-11-05 22:18:15 +0000729 explicit FoldConstant(EvalInfo &Info, bool Enabled)
730 : Info(Info),
731 Enabled(Enabled),
732 HadNoPriorDiags(Info.EvalStatus.Diag &&
733 Info.EvalStatus.Diag->empty() &&
734 !Info.EvalStatus.HasSideEffects),
735 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000736 if (Enabled &&
737 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
738 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000740 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000741 void keepDiagnostics() { Enabled = false; }
742 ~FoldConstant() {
743 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000744 !Info.EvalStatus.HasSideEffects)
745 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000746 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000747 }
748 };
Richard Smith17100ba2012-02-16 02:46:34 +0000749
George Burgess IV3a03fab2015-09-04 21:28:13 +0000750 /// RAII object used to treat the current evaluation as the correct pointer
751 /// offset fold for the current EvalMode
752 struct FoldOffsetRAII {
753 EvalInfo &Info;
754 EvalInfo::EvaluationMode OldMode;
755 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
756 : Info(Info), OldMode(Info.EvalMode) {
757 if (!Info.checkingPotentialConstantExpression())
758 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
759 : EvalInfo::EM_ConstantFold;
760 }
761
762 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
763 };
764
Richard Smith17100ba2012-02-16 02:46:34 +0000765 /// RAII object used to suppress diagnostics and side-effects from a
766 /// speculative evaluation.
767 class SpeculativeEvaluationRAII {
768 EvalInfo &Info;
769 Expr::EvalStatus Old;
770
771 public:
772 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000773 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000774 : Info(Info), Old(Info.EvalStatus) {
775 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 // If we're speculatively evaluating, we may have skipped over some
777 // evaluations and missed out a side effect.
778 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000779 }
780 ~SpeculativeEvaluationRAII() {
781 Info.EvalStatus = Old;
782 }
783 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000784
785 /// RAII object wrapping a full-expression or block scope, and handling
786 /// the ending of the lifetime of temporaries created within it.
787 template<bool IsFullExpression>
788 class ScopeRAII {
789 EvalInfo &Info;
790 unsigned OldStackSize;
791 public:
792 ScopeRAII(EvalInfo &Info)
793 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
794 ~ScopeRAII() {
795 // Body moved to a static method to encourage the compiler to inline away
796 // instances of this class.
797 cleanup(Info, OldStackSize);
798 }
799 private:
800 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
801 unsigned NewEnd = OldStackSize;
802 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
803 I != N; ++I) {
804 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
805 // Full-expression cleanup of a lifetime-extended temporary: nothing
806 // to do, just move this cleanup to the right place in the stack.
807 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
808 ++NewEnd;
809 } else {
810 // End the lifetime of the object.
811 Info.CleanupStack[I].endLifetime();
812 }
813 }
814 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
815 Info.CleanupStack.end());
816 }
817 };
818 typedef ScopeRAII<false> BlockScopeRAII;
819 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000820}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000821
Richard Smitha8105bc2012-01-06 16:39:00 +0000822bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
823 CheckSubobjectKind CSK) {
824 if (Invalid)
825 return false;
826 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000827 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000828 << CSK;
829 setInvalid();
830 return false;
831 }
832 return true;
833}
834
835void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
836 const Expr *E, uint64_t N) {
837 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000838 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000839 << static_cast<int>(N) << /*array*/ 0
840 << static_cast<unsigned>(MostDerivedArraySize);
841 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000842 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000843 << static_cast<int>(N) << /*non-array*/ 1;
844 setInvalid();
845}
846
Richard Smithf6f003a2011-12-16 19:06:07 +0000847CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
848 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000849 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000850 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000851 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000852 Info.CurrentCall = this;
853 ++Info.CallStackDepth;
854}
855
856CallStackFrame::~CallStackFrame() {
857 assert(Info.CurrentCall == this && "calls retired out of order");
858 --Info.CallStackDepth;
859 Info.CurrentCall = Caller;
860}
861
Richard Smith08d6a2c2013-07-24 07:11:57 +0000862APValue &CallStackFrame::createTemporary(const void *Key,
863 bool IsLifetimeExtended) {
864 APValue &Result = Temporaries[Key];
865 assert(Result.isUninit() && "temporary created multiple times");
866 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
867 return Result;
868}
869
Richard Smith84401042013-06-03 05:03:02 +0000870static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000871
872void EvalInfo::addCallStack(unsigned Limit) {
873 // Determine which calls to skip, if any.
874 unsigned ActiveCalls = CallStackDepth - 1;
875 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
876 if (Limit && Limit < ActiveCalls) {
877 SkipStart = Limit / 2 + Limit % 2;
878 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000879 }
880
Richard Smithf6f003a2011-12-16 19:06:07 +0000881 // Walk the call stack and add the diagnostics.
882 unsigned CallIdx = 0;
883 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
884 Frame = Frame->Caller, ++CallIdx) {
885 // Skip this call?
886 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
887 if (CallIdx == SkipStart) {
888 // Note that we're skipping calls.
889 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
890 << unsigned(ActiveCalls - Limit);
891 }
892 continue;
893 }
894
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000895 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000896 llvm::raw_svector_ostream Out(Buffer);
897 describeCall(Frame, Out);
898 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
899 }
900}
901
902namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000903 struct ComplexValue {
904 private:
905 bool IsInt;
906
907 public:
908 APSInt IntReal, IntImag;
909 APFloat FloatReal, FloatImag;
910
911 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
912
913 void makeComplexFloat() { IsInt = false; }
914 bool isComplexFloat() const { return !IsInt; }
915 APFloat &getComplexFloatReal() { return FloatReal; }
916 APFloat &getComplexFloatImag() { return FloatImag; }
917
918 void makeComplexInt() { IsInt = true; }
919 bool isComplexInt() const { return IsInt; }
920 APSInt &getComplexIntReal() { return IntReal; }
921 APSInt &getComplexIntImag() { return IntImag; }
922
Richard Smith2e312c82012-03-03 22:46:17 +0000923 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000924 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000925 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000926 else
Richard Smith2e312c82012-03-03 22:46:17 +0000927 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000928 }
Richard Smith2e312c82012-03-03 22:46:17 +0000929 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000930 assert(v.isComplexFloat() || v.isComplexInt());
931 if (v.isComplexFloat()) {
932 makeComplexFloat();
933 FloatReal = v.getComplexFloatReal();
934 FloatImag = v.getComplexFloatImag();
935 } else {
936 makeComplexInt();
937 IntReal = v.getComplexIntReal();
938 IntImag = v.getComplexIntImag();
939 }
940 }
John McCall93d91dc2010-05-07 17:22:02 +0000941 };
John McCall45d55e42010-05-07 21:00:08 +0000942
943 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000944 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000945 CharUnits Offset;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000946 bool InvalidBase : 1;
947 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +0000948 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000949
Richard Smithce40ad62011-11-12 22:28:03 +0000950 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000951 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000952 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000953 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000954 SubobjectDesignator &getLValueDesignator() { return Designator; }
955 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000956
Richard Smith2e312c82012-03-03 22:46:17 +0000957 void moveInto(APValue &V) const {
958 if (Designator.Invalid)
959 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
960 else
961 V = APValue(Base, Offset, Designator.Entries,
962 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000963 }
Richard Smith2e312c82012-03-03 22:46:17 +0000964 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000965 assert(V.isLValue());
966 Base = V.getLValueBase();
967 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +0000968 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +0000969 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000970 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000971 }
972
George Burgess IV3a03fab2015-09-04 21:28:13 +0000973 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +0000974 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000975 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +0000976 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +0000977 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000978 Designator = SubobjectDesignator(getType(B));
979 }
980
George Burgess IV3a03fab2015-09-04 21:28:13 +0000981 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
982 set(B, I, true);
983 }
984
Richard Smitha8105bc2012-01-06 16:39:00 +0000985 // Check that this LValue is not based on a null pointer. If it is, produce
986 // a diagnostic and mark the designator as invalid.
987 bool checkNullPointer(EvalInfo &Info, const Expr *E,
988 CheckSubobjectKind CSK) {
989 if (Designator.Invalid)
990 return false;
991 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000992 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000993 << CSK;
994 Designator.setInvalid();
995 return false;
996 }
997 return true;
998 }
999
1000 // Check this LValue refers to an object. If not, set the designator to be
1001 // invalid and emit a diagnostic.
1002 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001003 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001004 Designator.checkSubobject(Info, E, CSK);
1005 }
1006
1007 void addDecl(EvalInfo &Info, const Expr *E,
1008 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001009 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1010 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001011 }
1012 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001013 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1014 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001015 }
Richard Smith66c96992012-02-18 22:04:06 +00001016 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001017 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1018 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001019 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001020 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001021 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001022 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001023 }
John McCall45d55e42010-05-07 21:00:08 +00001024 };
Richard Smith027bf112011-11-17 22:56:20 +00001025
1026 struct MemberPtr {
1027 MemberPtr() {}
1028 explicit MemberPtr(const ValueDecl *Decl) :
1029 DeclAndIsDerivedMember(Decl, false), Path() {}
1030
1031 /// The member or (direct or indirect) field referred to by this member
1032 /// pointer, or 0 if this is a null member pointer.
1033 const ValueDecl *getDecl() const {
1034 return DeclAndIsDerivedMember.getPointer();
1035 }
1036 /// Is this actually a member of some type derived from the relevant class?
1037 bool isDerivedMember() const {
1038 return DeclAndIsDerivedMember.getInt();
1039 }
1040 /// Get the class which the declaration actually lives in.
1041 const CXXRecordDecl *getContainingRecord() const {
1042 return cast<CXXRecordDecl>(
1043 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1044 }
1045
Richard Smith2e312c82012-03-03 22:46:17 +00001046 void moveInto(APValue &V) const {
1047 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001048 }
Richard Smith2e312c82012-03-03 22:46:17 +00001049 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001050 assert(V.isMemberPointer());
1051 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1052 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1053 Path.clear();
1054 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1055 Path.insert(Path.end(), P.begin(), P.end());
1056 }
1057
1058 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1059 /// whether the member is a member of some class derived from the class type
1060 /// of the member pointer.
1061 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1062 /// Path - The path of base/derived classes from the member declaration's
1063 /// class (exclusive) to the class type of the member pointer (inclusive).
1064 SmallVector<const CXXRecordDecl*, 4> Path;
1065
1066 /// Perform a cast towards the class of the Decl (either up or down the
1067 /// hierarchy).
1068 bool castBack(const CXXRecordDecl *Class) {
1069 assert(!Path.empty());
1070 const CXXRecordDecl *Expected;
1071 if (Path.size() >= 2)
1072 Expected = Path[Path.size() - 2];
1073 else
1074 Expected = getContainingRecord();
1075 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1076 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1077 // if B does not contain the original member and is not a base or
1078 // derived class of the class containing the original member, the result
1079 // of the cast is undefined.
1080 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1081 // (D::*). We consider that to be a language defect.
1082 return false;
1083 }
1084 Path.pop_back();
1085 return true;
1086 }
1087 /// Perform a base-to-derived member pointer cast.
1088 bool castToDerived(const CXXRecordDecl *Derived) {
1089 if (!getDecl())
1090 return true;
1091 if (!isDerivedMember()) {
1092 Path.push_back(Derived);
1093 return true;
1094 }
1095 if (!castBack(Derived))
1096 return false;
1097 if (Path.empty())
1098 DeclAndIsDerivedMember.setInt(false);
1099 return true;
1100 }
1101 /// Perform a derived-to-base member pointer cast.
1102 bool castToBase(const CXXRecordDecl *Base) {
1103 if (!getDecl())
1104 return true;
1105 if (Path.empty())
1106 DeclAndIsDerivedMember.setInt(true);
1107 if (isDerivedMember()) {
1108 Path.push_back(Base);
1109 return true;
1110 }
1111 return castBack(Base);
1112 }
1113 };
Richard Smith357362d2011-12-13 06:39:58 +00001114
Richard Smith7bb00672012-02-01 01:42:44 +00001115 /// Compare two member pointers, which are assumed to be of the same type.
1116 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1117 if (!LHS.getDecl() || !RHS.getDecl())
1118 return !LHS.getDecl() && !RHS.getDecl();
1119 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1120 return false;
1121 return LHS.Path == RHS.Path;
1122 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001123}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001124
Richard Smith2e312c82012-03-03 22:46:17 +00001125static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001126static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1127 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001128 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001129static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1130static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001131static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1132 EvalInfo &Info);
1133static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001134static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001135static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001136 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001137static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001138static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001139static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001140
1141//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001142// Misc utilities
1143//===----------------------------------------------------------------------===//
1144
Richard Smith84401042013-06-03 05:03:02 +00001145/// Produce a string describing the given constexpr call.
1146static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1147 unsigned ArgIndex = 0;
1148 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1149 !isa<CXXConstructorDecl>(Frame->Callee) &&
1150 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1151
1152 if (!IsMemberCall)
1153 Out << *Frame->Callee << '(';
1154
1155 if (Frame->This && IsMemberCall) {
1156 APValue Val;
1157 Frame->This->moveInto(Val);
1158 Val.printPretty(Out, Frame->Info.Ctx,
1159 Frame->This->Designator.MostDerivedType);
1160 // FIXME: Add parens around Val if needed.
1161 Out << "->" << *Frame->Callee << '(';
1162 IsMemberCall = false;
1163 }
1164
1165 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1166 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1167 if (ArgIndex > (unsigned)IsMemberCall)
1168 Out << ", ";
1169
1170 const ParmVarDecl *Param = *I;
1171 const APValue &Arg = Frame->Arguments[ArgIndex];
1172 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1173
1174 if (ArgIndex == 0 && IsMemberCall)
1175 Out << "->" << *Frame->Callee << '(';
1176 }
1177
1178 Out << ')';
1179}
1180
Richard Smithd9f663b2013-04-22 15:31:51 +00001181/// Evaluate an expression to see if it had side-effects, and discard its
1182/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001183/// \return \c true if the caller should keep evaluating.
1184static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001185 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001186 if (!Evaluate(Scratch, Info, E))
1187 // We don't need the value, but we might have skipped a side effect here.
1188 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001189 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001190}
1191
Richard Smith861b5b52013-05-07 23:34:45 +00001192/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1193/// return its existing value.
1194static int64_t getExtValue(const APSInt &Value) {
1195 return Value.isSigned() ? Value.getSExtValue()
1196 : static_cast<int64_t>(Value.getZExtValue());
1197}
1198
Richard Smithd62306a2011-11-10 06:34:14 +00001199/// Should this call expression be treated as a string literal?
1200static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001201 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001202 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1203 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1204}
1205
Richard Smithce40ad62011-11-12 22:28:03 +00001206static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001207 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1208 // constant expression of pointer type that evaluates to...
1209
1210 // ... a null pointer value, or a prvalue core constant expression of type
1211 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001212 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001213
Richard Smithce40ad62011-11-12 22:28:03 +00001214 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1215 // ... the address of an object with static storage duration,
1216 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1217 return VD->hasGlobalStorage();
1218 // ... the address of a function,
1219 return isa<FunctionDecl>(D);
1220 }
1221
1222 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001223 switch (E->getStmtClass()) {
1224 default:
1225 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001226 case Expr::CompoundLiteralExprClass: {
1227 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1228 return CLE->isFileScope() && CLE->isLValue();
1229 }
Richard Smithe6c01442013-06-05 00:46:14 +00001230 case Expr::MaterializeTemporaryExprClass:
1231 // A materialized temporary might have been lifetime-extended to static
1232 // storage duration.
1233 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001234 // A string literal has static storage duration.
1235 case Expr::StringLiteralClass:
1236 case Expr::PredefinedExprClass:
1237 case Expr::ObjCStringLiteralClass:
1238 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001239 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001240 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001241 return true;
1242 case Expr::CallExprClass:
1243 return IsStringLiteralCall(cast<CallExpr>(E));
1244 // For GCC compatibility, &&label has static storage duration.
1245 case Expr::AddrLabelExprClass:
1246 return true;
1247 // A Block literal expression may be used as the initialization value for
1248 // Block variables at global or local static scope.
1249 case Expr::BlockExprClass:
1250 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001251 case Expr::ImplicitValueInitExprClass:
1252 // FIXME:
1253 // We can never form an lvalue with an implicit value initialization as its
1254 // base through expression evaluation, so these only appear in one case: the
1255 // implicit variable declaration we invent when checking whether a constexpr
1256 // constructor can produce a constant expression. We must assume that such
1257 // an expression might be a global lvalue.
1258 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001259 }
John McCall95007602010-05-10 23:27:23 +00001260}
1261
Richard Smithb228a862012-02-15 02:18:13 +00001262static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1263 assert(Base && "no location for a null lvalue");
1264 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1265 if (VD)
1266 Info.Note(VD->getLocation(), diag::note_declared_at);
1267 else
Ted Kremenek28831752012-08-23 20:46:57 +00001268 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001269 diag::note_constexpr_temporary_here);
1270}
1271
Richard Smith80815602011-11-07 05:07:52 +00001272/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001273/// value for an address or reference constant expression. Return true if we
1274/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001275static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1276 QualType Type, const LValue &LVal) {
1277 bool IsReferenceType = Type->isReferenceType();
1278
Richard Smith357362d2011-12-13 06:39:58 +00001279 APValue::LValueBase Base = LVal.getLValueBase();
1280 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1281
Richard Smith0dea49e2012-02-18 04:58:18 +00001282 // Check that the object is a global. Note that the fake 'this' object we
1283 // manufacture when checking potential constant expressions is conservatively
1284 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001285 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001286 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001287 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001288 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1289 << IsReferenceType << !Designator.Entries.empty()
1290 << !!VD << VD;
1291 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001292 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001293 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001294 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001295 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001296 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001297 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001298 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001299 LVal.getLValueCallIndex() == 0) &&
1300 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001301
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001302 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1303 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001304 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001305 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001306 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001307
Hans Wennborg82dd8772014-06-25 22:19:48 +00001308 // A dllimport variable never acts like a constant.
1309 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001310 return false;
1311 }
1312 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1313 // __declspec(dllimport) must be handled very carefully:
1314 // We must never initialize an expression with the thunk in C++.
1315 // Doing otherwise would allow the same id-expression to yield
1316 // different addresses for the same function in different translation
1317 // units. However, this means that we must dynamically initialize the
1318 // expression with the contents of the import address table at runtime.
1319 //
1320 // The C language has no notion of ODR; furthermore, it has no notion of
1321 // dynamic initialization. This means that we are permitted to
1322 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001323 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001324 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001325 }
1326 }
1327
Richard Smitha8105bc2012-01-06 16:39:00 +00001328 // Allow address constant expressions to be past-the-end pointers. This is
1329 // an extension: the standard requires them to point to an object.
1330 if (!IsReferenceType)
1331 return true;
1332
1333 // A reference constant expression must refer to an object.
1334 if (!Base) {
1335 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001336 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001337 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001338 }
1339
Richard Smith357362d2011-12-13 06:39:58 +00001340 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001341 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001342 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001343 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001344 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001345 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001346 }
1347
Richard Smith80815602011-11-07 05:07:52 +00001348 return true;
1349}
1350
Richard Smithfddd3842011-12-30 21:15:51 +00001351/// Check that this core constant expression is of literal type, and if not,
1352/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001353static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001354 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001355 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001356 return true;
1357
Richard Smith7525ff62013-05-09 07:14:00 +00001358 // C++1y: A constant initializer for an object o [...] may also invoke
1359 // constexpr constructors for o and its subobjects even if those objects
1360 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001361 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001362 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001363 return true;
1364
Richard Smithfddd3842011-12-30 21:15:51 +00001365 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001366 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001367 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001368 << E->getType();
1369 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001370 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001371 return false;
1372}
1373
Richard Smith0b0a0b62011-10-29 20:57:55 +00001374/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001375/// constant expression. If not, report an appropriate diagnostic. Does not
1376/// check that the expression is of literal type.
1377static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1378 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001379 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001380 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1381 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001382 return false;
1383 }
1384
Richard Smith77be48a2014-07-31 06:31:19 +00001385 // We allow _Atomic(T) to be initialized from anything that T can be
1386 // initialized from.
1387 if (const AtomicType *AT = Type->getAs<AtomicType>())
1388 Type = AT->getValueType();
1389
Richard Smithb228a862012-02-15 02:18:13 +00001390 // Core issue 1454: For a literal constant expression of array or class type,
1391 // each subobject of its value shall have been initialized by a constant
1392 // expression.
1393 if (Value.isArray()) {
1394 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1395 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1396 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1397 Value.getArrayInitializedElt(I)))
1398 return false;
1399 }
1400 if (!Value.hasArrayFiller())
1401 return true;
1402 return CheckConstantExpression(Info, DiagLoc, EltTy,
1403 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001404 }
Richard Smithb228a862012-02-15 02:18:13 +00001405 if (Value.isUnion() && Value.getUnionField()) {
1406 return CheckConstantExpression(Info, DiagLoc,
1407 Value.getUnionField()->getType(),
1408 Value.getUnionValue());
1409 }
1410 if (Value.isStruct()) {
1411 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1412 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1413 unsigned BaseIndex = 0;
1414 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1415 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1416 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1417 Value.getStructBase(BaseIndex)))
1418 return false;
1419 }
1420 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001421 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001422 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1423 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001424 return false;
1425 }
1426 }
1427
1428 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001429 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001430 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001431 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1432 }
1433
1434 // Everything else is fine.
1435 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001436}
1437
Benjamin Kramer8407df72015-03-09 16:47:52 +00001438static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001439 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001440}
1441
1442static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001443 if (Value.CallIndex)
1444 return false;
1445 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1446 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001447}
1448
Richard Smithcecf1842011-11-01 21:06:14 +00001449static bool IsWeakLValue(const LValue &Value) {
1450 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001451 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001452}
1453
David Majnemerb5116032014-12-09 23:32:34 +00001454static bool isZeroSized(const LValue &Value) {
1455 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001456 if (Decl && isa<VarDecl>(Decl)) {
1457 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001458 if (Ty->isArrayType())
1459 return Ty->isIncompleteType() ||
1460 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001461 }
1462 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001463}
1464
Richard Smith2e312c82012-03-03 22:46:17 +00001465static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001466 // A null base expression indicates a null pointer. These are always
1467 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001468 if (!Value.getLValueBase()) {
1469 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001470 return true;
1471 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001472
Richard Smith027bf112011-11-17 22:56:20 +00001473 // We have a non-null base. These are generally known to be true, but if it's
1474 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001475 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001476 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001477 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001478}
1479
Richard Smith2e312c82012-03-03 22:46:17 +00001480static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001481 switch (Val.getKind()) {
1482 case APValue::Uninitialized:
1483 return false;
1484 case APValue::Int:
1485 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001486 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001487 case APValue::Float:
1488 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001489 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001490 case APValue::ComplexInt:
1491 Result = Val.getComplexIntReal().getBoolValue() ||
1492 Val.getComplexIntImag().getBoolValue();
1493 return true;
1494 case APValue::ComplexFloat:
1495 Result = !Val.getComplexFloatReal().isZero() ||
1496 !Val.getComplexFloatImag().isZero();
1497 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001498 case APValue::LValue:
1499 return EvalPointerValueAsBool(Val, Result);
1500 case APValue::MemberPointer:
1501 Result = Val.getMemberPointerDecl();
1502 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001503 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001504 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001505 case APValue::Struct:
1506 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001507 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001508 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001509 }
1510
Richard Smith11562c52011-10-28 17:51:58 +00001511 llvm_unreachable("unknown APValue kind");
1512}
1513
1514static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1515 EvalInfo &Info) {
1516 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001517 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001518 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001519 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001520 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001521}
1522
Richard Smith357362d2011-12-13 06:39:58 +00001523template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001524static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001525 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001526 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001527 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001528}
1529
1530static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1531 QualType SrcType, const APFloat &Value,
1532 QualType DestType, APSInt &Result) {
1533 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001534 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001535 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001536
Richard Smith357362d2011-12-13 06:39:58 +00001537 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001538 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001539 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1540 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001541 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001542 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001543}
1544
Richard Smith357362d2011-12-13 06:39:58 +00001545static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1546 QualType SrcType, QualType DestType,
1547 APFloat &Result) {
1548 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001549 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001550 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1551 APFloat::rmNearestTiesToEven, &ignored)
1552 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001553 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001554 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001555}
1556
Richard Smith911e1422012-01-30 22:27:01 +00001557static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1558 QualType DestType, QualType SrcType,
1559 APSInt &Value) {
1560 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001561 APSInt Result = Value;
1562 // Figure out if this is a truncate, extend or noop cast.
1563 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001564 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001565 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001566 return Result;
1567}
1568
Richard Smith357362d2011-12-13 06:39:58 +00001569static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1570 QualType SrcType, const APSInt &Value,
1571 QualType DestType, APFloat &Result) {
1572 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1573 if (Result.convertFromAPInt(Value, Value.isSigned(),
1574 APFloat::rmNearestTiesToEven)
1575 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001576 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001577 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001578}
1579
Richard Smith49ca8aa2013-08-06 07:09:20 +00001580static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1581 APValue &Value, const FieldDecl *FD) {
1582 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1583
1584 if (!Value.isInt()) {
1585 // Trying to store a pointer-cast-to-integer into a bitfield.
1586 // FIXME: In this case, we should provide the diagnostic for casting
1587 // a pointer to an integer.
1588 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1589 Info.Diag(E);
1590 return false;
1591 }
1592
1593 APSInt &Int = Value.getInt();
1594 unsigned OldBitWidth = Int.getBitWidth();
1595 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1596 if (NewBitWidth < OldBitWidth)
1597 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1598 return true;
1599}
1600
Eli Friedman803acb32011-12-22 03:51:45 +00001601static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1602 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001603 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001604 if (!Evaluate(SVal, Info, E))
1605 return false;
1606 if (SVal.isInt()) {
1607 Res = SVal.getInt();
1608 return true;
1609 }
1610 if (SVal.isFloat()) {
1611 Res = SVal.getFloat().bitcastToAPInt();
1612 return true;
1613 }
1614 if (SVal.isVector()) {
1615 QualType VecTy = E->getType();
1616 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1617 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1618 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1619 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1620 Res = llvm::APInt::getNullValue(VecSize);
1621 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1622 APValue &Elt = SVal.getVectorElt(i);
1623 llvm::APInt EltAsInt;
1624 if (Elt.isInt()) {
1625 EltAsInt = Elt.getInt();
1626 } else if (Elt.isFloat()) {
1627 EltAsInt = Elt.getFloat().bitcastToAPInt();
1628 } else {
1629 // Don't try to handle vectors of anything other than int or float
1630 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001631 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001632 return false;
1633 }
1634 unsigned BaseEltSize = EltAsInt.getBitWidth();
1635 if (BigEndian)
1636 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1637 else
1638 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1639 }
1640 return true;
1641 }
1642 // Give up if the input isn't an int, float, or vector. For example, we
1643 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001644 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001645 return false;
1646}
1647
Richard Smith43e77732013-05-07 04:50:00 +00001648/// Perform the given integer operation, which is known to need at most BitWidth
1649/// bits, and check for overflow in the original type (if that type was not an
1650/// unsigned type).
1651template<typename Operation>
1652static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1653 const APSInt &LHS, const APSInt &RHS,
1654 unsigned BitWidth, Operation Op) {
1655 if (LHS.isUnsigned())
1656 return Op(LHS, RHS);
1657
1658 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1659 APSInt Result = Value.trunc(LHS.getBitWidth());
1660 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001661 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001662 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1663 diag::warn_integer_constant_overflow)
1664 << Result.toString(10) << E->getType();
1665 else
1666 HandleOverflow(Info, E, Value, E->getType());
1667 }
1668 return Result;
1669}
1670
1671/// Perform the given binary integer operation.
1672static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1673 BinaryOperatorKind Opcode, APSInt RHS,
1674 APSInt &Result) {
1675 switch (Opcode) {
1676 default:
1677 Info.Diag(E);
1678 return false;
1679 case BO_Mul:
1680 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1681 std::multiplies<APSInt>());
1682 return true;
1683 case BO_Add:
1684 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1685 std::plus<APSInt>());
1686 return true;
1687 case BO_Sub:
1688 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1689 std::minus<APSInt>());
1690 return true;
1691 case BO_And: Result = LHS & RHS; return true;
1692 case BO_Xor: Result = LHS ^ RHS; return true;
1693 case BO_Or: Result = LHS | RHS; return true;
1694 case BO_Div:
1695 case BO_Rem:
1696 if (RHS == 0) {
1697 Info.Diag(E, diag::note_expr_divide_by_zero);
1698 return false;
1699 }
1700 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1701 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1702 LHS.isSigned() && LHS.isMinSignedValue())
1703 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1704 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1705 return true;
1706 case BO_Shl: {
1707 if (Info.getLangOpts().OpenCL)
1708 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1709 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1710 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1711 RHS.isUnsigned());
1712 else if (RHS.isSigned() && RHS.isNegative()) {
1713 // During constant-folding, a negative shift is an opposite shift. Such
1714 // a shift is not a constant expression.
1715 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1716 RHS = -RHS;
1717 goto shift_right;
1718 }
1719 shift_left:
1720 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1721 // the shifted type.
1722 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1723 if (SA != RHS) {
1724 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1725 << RHS << E->getType() << LHS.getBitWidth();
1726 } else if (LHS.isSigned()) {
1727 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1728 // operand, and must not overflow the corresponding unsigned type.
1729 if (LHS.isNegative())
1730 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1731 else if (LHS.countLeadingZeros() < SA)
1732 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1733 }
1734 Result = LHS << SA;
1735 return true;
1736 }
1737 case BO_Shr: {
1738 if (Info.getLangOpts().OpenCL)
1739 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1740 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1741 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1742 RHS.isUnsigned());
1743 else if (RHS.isSigned() && RHS.isNegative()) {
1744 // During constant-folding, a negative shift is an opposite shift. Such a
1745 // shift is not a constant expression.
1746 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1747 RHS = -RHS;
1748 goto shift_left;
1749 }
1750 shift_right:
1751 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1752 // shifted type.
1753 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1754 if (SA != RHS)
1755 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1756 << RHS << E->getType() << LHS.getBitWidth();
1757 Result = LHS >> SA;
1758 return true;
1759 }
1760
1761 case BO_LT: Result = LHS < RHS; return true;
1762 case BO_GT: Result = LHS > RHS; return true;
1763 case BO_LE: Result = LHS <= RHS; return true;
1764 case BO_GE: Result = LHS >= RHS; return true;
1765 case BO_EQ: Result = LHS == RHS; return true;
1766 case BO_NE: Result = LHS != RHS; return true;
1767 }
1768}
1769
Richard Smith861b5b52013-05-07 23:34:45 +00001770/// Perform the given binary floating-point operation, in-place, on LHS.
1771static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1772 APFloat &LHS, BinaryOperatorKind Opcode,
1773 const APFloat &RHS) {
1774 switch (Opcode) {
1775 default:
1776 Info.Diag(E);
1777 return false;
1778 case BO_Mul:
1779 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1780 break;
1781 case BO_Add:
1782 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1783 break;
1784 case BO_Sub:
1785 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1786 break;
1787 case BO_Div:
1788 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1789 break;
1790 }
1791
1792 if (LHS.isInfinity() || LHS.isNaN())
1793 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1794 return true;
1795}
1796
Richard Smitha8105bc2012-01-06 16:39:00 +00001797/// Cast an lvalue referring to a base subobject to a derived class, by
1798/// truncating the lvalue's path to the given length.
1799static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1800 const RecordDecl *TruncatedType,
1801 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001802 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001803
1804 // Check we actually point to a derived class object.
1805 if (TruncatedElements == D.Entries.size())
1806 return true;
1807 assert(TruncatedElements >= D.MostDerivedPathLength &&
1808 "not casting to a derived class");
1809 if (!Result.checkSubobject(Info, E, CSK_Derived))
1810 return false;
1811
1812 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001813 const RecordDecl *RD = TruncatedType;
1814 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001815 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001816 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1817 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001818 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001819 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001820 else
Richard Smithd62306a2011-11-10 06:34:14 +00001821 Result.Offset -= Layout.getBaseClassOffset(Base);
1822 RD = Base;
1823 }
Richard Smith027bf112011-11-17 22:56:20 +00001824 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001825 return true;
1826}
1827
John McCalld7bca762012-05-01 00:38:49 +00001828static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001829 const CXXRecordDecl *Derived,
1830 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001831 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001832 if (!RL) {
1833 if (Derived->isInvalidDecl()) return false;
1834 RL = &Info.Ctx.getASTRecordLayout(Derived);
1835 }
1836
Richard Smithd62306a2011-11-10 06:34:14 +00001837 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001838 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001839 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001840}
1841
Richard Smitha8105bc2012-01-06 16:39:00 +00001842static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001843 const CXXRecordDecl *DerivedDecl,
1844 const CXXBaseSpecifier *Base) {
1845 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1846
John McCalld7bca762012-05-01 00:38:49 +00001847 if (!Base->isVirtual())
1848 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001849
Richard Smitha8105bc2012-01-06 16:39:00 +00001850 SubobjectDesignator &D = Obj.Designator;
1851 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001852 return false;
1853
Richard Smitha8105bc2012-01-06 16:39:00 +00001854 // Extract most-derived object and corresponding type.
1855 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1856 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1857 return false;
1858
1859 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001860 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001861 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1862 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001863 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001864 return true;
1865}
1866
Richard Smith84401042013-06-03 05:03:02 +00001867static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1868 QualType Type, LValue &Result) {
1869 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1870 PathE = E->path_end();
1871 PathI != PathE; ++PathI) {
1872 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1873 *PathI))
1874 return false;
1875 Type = (*PathI)->getType();
1876 }
1877 return true;
1878}
1879
Richard Smithd62306a2011-11-10 06:34:14 +00001880/// Update LVal to refer to the given field, which must be a member of the type
1881/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001882static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001883 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001884 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001885 if (!RL) {
1886 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001887 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001888 }
Richard Smithd62306a2011-11-10 06:34:14 +00001889
1890 unsigned I = FD->getFieldIndex();
1891 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001892 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001893 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001894}
1895
Richard Smith1b78b3d2012-01-25 22:15:11 +00001896/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001897static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001898 LValue &LVal,
1899 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001900 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001901 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001902 return false;
1903 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001904}
1905
Richard Smithd62306a2011-11-10 06:34:14 +00001906/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001907static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1908 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001909 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1910 // extension.
1911 if (Type->isVoidType() || Type->isFunctionType()) {
1912 Size = CharUnits::One();
1913 return true;
1914 }
1915
1916 if (!Type->isConstantSizeType()) {
1917 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001918 // FIXME: Better diagnostic.
1919 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001920 return false;
1921 }
1922
1923 Size = Info.Ctx.getTypeSizeInChars(Type);
1924 return true;
1925}
1926
1927/// Update a pointer value to model pointer arithmetic.
1928/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001929/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001930/// \param LVal - The pointer value to be updated.
1931/// \param EltTy - The pointee type represented by LVal.
1932/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001933static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1934 LValue &LVal, QualType EltTy,
1935 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001936 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001937 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001938 return false;
1939
1940 // Compute the new offset in the appropriate width.
1941 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001942 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001943 return true;
1944}
1945
Richard Smith66c96992012-02-18 22:04:06 +00001946/// Update an lvalue to refer to a component of a complex number.
1947/// \param Info - Information about the ongoing evaluation.
1948/// \param LVal - The lvalue to be updated.
1949/// \param EltTy - The complex number's component type.
1950/// \param Imag - False for the real component, true for the imaginary.
1951static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1952 LValue &LVal, QualType EltTy,
1953 bool Imag) {
1954 if (Imag) {
1955 CharUnits SizeOfComponent;
1956 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1957 return false;
1958 LVal.Offset += SizeOfComponent;
1959 }
1960 LVal.addComplex(Info, E, EltTy, Imag);
1961 return true;
1962}
1963
Richard Smith27908702011-10-24 17:54:18 +00001964/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001965///
1966/// \param Info Information about the ongoing evaluation.
1967/// \param E An expression to be used when printing diagnostics.
1968/// \param VD The variable whose initializer should be obtained.
1969/// \param Frame The frame in which the variable was created. Must be null
1970/// if this variable is not local to the evaluation.
1971/// \param Result Filled in with a pointer to the value of the variable.
1972static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1973 const VarDecl *VD, CallStackFrame *Frame,
1974 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001975 // If this is a parameter to an active constexpr function call, perform
1976 // argument substitution.
1977 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001978 // Assume arguments of a potential constant expression are unknown
1979 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001980 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001981 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001982 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001983 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001984 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001985 }
Richard Smith3229b742013-05-05 21:17:10 +00001986 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001987 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001988 }
Richard Smith27908702011-10-24 17:54:18 +00001989
Richard Smithd9f663b2013-04-22 15:31:51 +00001990 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001991 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001992 Result = Frame->getTemporary(VD);
1993 assert(Result && "missing value for local variable");
1994 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001995 }
1996
Richard Smithd0b4dd62011-12-19 06:19:21 +00001997 // Dig out the initializer, and use the declaration which it's attached to.
1998 const Expr *Init = VD->getAnyInitializer(VD);
1999 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002000 // If we're checking a potential constant expression, the variable could be
2001 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002002 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002003 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002004 return false;
2005 }
2006
Richard Smithd62306a2011-11-10 06:34:14 +00002007 // If we're currently evaluating the initializer of this declaration, use that
2008 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002009 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002010 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002011 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002012 }
2013
Richard Smithcecf1842011-11-01 21:06:14 +00002014 // Never evaluate the initializer of a weak variable. We can't be sure that
2015 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002016 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002017 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002018 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002019 }
Richard Smithcecf1842011-11-01 21:06:14 +00002020
Richard Smithd0b4dd62011-12-19 06:19:21 +00002021 // Check that we can fold the initializer. In C++, we will have already done
2022 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002023 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002024 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002025 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002026 Notes.size() + 1) << VD;
2027 Info.Note(VD->getLocation(), diag::note_declared_at);
2028 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002029 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002030 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002031 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002032 Notes.size() + 1) << VD;
2033 Info.Note(VD->getLocation(), diag::note_declared_at);
2034 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002035 }
Richard Smith27908702011-10-24 17:54:18 +00002036
Richard Smith3229b742013-05-05 21:17:10 +00002037 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002038 return true;
Richard Smith27908702011-10-24 17:54:18 +00002039}
2040
Richard Smith11562c52011-10-28 17:51:58 +00002041static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002042 Qualifiers Quals = T.getQualifiers();
2043 return Quals.hasConst() && !Quals.hasVolatile();
2044}
2045
Richard Smithe97cbd72011-11-11 04:05:33 +00002046/// Get the base index of the given base class within an APValue representing
2047/// the given derived class.
2048static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2049 const CXXRecordDecl *Base) {
2050 Base = Base->getCanonicalDecl();
2051 unsigned Index = 0;
2052 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2053 E = Derived->bases_end(); I != E; ++I, ++Index) {
2054 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2055 return Index;
2056 }
2057
2058 llvm_unreachable("base class missing from derived class's bases list");
2059}
2060
Richard Smith3da88fa2013-04-26 14:36:30 +00002061/// Extract the value of a character from a string literal.
2062static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2063 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002064 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2065 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2066 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002067 const StringLiteral *S = cast<StringLiteral>(Lit);
2068 const ConstantArrayType *CAT =
2069 Info.Ctx.getAsConstantArrayType(S->getType());
2070 assert(CAT && "string literal isn't an array");
2071 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002072 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002073
2074 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002075 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002076 if (Index < S->getLength())
2077 Value = S->getCodeUnit(Index);
2078 return Value;
2079}
2080
Richard Smith3da88fa2013-04-26 14:36:30 +00002081// Expand a string literal into an array of characters.
2082static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2083 APValue &Result) {
2084 const StringLiteral *S = cast<StringLiteral>(Lit);
2085 const ConstantArrayType *CAT =
2086 Info.Ctx.getAsConstantArrayType(S->getType());
2087 assert(CAT && "string literal isn't an array");
2088 QualType CharType = CAT->getElementType();
2089 assert(CharType->isIntegerType() && "unexpected character type");
2090
2091 unsigned Elts = CAT->getSize().getZExtValue();
2092 Result = APValue(APValue::UninitArray(),
2093 std::min(S->getLength(), Elts), Elts);
2094 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2095 CharType->isUnsignedIntegerType());
2096 if (Result.hasArrayFiller())
2097 Result.getArrayFiller() = APValue(Value);
2098 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2099 Value = S->getCodeUnit(I);
2100 Result.getArrayInitializedElt(I) = APValue(Value);
2101 }
2102}
2103
2104// Expand an array so that it has more than Index filled elements.
2105static void expandArray(APValue &Array, unsigned Index) {
2106 unsigned Size = Array.getArraySize();
2107 assert(Index < Size);
2108
2109 // Always at least double the number of elements for which we store a value.
2110 unsigned OldElts = Array.getArrayInitializedElts();
2111 unsigned NewElts = std::max(Index+1, OldElts * 2);
2112 NewElts = std::min(Size, std::max(NewElts, 8u));
2113
2114 // Copy the data across.
2115 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2116 for (unsigned I = 0; I != OldElts; ++I)
2117 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2118 for (unsigned I = OldElts; I != NewElts; ++I)
2119 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2120 if (NewValue.hasArrayFiller())
2121 NewValue.getArrayFiller() = Array.getArrayFiller();
2122 Array.swap(NewValue);
2123}
2124
Richard Smithb01fe402014-09-16 01:24:02 +00002125/// Determine whether a type would actually be read by an lvalue-to-rvalue
2126/// conversion. If it's of class type, we may assume that the copy operation
2127/// is trivial. Note that this is never true for a union type with fields
2128/// (because the copy always "reads" the active member) and always true for
2129/// a non-class type.
2130static bool isReadByLvalueToRvalueConversion(QualType T) {
2131 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2132 if (!RD || (RD->isUnion() && !RD->field_empty()))
2133 return true;
2134 if (RD->isEmpty())
2135 return false;
2136
2137 for (auto *Field : RD->fields())
2138 if (isReadByLvalueToRvalueConversion(Field->getType()))
2139 return true;
2140
2141 for (auto &BaseSpec : RD->bases())
2142 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2143 return true;
2144
2145 return false;
2146}
2147
2148/// Diagnose an attempt to read from any unreadable field within the specified
2149/// type, which might be a class type.
2150static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2151 QualType T) {
2152 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2153 if (!RD)
2154 return false;
2155
2156 if (!RD->hasMutableFields())
2157 return false;
2158
2159 for (auto *Field : RD->fields()) {
2160 // If we're actually going to read this field in some way, then it can't
2161 // be mutable. If we're in a union, then assigning to a mutable field
2162 // (even an empty one) can change the active member, so that's not OK.
2163 // FIXME: Add core issue number for the union case.
2164 if (Field->isMutable() &&
2165 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2166 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2167 Info.Note(Field->getLocation(), diag::note_declared_at);
2168 return true;
2169 }
2170
2171 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2172 return true;
2173 }
2174
2175 for (auto &BaseSpec : RD->bases())
2176 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2177 return true;
2178
2179 // All mutable fields were empty, and thus not actually read.
2180 return false;
2181}
2182
Richard Smith861b5b52013-05-07 23:34:45 +00002183/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002184enum AccessKinds {
2185 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002186 AK_Assign,
2187 AK_Increment,
2188 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002189};
2190
Richard Smith3229b742013-05-05 21:17:10 +00002191/// A handle to a complete object (an object that is not a subobject of
2192/// another object).
2193struct CompleteObject {
2194 /// The value of the complete object.
2195 APValue *Value;
2196 /// The type of the complete object.
2197 QualType Type;
2198
Craig Topper36250ad2014-05-12 05:36:57 +00002199 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002200 CompleteObject(APValue *Value, QualType Type)
2201 : Value(Value), Type(Type) {
2202 assert(Value && "missing value for complete object");
2203 }
2204
Aaron Ballman67347662015-02-15 22:00:28 +00002205 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002206};
2207
Richard Smith3da88fa2013-04-26 14:36:30 +00002208/// Find the designated sub-object of an rvalue.
2209template<typename SubobjectHandler>
2210typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002211findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002212 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002213 if (Sub.Invalid)
2214 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002215 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002216 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002217 if (Info.getLangOpts().CPlusPlus11)
2218 Info.Diag(E, diag::note_constexpr_access_past_end)
2219 << handler.AccessKind;
2220 else
2221 Info.Diag(E);
2222 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002223 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002224
Richard Smith3229b742013-05-05 21:17:10 +00002225 APValue *O = Obj.Value;
2226 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002227 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002228
Richard Smithd62306a2011-11-10 06:34:14 +00002229 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002230 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2231 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002232 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002233 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2234 return handler.failed();
2235 }
2236
Richard Smith49ca8aa2013-08-06 07:09:20 +00002237 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002238 // If we are reading an object of class type, there may still be more
2239 // things we need to check: if there are any mutable subobjects, we
2240 // cannot perform this read. (This only happens when performing a trivial
2241 // copy or assignment.)
2242 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2243 diagnoseUnreadableFields(Info, E, ObjType))
2244 return handler.failed();
2245
Richard Smith49ca8aa2013-08-06 07:09:20 +00002246 if (!handler.found(*O, ObjType))
2247 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002248
Richard Smith49ca8aa2013-08-06 07:09:20 +00002249 // If we modified a bit-field, truncate it to the right width.
2250 if (handler.AccessKind != AK_Read &&
2251 LastField && LastField->isBitField() &&
2252 !truncateBitfieldValue(Info, E, *O, LastField))
2253 return false;
2254
2255 return true;
2256 }
2257
Craig Topper36250ad2014-05-12 05:36:57 +00002258 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002259 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002260 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002261 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002262 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002263 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002264 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002265 // Note, it should not be possible to form a pointer with a valid
2266 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002267 if (Info.getLangOpts().CPlusPlus11)
2268 Info.Diag(E, diag::note_constexpr_access_past_end)
2269 << handler.AccessKind;
2270 else
2271 Info.Diag(E);
2272 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002273 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002274
2275 ObjType = CAT->getElementType();
2276
Richard Smith14a94132012-02-17 03:35:37 +00002277 // An array object is represented as either an Array APValue or as an
2278 // LValue which refers to a string literal.
2279 if (O->isLValue()) {
2280 assert(I == N - 1 && "extracting subobject of character?");
2281 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002282 if (handler.AccessKind != AK_Read)
2283 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2284 *O);
2285 else
2286 return handler.foundString(*O, ObjType, Index);
2287 }
2288
2289 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002290 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002291 else if (handler.AccessKind != AK_Read) {
2292 expandArray(*O, Index);
2293 O = &O->getArrayInitializedElt(Index);
2294 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002295 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002296 } else if (ObjType->isAnyComplexType()) {
2297 // Next subobject is a complex number.
2298 uint64_t Index = Sub.Entries[I].ArrayIndex;
2299 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002300 if (Info.getLangOpts().CPlusPlus11)
2301 Info.Diag(E, diag::note_constexpr_access_past_end)
2302 << handler.AccessKind;
2303 else
2304 Info.Diag(E);
2305 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002306 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002307
2308 bool WasConstQualified = ObjType.isConstQualified();
2309 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2310 if (WasConstQualified)
2311 ObjType.addConst();
2312
Richard Smith66c96992012-02-18 22:04:06 +00002313 assert(I == N - 1 && "extracting subobject of scalar?");
2314 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002315 return handler.found(Index ? O->getComplexIntImag()
2316 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002317 } else {
2318 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002319 return handler.found(Index ? O->getComplexFloatImag()
2320 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002321 }
Richard Smithd62306a2011-11-10 06:34:14 +00002322 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002323 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002324 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002325 << Field;
2326 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002327 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002328 }
2329
Richard Smithd62306a2011-11-10 06:34:14 +00002330 // Next subobject is a class, struct or union field.
2331 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2332 if (RD->isUnion()) {
2333 const FieldDecl *UnionField = O->getUnionField();
2334 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002335 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002336 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2337 << handler.AccessKind << Field << !UnionField << UnionField;
2338 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002339 }
Richard Smithd62306a2011-11-10 06:34:14 +00002340 O = &O->getUnionValue();
2341 } else
2342 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002343
2344 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002345 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002346 if (WasConstQualified && !Field->isMutable())
2347 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002348
2349 if (ObjType.isVolatileQualified()) {
2350 if (Info.getLangOpts().CPlusPlus) {
2351 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002352 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2353 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002354 Info.Note(Field->getLocation(), diag::note_declared_at);
2355 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002356 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002357 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002358 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002359 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002360
2361 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002362 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002363 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002364 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2365 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2366 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002367
2368 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002369 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002370 if (WasConstQualified)
2371 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002372 }
2373 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002374}
2375
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002376namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002377struct ExtractSubobjectHandler {
2378 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002379 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002380
2381 static const AccessKinds AccessKind = AK_Read;
2382
2383 typedef bool result_type;
2384 bool failed() { return false; }
2385 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002386 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002387 return true;
2388 }
2389 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002390 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002391 return true;
2392 }
2393 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002394 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002395 return true;
2396 }
2397 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002398 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002399 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2400 return true;
2401 }
2402};
Richard Smith3229b742013-05-05 21:17:10 +00002403} // end anonymous namespace
2404
Richard Smith3da88fa2013-04-26 14:36:30 +00002405const AccessKinds ExtractSubobjectHandler::AccessKind;
2406
2407/// Extract the designated sub-object of an rvalue.
2408static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002409 const CompleteObject &Obj,
2410 const SubobjectDesignator &Sub,
2411 APValue &Result) {
2412 ExtractSubobjectHandler Handler = { Info, Result };
2413 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002414}
2415
Richard Smith3229b742013-05-05 21:17:10 +00002416namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002417struct ModifySubobjectHandler {
2418 EvalInfo &Info;
2419 APValue &NewVal;
2420 const Expr *E;
2421
2422 typedef bool result_type;
2423 static const AccessKinds AccessKind = AK_Assign;
2424
2425 bool checkConst(QualType QT) {
2426 // Assigning to a const object has undefined behavior.
2427 if (QT.isConstQualified()) {
2428 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2429 return false;
2430 }
2431 return true;
2432 }
2433
2434 bool failed() { return false; }
2435 bool found(APValue &Subobj, QualType SubobjType) {
2436 if (!checkConst(SubobjType))
2437 return false;
2438 // We've been given ownership of NewVal, so just swap it in.
2439 Subobj.swap(NewVal);
2440 return true;
2441 }
2442 bool found(APSInt &Value, QualType SubobjType) {
2443 if (!checkConst(SubobjType))
2444 return false;
2445 if (!NewVal.isInt()) {
2446 // Maybe trying to write a cast pointer value into a complex?
2447 Info.Diag(E);
2448 return false;
2449 }
2450 Value = NewVal.getInt();
2451 return true;
2452 }
2453 bool found(APFloat &Value, QualType SubobjType) {
2454 if (!checkConst(SubobjType))
2455 return false;
2456 Value = NewVal.getFloat();
2457 return true;
2458 }
2459 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2460 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2461 }
2462};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002463} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002464
Richard Smith3229b742013-05-05 21:17:10 +00002465const AccessKinds ModifySubobjectHandler::AccessKind;
2466
Richard Smith3da88fa2013-04-26 14:36:30 +00002467/// Update the designated sub-object of an rvalue to the given value.
2468static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002469 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002470 const SubobjectDesignator &Sub,
2471 APValue &NewVal) {
2472 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002473 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002474}
2475
Richard Smith84f6dcf2012-02-02 01:16:57 +00002476/// Find the position where two subobject designators diverge, or equivalently
2477/// the length of the common initial subsequence.
2478static unsigned FindDesignatorMismatch(QualType ObjType,
2479 const SubobjectDesignator &A,
2480 const SubobjectDesignator &B,
2481 bool &WasArrayIndex) {
2482 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2483 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002484 if (!ObjType.isNull() &&
2485 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002486 // Next subobject is an array element.
2487 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2488 WasArrayIndex = true;
2489 return I;
2490 }
Richard Smith66c96992012-02-18 22:04:06 +00002491 if (ObjType->isAnyComplexType())
2492 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2493 else
2494 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002495 } else {
2496 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2497 WasArrayIndex = false;
2498 return I;
2499 }
2500 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2501 // Next subobject is a field.
2502 ObjType = FD->getType();
2503 else
2504 // Next subobject is a base class.
2505 ObjType = QualType();
2506 }
2507 }
2508 WasArrayIndex = false;
2509 return I;
2510}
2511
2512/// Determine whether the given subobject designators refer to elements of the
2513/// same array object.
2514static bool AreElementsOfSameArray(QualType ObjType,
2515 const SubobjectDesignator &A,
2516 const SubobjectDesignator &B) {
2517 if (A.Entries.size() != B.Entries.size())
2518 return false;
2519
2520 bool IsArray = A.MostDerivedArraySize != 0;
2521 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2522 // A is a subobject of the array element.
2523 return false;
2524
2525 // If A (and B) designates an array element, the last entry will be the array
2526 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2527 // of length 1' case, and the entire path must match.
2528 bool WasArrayIndex;
2529 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2530 return CommonLength >= A.Entries.size() - IsArray;
2531}
2532
Richard Smith3229b742013-05-05 21:17:10 +00002533/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002534static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2535 AccessKinds AK, const LValue &LVal,
2536 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002537 if (!LVal.Base) {
2538 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2539 return CompleteObject();
2540 }
2541
Craig Topper36250ad2014-05-12 05:36:57 +00002542 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002543 if (LVal.CallIndex) {
2544 Frame = Info.getCallFrame(LVal.CallIndex);
2545 if (!Frame) {
2546 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2547 << AK << LVal.Base.is<const ValueDecl*>();
2548 NoteLValueLocation(Info, LVal.Base);
2549 return CompleteObject();
2550 }
Richard Smith3229b742013-05-05 21:17:10 +00002551 }
2552
2553 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2554 // is not a constant expression (even if the object is non-volatile). We also
2555 // apply this rule to C++98, in order to conform to the expected 'volatile'
2556 // semantics.
2557 if (LValType.isVolatileQualified()) {
2558 if (Info.getLangOpts().CPlusPlus)
2559 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2560 << AK << LValType;
2561 else
2562 Info.Diag(E);
2563 return CompleteObject();
2564 }
2565
2566 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002567 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002568 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002569
2570 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2571 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2572 // In C++11, constexpr, non-volatile variables initialized with constant
2573 // expressions are constant expressions too. Inside constexpr functions,
2574 // parameters are constant expressions even if they're non-const.
2575 // In C++1y, objects local to a constant expression (those with a Frame) are
2576 // both readable and writable inside constant expressions.
2577 // In C, such things can also be folded, although they are not ICEs.
2578 const VarDecl *VD = dyn_cast<VarDecl>(D);
2579 if (VD) {
2580 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2581 VD = VDef;
2582 }
2583 if (!VD || VD->isInvalidDecl()) {
2584 Info.Diag(E);
2585 return CompleteObject();
2586 }
2587
2588 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002589 if (BaseType.isVolatileQualified()) {
2590 if (Info.getLangOpts().CPlusPlus) {
2591 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2592 << AK << 1 << VD;
2593 Info.Note(VD->getLocation(), diag::note_declared_at);
2594 } else {
2595 Info.Diag(E);
2596 }
2597 return CompleteObject();
2598 }
2599
2600 // Unless we're looking at a local variable or argument in a constexpr call,
2601 // the variable we're reading must be const.
2602 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002603 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002604 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2605 // OK, we can read and modify an object if we're in the process of
2606 // evaluating its initializer, because its lifetime began in this
2607 // evaluation.
2608 } else if (AK != AK_Read) {
2609 // All the remaining cases only permit reading.
2610 Info.Diag(E, diag::note_constexpr_modify_global);
2611 return CompleteObject();
2612 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002613 // OK, we can read this variable.
2614 } else if (BaseType->isIntegralOrEnumerationType()) {
2615 if (!BaseType.isConstQualified()) {
2616 if (Info.getLangOpts().CPlusPlus) {
2617 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2618 Info.Note(VD->getLocation(), diag::note_declared_at);
2619 } else {
2620 Info.Diag(E);
2621 }
2622 return CompleteObject();
2623 }
2624 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2625 // We support folding of const floating-point types, in order to make
2626 // static const data members of such types (supported as an extension)
2627 // more useful.
2628 if (Info.getLangOpts().CPlusPlus11) {
2629 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2630 Info.Note(VD->getLocation(), diag::note_declared_at);
2631 } else {
2632 Info.CCEDiag(E);
2633 }
2634 } else {
2635 // FIXME: Allow folding of values of any literal type in all languages.
2636 if (Info.getLangOpts().CPlusPlus11) {
2637 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2638 Info.Note(VD->getLocation(), diag::note_declared_at);
2639 } else {
2640 Info.Diag(E);
2641 }
2642 return CompleteObject();
2643 }
2644 }
2645
2646 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2647 return CompleteObject();
2648 } else {
2649 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2650
2651 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002652 if (const MaterializeTemporaryExpr *MTE =
2653 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2654 assert(MTE->getStorageDuration() == SD_Static &&
2655 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002656
Richard Smithe6c01442013-06-05 00:46:14 +00002657 // Per C++1y [expr.const]p2:
2658 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2659 // - a [...] glvalue of integral or enumeration type that refers to
2660 // a non-volatile const object [...]
2661 // [...]
2662 // - a [...] glvalue of literal type that refers to a non-volatile
2663 // object whose lifetime began within the evaluation of e.
2664 //
2665 // C++11 misses the 'began within the evaluation of e' check and
2666 // instead allows all temporaries, including things like:
2667 // int &&r = 1;
2668 // int x = ++r;
2669 // constexpr int k = r;
2670 // Therefore we use the C++1y rules in C++11 too.
2671 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2672 const ValueDecl *ED = MTE->getExtendingDecl();
2673 if (!(BaseType.isConstQualified() &&
2674 BaseType->isIntegralOrEnumerationType()) &&
2675 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2676 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2677 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2678 return CompleteObject();
2679 }
2680
2681 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2682 assert(BaseVal && "got reference to unevaluated temporary");
2683 } else {
2684 Info.Diag(E);
2685 return CompleteObject();
2686 }
2687 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002688 BaseVal = Frame->getTemporary(Base);
2689 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002690 }
Richard Smith3229b742013-05-05 21:17:10 +00002691
2692 // Volatile temporary objects cannot be accessed in constant expressions.
2693 if (BaseType.isVolatileQualified()) {
2694 if (Info.getLangOpts().CPlusPlus) {
2695 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2696 << AK << 0;
2697 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2698 } else {
2699 Info.Diag(E);
2700 }
2701 return CompleteObject();
2702 }
2703 }
2704
Richard Smith7525ff62013-05-09 07:14:00 +00002705 // During the construction of an object, it is not yet 'const'.
2706 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2707 // and this doesn't do quite the right thing for const subobjects of the
2708 // object under construction.
2709 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2710 BaseType = Info.Ctx.getCanonicalType(BaseType);
2711 BaseType.removeLocalConst();
2712 }
2713
Richard Smith6d4c6582013-11-05 22:18:15 +00002714 // In C++1y, we can't safely access any mutable state when we might be
2715 // evaluating after an unmodeled side effect or an evaluation failure.
2716 //
2717 // FIXME: Not all local state is mutable. Allow local constant subobjects
2718 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002719 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002720 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002721 return CompleteObject();
2722
2723 return CompleteObject(BaseVal, BaseType);
2724}
2725
Richard Smith243ef902013-05-05 23:31:59 +00002726/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2727/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2728/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002729///
2730/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002731/// \param Conv - The expression for which we are performing the conversion.
2732/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002733/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2734/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002735/// \param LVal - The glvalue on which we are attempting to perform this action.
2736/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002737static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002738 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002739 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002740 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002741 return false;
2742
Richard Smith3229b742013-05-05 21:17:10 +00002743 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002744 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002745 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002746 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2747 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2748 // initializer until now for such expressions. Such an expression can't be
2749 // an ICE in C, so this only matters for fold.
2750 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2751 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002752 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002753 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002754 }
Richard Smith3229b742013-05-05 21:17:10 +00002755 APValue Lit;
2756 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2757 return false;
2758 CompleteObject LitObj(&Lit, Base->getType());
2759 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002760 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002761 // We represent a string literal array as an lvalue pointing at the
2762 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002763 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002764 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2765 CompleteObject StrObj(&Str, Base->getType());
2766 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002767 }
Richard Smith11562c52011-10-28 17:51:58 +00002768 }
2769
Richard Smith3229b742013-05-05 21:17:10 +00002770 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2771 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002772}
2773
2774/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002775static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002776 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002777 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002778 return false;
2779
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002780 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002781 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002782 return false;
2783 }
2784
Richard Smith3229b742013-05-05 21:17:10 +00002785 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2786 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002787}
2788
Richard Smith243ef902013-05-05 23:31:59 +00002789static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2790 return T->isSignedIntegerType() &&
2791 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2792}
2793
2794namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002795struct CompoundAssignSubobjectHandler {
2796 EvalInfo &Info;
2797 const Expr *E;
2798 QualType PromotedLHSType;
2799 BinaryOperatorKind Opcode;
2800 const APValue &RHS;
2801
2802 static const AccessKinds AccessKind = AK_Assign;
2803
2804 typedef bool result_type;
2805
2806 bool checkConst(QualType QT) {
2807 // Assigning to a const object has undefined behavior.
2808 if (QT.isConstQualified()) {
2809 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2810 return false;
2811 }
2812 return true;
2813 }
2814
2815 bool failed() { return false; }
2816 bool found(APValue &Subobj, QualType SubobjType) {
2817 switch (Subobj.getKind()) {
2818 case APValue::Int:
2819 return found(Subobj.getInt(), SubobjType);
2820 case APValue::Float:
2821 return found(Subobj.getFloat(), SubobjType);
2822 case APValue::ComplexInt:
2823 case APValue::ComplexFloat:
2824 // FIXME: Implement complex compound assignment.
2825 Info.Diag(E);
2826 return false;
2827 case APValue::LValue:
2828 return foundPointer(Subobj, SubobjType);
2829 default:
2830 // FIXME: can this happen?
2831 Info.Diag(E);
2832 return false;
2833 }
2834 }
2835 bool found(APSInt &Value, QualType SubobjType) {
2836 if (!checkConst(SubobjType))
2837 return false;
2838
2839 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2840 // We don't support compound assignment on integer-cast-to-pointer
2841 // values.
2842 Info.Diag(E);
2843 return false;
2844 }
2845
2846 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2847 SubobjType, Value);
2848 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2849 return false;
2850 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2851 return true;
2852 }
2853 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002854 return checkConst(SubobjType) &&
2855 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2856 Value) &&
2857 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2858 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002859 }
2860 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2861 if (!checkConst(SubobjType))
2862 return false;
2863
2864 QualType PointeeType;
2865 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2866 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002867
2868 if (PointeeType.isNull() || !RHS.isInt() ||
2869 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002870 Info.Diag(E);
2871 return false;
2872 }
2873
Richard Smith861b5b52013-05-07 23:34:45 +00002874 int64_t Offset = getExtValue(RHS.getInt());
2875 if (Opcode == BO_Sub)
2876 Offset = -Offset;
2877
2878 LValue LVal;
2879 LVal.setFrom(Info.Ctx, Subobj);
2880 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2881 return false;
2882 LVal.moveInto(Subobj);
2883 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002884 }
2885 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2886 llvm_unreachable("shouldn't encounter string elements here");
2887 }
2888};
2889} // end anonymous namespace
2890
2891const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2892
2893/// Perform a compound assignment of LVal <op>= RVal.
2894static bool handleCompoundAssignment(
2895 EvalInfo &Info, const Expr *E,
2896 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2897 BinaryOperatorKind Opcode, const APValue &RVal) {
2898 if (LVal.Designator.Invalid)
2899 return false;
2900
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002901 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002902 Info.Diag(E);
2903 return false;
2904 }
2905
2906 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2907 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2908 RVal };
2909 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2910}
2911
2912namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002913struct IncDecSubobjectHandler {
2914 EvalInfo &Info;
2915 const Expr *E;
2916 AccessKinds AccessKind;
2917 APValue *Old;
2918
2919 typedef bool result_type;
2920
2921 bool checkConst(QualType QT) {
2922 // Assigning to a const object has undefined behavior.
2923 if (QT.isConstQualified()) {
2924 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2925 return false;
2926 }
2927 return true;
2928 }
2929
2930 bool failed() { return false; }
2931 bool found(APValue &Subobj, QualType SubobjType) {
2932 // Stash the old value. Also clear Old, so we don't clobber it later
2933 // if we're post-incrementing a complex.
2934 if (Old) {
2935 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002936 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002937 }
2938
2939 switch (Subobj.getKind()) {
2940 case APValue::Int:
2941 return found(Subobj.getInt(), SubobjType);
2942 case APValue::Float:
2943 return found(Subobj.getFloat(), SubobjType);
2944 case APValue::ComplexInt:
2945 return found(Subobj.getComplexIntReal(),
2946 SubobjType->castAs<ComplexType>()->getElementType()
2947 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2948 case APValue::ComplexFloat:
2949 return found(Subobj.getComplexFloatReal(),
2950 SubobjType->castAs<ComplexType>()->getElementType()
2951 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2952 case APValue::LValue:
2953 return foundPointer(Subobj, SubobjType);
2954 default:
2955 // FIXME: can this happen?
2956 Info.Diag(E);
2957 return false;
2958 }
2959 }
2960 bool found(APSInt &Value, QualType SubobjType) {
2961 if (!checkConst(SubobjType))
2962 return false;
2963
2964 if (!SubobjType->isIntegerType()) {
2965 // We don't support increment / decrement on integer-cast-to-pointer
2966 // values.
2967 Info.Diag(E);
2968 return false;
2969 }
2970
2971 if (Old) *Old = APValue(Value);
2972
2973 // bool arithmetic promotes to int, and the conversion back to bool
2974 // doesn't reduce mod 2^n, so special-case it.
2975 if (SubobjType->isBooleanType()) {
2976 if (AccessKind == AK_Increment)
2977 Value = 1;
2978 else
2979 Value = !Value;
2980 return true;
2981 }
2982
2983 bool WasNegative = Value.isNegative();
2984 if (AccessKind == AK_Increment) {
2985 ++Value;
2986
2987 if (!WasNegative && Value.isNegative() &&
2988 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2989 APSInt ActualValue(Value, /*IsUnsigned*/true);
2990 HandleOverflow(Info, E, ActualValue, SubobjType);
2991 }
2992 } else {
2993 --Value;
2994
2995 if (WasNegative && !Value.isNegative() &&
2996 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2997 unsigned BitWidth = Value.getBitWidth();
2998 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2999 ActualValue.setBit(BitWidth);
3000 HandleOverflow(Info, E, ActualValue, SubobjType);
3001 }
3002 }
3003 return true;
3004 }
3005 bool found(APFloat &Value, QualType SubobjType) {
3006 if (!checkConst(SubobjType))
3007 return false;
3008
3009 if (Old) *Old = APValue(Value);
3010
3011 APFloat One(Value.getSemantics(), 1);
3012 if (AccessKind == AK_Increment)
3013 Value.add(One, APFloat::rmNearestTiesToEven);
3014 else
3015 Value.subtract(One, APFloat::rmNearestTiesToEven);
3016 return true;
3017 }
3018 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3019 if (!checkConst(SubobjType))
3020 return false;
3021
3022 QualType PointeeType;
3023 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3024 PointeeType = PT->getPointeeType();
3025 else {
3026 Info.Diag(E);
3027 return false;
3028 }
3029
3030 LValue LVal;
3031 LVal.setFrom(Info.Ctx, Subobj);
3032 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3033 AccessKind == AK_Increment ? 1 : -1))
3034 return false;
3035 LVal.moveInto(Subobj);
3036 return true;
3037 }
3038 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3039 llvm_unreachable("shouldn't encounter string elements here");
3040 }
3041};
3042} // end anonymous namespace
3043
3044/// Perform an increment or decrement on LVal.
3045static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3046 QualType LValType, bool IsIncrement, APValue *Old) {
3047 if (LVal.Designator.Invalid)
3048 return false;
3049
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003050 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003051 Info.Diag(E);
3052 return false;
3053 }
3054
3055 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3056 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3057 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3058 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3059}
3060
Richard Smithe97cbd72011-11-11 04:05:33 +00003061/// Build an lvalue for the object argument of a member function call.
3062static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3063 LValue &This) {
3064 if (Object->getType()->isPointerType())
3065 return EvaluatePointer(Object, This, Info);
3066
3067 if (Object->isGLValue())
3068 return EvaluateLValue(Object, This, Info);
3069
Richard Smithd9f663b2013-04-22 15:31:51 +00003070 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003071 return EvaluateTemporary(Object, This, Info);
3072
Richard Smith3e79a572014-06-11 19:53:12 +00003073 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003074 return false;
3075}
3076
3077/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3078/// lvalue referring to the result.
3079///
3080/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003081/// \param LV - An lvalue referring to the base of the member pointer.
3082/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003083/// \param IncludeMember - Specifies whether the member itself is included in
3084/// the resulting LValue subobject designator. This is not possible when
3085/// creating a bound member function.
3086/// \return The field or method declaration to which the member pointer refers,
3087/// or 0 if evaluation fails.
3088static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003089 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003090 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003091 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003092 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003093 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003094 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003095 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003096
3097 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3098 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003099 if (!MemPtr.getDecl()) {
3100 // FIXME: Specific diagnostic.
3101 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003102 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003103 }
Richard Smith253c2a32012-01-27 01:14:48 +00003104
Richard Smith027bf112011-11-17 22:56:20 +00003105 if (MemPtr.isDerivedMember()) {
3106 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003107 // The end of the derived-to-base path for the base object must match the
3108 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003109 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003110 LV.Designator.Entries.size()) {
3111 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003112 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003113 }
Richard Smith027bf112011-11-17 22:56:20 +00003114 unsigned PathLengthToMember =
3115 LV.Designator.Entries.size() - MemPtr.Path.size();
3116 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3117 const CXXRecordDecl *LVDecl = getAsBaseClass(
3118 LV.Designator.Entries[PathLengthToMember + I]);
3119 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003120 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3121 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003122 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003123 }
Richard Smith027bf112011-11-17 22:56:20 +00003124 }
3125
3126 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003127 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003128 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003129 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003130 } else if (!MemPtr.Path.empty()) {
3131 // Extend the LValue path with the member pointer's path.
3132 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3133 MemPtr.Path.size() + IncludeMember);
3134
3135 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003136 if (const PointerType *PT = LVType->getAs<PointerType>())
3137 LVType = PT->getPointeeType();
3138 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3139 assert(RD && "member pointer access on non-class-type expression");
3140 // The first class in the path is that of the lvalue.
3141 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3142 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003143 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003144 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003145 RD = Base;
3146 }
3147 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003148 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3149 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003150 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003151 }
3152
3153 // Add the member. Note that we cannot build bound member functions here.
3154 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003155 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003156 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003157 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003158 } else if (const IndirectFieldDecl *IFD =
3159 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003160 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003161 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003162 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003163 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003164 }
Richard Smith027bf112011-11-17 22:56:20 +00003165 }
3166
3167 return MemPtr.getDecl();
3168}
3169
Richard Smith84401042013-06-03 05:03:02 +00003170static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3171 const BinaryOperator *BO,
3172 LValue &LV,
3173 bool IncludeMember = true) {
3174 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3175
3176 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3177 if (Info.keepEvaluatingAfterFailure()) {
3178 MemberPtr MemPtr;
3179 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3180 }
Craig Topper36250ad2014-05-12 05:36:57 +00003181 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003182 }
3183
3184 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3185 BO->getRHS(), IncludeMember);
3186}
3187
Richard Smith027bf112011-11-17 22:56:20 +00003188/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3189/// the provided lvalue, which currently refers to the base object.
3190static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3191 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003192 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003193 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003194 return false;
3195
Richard Smitha8105bc2012-01-06 16:39:00 +00003196 QualType TargetQT = E->getType();
3197 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3198 TargetQT = PT->getPointeeType();
3199
3200 // Check this cast lands within the final derived-to-base subobject path.
3201 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003202 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003203 << D.MostDerivedType << TargetQT;
3204 return false;
3205 }
3206
Richard Smith027bf112011-11-17 22:56:20 +00003207 // Check the type of the final cast. We don't need to check the path,
3208 // since a cast can only be formed if the path is unique.
3209 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003210 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3211 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003212 if (NewEntriesSize == D.MostDerivedPathLength)
3213 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3214 else
Richard Smith027bf112011-11-17 22:56:20 +00003215 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003216 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003217 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003218 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003219 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003220 }
Richard Smith027bf112011-11-17 22:56:20 +00003221
3222 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003223 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003224}
3225
Mike Stump876387b2009-10-27 22:09:17 +00003226namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003227enum EvalStmtResult {
3228 /// Evaluation failed.
3229 ESR_Failed,
3230 /// Hit a 'return' statement.
3231 ESR_Returned,
3232 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003233 ESR_Succeeded,
3234 /// Hit a 'continue' statement.
3235 ESR_Continue,
3236 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003237 ESR_Break,
3238 /// Still scanning for 'case' or 'default' statement.
3239 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003240};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003241}
Richard Smith254a73d2011-10-28 22:34:42 +00003242
Richard Smithd9f663b2013-04-22 15:31:51 +00003243static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3244 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3245 // We don't need to evaluate the initializer for a static local.
3246 if (!VD->hasLocalStorage())
3247 return true;
3248
3249 LValue Result;
3250 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003251 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003252
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003253 const Expr *InitE = VD->getInit();
3254 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003255 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3256 << false << VD->getType();
3257 Val = APValue();
3258 return false;
3259 }
3260
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003261 if (InitE->isValueDependent())
3262 return false;
3263
3264 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003265 // Wipe out any partially-computed value, to allow tracking that this
3266 // evaluation failed.
3267 Val = APValue();
3268 return false;
3269 }
3270 }
3271
3272 return true;
3273}
3274
Richard Smith4e18ca52013-05-06 05:56:11 +00003275/// Evaluate a condition (either a variable declaration or an expression).
3276static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3277 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003278 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003279 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3280 return false;
3281 return EvaluateAsBooleanCondition(Cond, Result, Info);
3282}
3283
Richard Smith52a980a2015-08-28 02:43:42 +00003284/// \brief A location where the result (returned value) of evaluating a
3285/// statement should be stored.
3286struct StmtResult {
3287 /// The APValue that should be filled in with the returned value.
3288 APValue &Value;
3289 /// The location containing the result, if any (used to support RVO).
3290 const LValue *Slot;
3291};
3292
3293static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003294 const Stmt *S,
3295 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003296
3297/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003298static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003299 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003300 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003301 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003302 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003303 case ESR_Break:
3304 return ESR_Succeeded;
3305 case ESR_Succeeded:
3306 case ESR_Continue:
3307 return ESR_Continue;
3308 case ESR_Failed:
3309 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003310 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003311 return ESR;
3312 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003313 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003314}
3315
Richard Smith496ddcf2013-05-12 17:32:42 +00003316/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003317static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003318 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003319 BlockScopeRAII Scope(Info);
3320
Richard Smith496ddcf2013-05-12 17:32:42 +00003321 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003322 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003323 {
3324 FullExpressionRAII Scope(Info);
3325 if (SS->getConditionVariable() &&
3326 !EvaluateDecl(Info, SS->getConditionVariable()))
3327 return ESR_Failed;
3328 if (!EvaluateInteger(SS->getCond(), Value, Info))
3329 return ESR_Failed;
3330 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003331
3332 // Find the switch case corresponding to the value of the condition.
3333 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003334 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003335 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3336 SC = SC->getNextSwitchCase()) {
3337 if (isa<DefaultStmt>(SC)) {
3338 Found = SC;
3339 continue;
3340 }
3341
3342 const CaseStmt *CS = cast<CaseStmt>(SC);
3343 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3344 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3345 : LHS;
3346 if (LHS <= Value && Value <= RHS) {
3347 Found = SC;
3348 break;
3349 }
3350 }
3351
3352 if (!Found)
3353 return ESR_Succeeded;
3354
3355 // Search the switch body for the switch case and evaluate it from there.
3356 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3357 case ESR_Break:
3358 return ESR_Succeeded;
3359 case ESR_Succeeded:
3360 case ESR_Continue:
3361 case ESR_Failed:
3362 case ESR_Returned:
3363 return ESR;
3364 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003365 // This can only happen if the switch case is nested within a statement
3366 // expression. We have no intention of supporting that.
3367 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3368 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003369 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003370 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003371}
3372
Richard Smith254a73d2011-10-28 22:34:42 +00003373// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003374static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003375 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003376 if (!Info.nextStep(S))
3377 return ESR_Failed;
3378
Richard Smith496ddcf2013-05-12 17:32:42 +00003379 // If we're hunting down a 'case' or 'default' label, recurse through
3380 // substatements until we hit the label.
3381 if (Case) {
3382 // FIXME: We don't start the lifetime of objects whose initialization we
3383 // jump over. However, such objects must be of class type with a trivial
3384 // default constructor that initialize all subobjects, so must be empty,
3385 // so this almost never matters.
3386 switch (S->getStmtClass()) {
3387 case Stmt::CompoundStmtClass:
3388 // FIXME: Precompute which substatement of a compound statement we
3389 // would jump to, and go straight there rather than performing a
3390 // linear scan each time.
3391 case Stmt::LabelStmtClass:
3392 case Stmt::AttributedStmtClass:
3393 case Stmt::DoStmtClass:
3394 break;
3395
3396 case Stmt::CaseStmtClass:
3397 case Stmt::DefaultStmtClass:
3398 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003399 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003400 break;
3401
3402 case Stmt::IfStmtClass: {
3403 // FIXME: Precompute which side of an 'if' we would jump to, and go
3404 // straight there rather than scanning both sides.
3405 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003406
3407 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3408 // preceded by our switch label.
3409 BlockScopeRAII Scope(Info);
3410
Richard Smith496ddcf2013-05-12 17:32:42 +00003411 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3412 if (ESR != ESR_CaseNotFound || !IS->getElse())
3413 return ESR;
3414 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3415 }
3416
3417 case Stmt::WhileStmtClass: {
3418 EvalStmtResult ESR =
3419 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3420 if (ESR != ESR_Continue)
3421 return ESR;
3422 break;
3423 }
3424
3425 case Stmt::ForStmtClass: {
3426 const ForStmt *FS = cast<ForStmt>(S);
3427 EvalStmtResult ESR =
3428 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3429 if (ESR != ESR_Continue)
3430 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003431 if (FS->getInc()) {
3432 FullExpressionRAII IncScope(Info);
3433 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3434 return ESR_Failed;
3435 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003436 break;
3437 }
3438
3439 case Stmt::DeclStmtClass:
3440 // FIXME: If the variable has initialization that can't be jumped over,
3441 // bail out of any immediately-surrounding compound-statement too.
3442 default:
3443 return ESR_CaseNotFound;
3444 }
3445 }
3446
Richard Smith254a73d2011-10-28 22:34:42 +00003447 switch (S->getStmtClass()) {
3448 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003449 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003450 // Don't bother evaluating beyond an expression-statement which couldn't
3451 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003452 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003453 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003454 return ESR_Failed;
3455 return ESR_Succeeded;
3456 }
3457
3458 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003459 return ESR_Failed;
3460
3461 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003462 return ESR_Succeeded;
3463
Richard Smithd9f663b2013-04-22 15:31:51 +00003464 case Stmt::DeclStmtClass: {
3465 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003466 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003467 // Each declaration initialization is its own full-expression.
3468 // FIXME: This isn't quite right; if we're performing aggregate
3469 // initialization, each braced subexpression is its own full-expression.
3470 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003471 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003472 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003473 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003474 return ESR_Succeeded;
3475 }
3476
Richard Smith357362d2011-12-13 06:39:58 +00003477 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003478 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003479 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003480 if (RetExpr &&
3481 !(Result.Slot
3482 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3483 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003484 return ESR_Failed;
3485 return ESR_Returned;
3486 }
Richard Smith254a73d2011-10-28 22:34:42 +00003487
3488 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003489 BlockScopeRAII Scope(Info);
3490
Richard Smith254a73d2011-10-28 22:34:42 +00003491 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003492 for (const auto *BI : CS->body()) {
3493 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003494 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003495 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003496 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003497 return ESR;
3498 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003499 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003500 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003501
3502 case Stmt::IfStmtClass: {
3503 const IfStmt *IS = cast<IfStmt>(S);
3504
3505 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003506 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003507 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003508 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003509 return ESR_Failed;
3510
3511 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3512 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3513 if (ESR != ESR_Succeeded)
3514 return ESR;
3515 }
3516 return ESR_Succeeded;
3517 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003518
3519 case Stmt::WhileStmtClass: {
3520 const WhileStmt *WS = cast<WhileStmt>(S);
3521 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003522 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003523 bool Continue;
3524 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3525 Continue))
3526 return ESR_Failed;
3527 if (!Continue)
3528 break;
3529
3530 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3531 if (ESR != ESR_Continue)
3532 return ESR;
3533 }
3534 return ESR_Succeeded;
3535 }
3536
3537 case Stmt::DoStmtClass: {
3538 const DoStmt *DS = cast<DoStmt>(S);
3539 bool Continue;
3540 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003541 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003542 if (ESR != ESR_Continue)
3543 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003544 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003545
Richard Smith08d6a2c2013-07-24 07:11:57 +00003546 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003547 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3548 return ESR_Failed;
3549 } while (Continue);
3550 return ESR_Succeeded;
3551 }
3552
3553 case Stmt::ForStmtClass: {
3554 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003555 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003556 if (FS->getInit()) {
3557 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3558 if (ESR != ESR_Succeeded)
3559 return ESR;
3560 }
3561 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003562 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003563 bool Continue = true;
3564 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3565 FS->getCond(), Continue))
3566 return ESR_Failed;
3567 if (!Continue)
3568 break;
3569
3570 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3571 if (ESR != ESR_Continue)
3572 return ESR;
3573
Richard Smith08d6a2c2013-07-24 07:11:57 +00003574 if (FS->getInc()) {
3575 FullExpressionRAII IncScope(Info);
3576 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3577 return ESR_Failed;
3578 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003579 }
3580 return ESR_Succeeded;
3581 }
3582
Richard Smith896e0d72013-05-06 06:51:17 +00003583 case Stmt::CXXForRangeStmtClass: {
3584 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003585 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003586
3587 // Initialize the __range variable.
3588 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3589 if (ESR != ESR_Succeeded)
3590 return ESR;
3591
3592 // Create the __begin and __end iterators.
3593 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3594 if (ESR != ESR_Succeeded)
3595 return ESR;
3596
3597 while (true) {
3598 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003599 {
3600 bool Continue = true;
3601 FullExpressionRAII CondExpr(Info);
3602 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3603 return ESR_Failed;
3604 if (!Continue)
3605 break;
3606 }
Richard Smith896e0d72013-05-06 06:51:17 +00003607
3608 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003609 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003610 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3611 if (ESR != ESR_Succeeded)
3612 return ESR;
3613
3614 // Loop body.
3615 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3616 if (ESR != ESR_Continue)
3617 return ESR;
3618
3619 // Increment: ++__begin
3620 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3621 return ESR_Failed;
3622 }
3623
3624 return ESR_Succeeded;
3625 }
3626
Richard Smith496ddcf2013-05-12 17:32:42 +00003627 case Stmt::SwitchStmtClass:
3628 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3629
Richard Smith4e18ca52013-05-06 05:56:11 +00003630 case Stmt::ContinueStmtClass:
3631 return ESR_Continue;
3632
3633 case Stmt::BreakStmtClass:
3634 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003635
3636 case Stmt::LabelStmtClass:
3637 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3638
3639 case Stmt::AttributedStmtClass:
3640 // As a general principle, C++11 attributes can be ignored without
3641 // any semantic impact.
3642 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3643 Case);
3644
3645 case Stmt::CaseStmtClass:
3646 case Stmt::DefaultStmtClass:
3647 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003648 }
3649}
3650
Richard Smithcc36f692011-12-22 02:22:31 +00003651/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3652/// default constructor. If so, we'll fold it whether or not it's marked as
3653/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3654/// so we need special handling.
3655static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003656 const CXXConstructorDecl *CD,
3657 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003658 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3659 return false;
3660
Richard Smith66e05fe2012-01-18 05:21:49 +00003661 // Value-initialization does not call a trivial default constructor, so such a
3662 // call is a core constant expression whether or not the constructor is
3663 // constexpr.
3664 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003665 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003666 // FIXME: If DiagDecl is an implicitly-declared special member function,
3667 // we should be much more explicit about why it's not constexpr.
3668 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3669 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3670 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003671 } else {
3672 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3673 }
3674 }
3675 return true;
3676}
3677
Richard Smith357362d2011-12-13 06:39:58 +00003678/// CheckConstexprFunction - Check that a function can be called in a constant
3679/// expression.
3680static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3681 const FunctionDecl *Declaration,
3682 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003683 // Potential constant expressions can contain calls to declared, but not yet
3684 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003685 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003686 Declaration->isConstexpr())
3687 return false;
3688
Richard Smith0838f3a2013-05-14 05:18:44 +00003689 // Bail out with no diagnostic if the function declaration itself is invalid.
3690 // We will have produced a relevant diagnostic while parsing it.
3691 if (Declaration->isInvalidDecl())
3692 return false;
3693
Richard Smith357362d2011-12-13 06:39:58 +00003694 // Can we evaluate this function call?
3695 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3696 return true;
3697
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003698 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003699 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003700 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3701 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003702 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3703 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3704 << DiagDecl;
3705 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3706 } else {
3707 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3708 }
3709 return false;
3710}
3711
Richard Smithbe6dd812014-11-19 21:27:17 +00003712/// Determine if a class has any fields that might need to be copied by a
3713/// trivial copy or move operation.
3714static bool hasFields(const CXXRecordDecl *RD) {
3715 if (!RD || RD->isEmpty())
3716 return false;
3717 for (auto *FD : RD->fields()) {
3718 if (FD->isUnnamedBitfield())
3719 continue;
3720 return true;
3721 }
3722 for (auto &Base : RD->bases())
3723 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3724 return true;
3725 return false;
3726}
3727
Richard Smithd62306a2011-11-10 06:34:14 +00003728namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003729typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003730}
3731
3732/// EvaluateArgs - Evaluate the arguments to a function call.
3733static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3734 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003735 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003736 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003737 I != E; ++I) {
3738 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3739 // If we're checking for a potential constant expression, evaluate all
3740 // initializers even if some of them fail.
3741 if (!Info.keepEvaluatingAfterFailure())
3742 return false;
3743 Success = false;
3744 }
3745 }
3746 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003747}
3748
Richard Smith254a73d2011-10-28 22:34:42 +00003749/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003750static bool HandleFunctionCall(SourceLocation CallLoc,
3751 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003752 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003753 EvalInfo &Info, APValue &Result,
3754 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003755 ArgVector ArgValues(Args.size());
3756 if (!EvaluateArgs(Args, ArgValues, Info))
3757 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003758
Richard Smith253c2a32012-01-27 01:14:48 +00003759 if (!Info.CheckCallLimit(CallLoc))
3760 return false;
3761
3762 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003763
3764 // For a trivial copy or move assignment, perform an APValue copy. This is
3765 // essential for unions, where the operations performed by the assignment
3766 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003767 //
3768 // Skip this for non-union classes with no fields; in that case, the defaulted
3769 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003770 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003771 if (MD && MD->isDefaulted() &&
3772 (MD->getParent()->isUnion() ||
3773 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003774 assert(This &&
3775 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3776 LValue RHS;
3777 RHS.setFrom(Info.Ctx, ArgValues[0]);
3778 APValue RHSValue;
3779 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3780 RHS, RHSValue))
3781 return false;
3782 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3783 RHSValue))
3784 return false;
3785 This->moveInto(Result);
3786 return true;
3787 }
3788
Richard Smith52a980a2015-08-28 02:43:42 +00003789 StmtResult Ret = {Result, ResultSlot};
3790 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003791 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003792 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003793 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003794 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003795 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003796 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003797}
3798
Richard Smithd62306a2011-11-10 06:34:14 +00003799/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003800static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003801 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003802 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003803 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003804 ArgVector ArgValues(Args.size());
3805 if (!EvaluateArgs(Args, ArgValues, Info))
3806 return false;
3807
Richard Smith253c2a32012-01-27 01:14:48 +00003808 if (!Info.CheckCallLimit(CallLoc))
3809 return false;
3810
Richard Smith3607ffe2012-02-13 03:54:03 +00003811 const CXXRecordDecl *RD = Definition->getParent();
3812 if (RD->getNumVBases()) {
3813 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3814 return false;
3815 }
3816
Richard Smith253c2a32012-01-27 01:14:48 +00003817 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003818
Richard Smith52a980a2015-08-28 02:43:42 +00003819 // FIXME: Creating an APValue just to hold a nonexistent return value is
3820 // wasteful.
3821 APValue RetVal;
3822 StmtResult Ret = {RetVal, nullptr};
3823
Richard Smithd62306a2011-11-10 06:34:14 +00003824 // If it's a delegating constructor, just delegate.
3825 if (Definition->isDelegatingConstructor()) {
3826 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003827 {
3828 FullExpressionRAII InitScope(Info);
3829 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3830 return false;
3831 }
Richard Smith52a980a2015-08-28 02:43:42 +00003832 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003833 }
3834
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003835 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003836 // essential for unions (or classes with anonymous union members), where the
3837 // operations performed by the constructor cannot be represented by
3838 // ctor-initializers.
3839 //
3840 // Skip this for empty non-union classes; we should not perform an
3841 // lvalue-to-rvalue conversion on them because their copy constructor does not
3842 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003843 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003844 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003845 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003846 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003847 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003848 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003849 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003850 }
3851
3852 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003853 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003854 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003855 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003856
John McCalld7bca762012-05-01 00:38:49 +00003857 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003858 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3859
Richard Smith08d6a2c2013-07-24 07:11:57 +00003860 // A scope for temporaries lifetime-extended by reference members.
3861 BlockScopeRAII LifetimeExtendedScope(Info);
3862
Richard Smith253c2a32012-01-27 01:14:48 +00003863 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003864 unsigned BasesSeen = 0;
3865#ifndef NDEBUG
3866 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3867#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003868 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003869 LValue Subobject = This;
3870 APValue *Value = &Result;
3871
3872 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003873 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003874 if (I->isBaseInitializer()) {
3875 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003876#ifndef NDEBUG
3877 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003878 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003879 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3880 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3881 "base class initializers not in expected order");
3882 ++BaseIt;
3883#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003884 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003885 BaseType->getAsCXXRecordDecl(), &Layout))
3886 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003887 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003888 } else if ((FD = I->getMember())) {
3889 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003890 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003891 if (RD->isUnion()) {
3892 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003893 Value = &Result.getUnionValue();
3894 } else {
3895 Value = &Result.getStructField(FD->getFieldIndex());
3896 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003897 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003898 // Walk the indirect field decl's chain to find the object to initialize,
3899 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003900 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003901 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003902 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3903 // Switch the union field if it differs. This happens if we had
3904 // preceding zero-initialization, and we're now initializing a union
3905 // subobject other than the first.
3906 // FIXME: In this case, the values of the other subobjects are
3907 // specified, since zero-initialization sets all padding bits to zero.
3908 if (Value->isUninit() ||
3909 (Value->isUnion() && Value->getUnionField() != FD)) {
3910 if (CD->isUnion())
3911 *Value = APValue(FD);
3912 else
3913 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003914 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003915 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003916 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003917 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003918 if (CD->isUnion())
3919 Value = &Value->getUnionValue();
3920 else
3921 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003922 }
Richard Smithd62306a2011-11-10 06:34:14 +00003923 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003924 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003925 }
Richard Smith253c2a32012-01-27 01:14:48 +00003926
Richard Smith08d6a2c2013-07-24 07:11:57 +00003927 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003928 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3929 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003930 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003931 // If we're checking for a potential constant expression, evaluate all
3932 // initializers even if some of them fail.
3933 if (!Info.keepEvaluatingAfterFailure())
3934 return false;
3935 Success = false;
3936 }
Richard Smithd62306a2011-11-10 06:34:14 +00003937 }
3938
Richard Smithd9f663b2013-04-22 15:31:51 +00003939 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00003940 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003941}
3942
Eli Friedman9a156e52008-11-12 09:44:48 +00003943//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003944// Generic Evaluation
3945//===----------------------------------------------------------------------===//
3946namespace {
3947
Aaron Ballman68af21c2014-01-03 19:26:43 +00003948template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003949class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003950 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003951private:
Richard Smith52a980a2015-08-28 02:43:42 +00003952 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003953 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003954 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003955 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003956 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003957 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003958 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003959
Richard Smith17100ba2012-02-16 02:46:34 +00003960 // Check whether a conditional operator with a non-constant condition is a
3961 // potential constant expression. If neither arm is a potential constant
3962 // expression, then the conditional operator is not either.
3963 template<typename ConditionalOperator>
3964 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003965 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003966
3967 // Speculatively evaluate both arms.
3968 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003969 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003970 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3971
3972 StmtVisitorTy::Visit(E->getFalseExpr());
3973 if (Diag.empty())
3974 return;
3975
3976 Diag.clear();
3977 StmtVisitorTy::Visit(E->getTrueExpr());
3978 if (Diag.empty())
3979 return;
3980 }
3981
3982 Error(E, diag::note_constexpr_conditional_never_const);
3983 }
3984
3985
3986 template<typename ConditionalOperator>
3987 bool HandleConditionalOperator(const ConditionalOperator *E) {
3988 bool BoolResult;
3989 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003990 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003991 CheckPotentialConstantConditional(E);
3992 return false;
3993 }
3994
3995 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3996 return StmtVisitorTy::Visit(EvalExpr);
3997 }
3998
Peter Collingbournee9200682011-05-13 03:29:01 +00003999protected:
4000 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004001 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004002 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4003
Richard Smith92b1ce02011-12-12 09:28:41 +00004004 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004005 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004006 }
4007
Aaron Ballman68af21c2014-01-03 19:26:43 +00004008 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004009
4010public:
4011 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4012
4013 EvalInfo &getEvalInfo() { return Info; }
4014
Richard Smithf57d8cb2011-12-09 22:58:01 +00004015 /// Report an evaluation error. This should only be called when an error is
4016 /// first discovered. When propagating an error, just return false.
4017 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004018 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004019 return false;
4020 }
4021 bool Error(const Expr *E) {
4022 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4023 }
4024
Aaron Ballman68af21c2014-01-03 19:26:43 +00004025 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004026 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004027 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004028 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004029 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004030 }
4031
Aaron Ballman68af21c2014-01-03 19:26:43 +00004032 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004033 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004034 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004035 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004036 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004037 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004038 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004039 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004040 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004041 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004042 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004043 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004044 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004045 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004046 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004047 // The initializer may not have been parsed yet, or might be erroneous.
4048 if (!E->getExpr())
4049 return Error(E);
4050 return StmtVisitorTy::Visit(E->getExpr());
4051 }
Richard Smith5894a912011-12-19 22:12:41 +00004052 // We cannot create any objects for which cleanups are required, so there is
4053 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004054 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004055 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004056
Aaron Ballman68af21c2014-01-03 19:26:43 +00004057 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004058 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4059 return static_cast<Derived*>(this)->VisitCastExpr(E);
4060 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004061 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004062 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4063 return static_cast<Derived*>(this)->VisitCastExpr(E);
4064 }
4065
Aaron Ballman68af21c2014-01-03 19:26:43 +00004066 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004067 switch (E->getOpcode()) {
4068 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004069 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004070
4071 case BO_Comma:
4072 VisitIgnoredValue(E->getLHS());
4073 return StmtVisitorTy::Visit(E->getRHS());
4074
4075 case BO_PtrMemD:
4076 case BO_PtrMemI: {
4077 LValue Obj;
4078 if (!HandleMemberPointerAccess(Info, E, Obj))
4079 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004080 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004081 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004082 return false;
4083 return DerivedSuccess(Result, E);
4084 }
4085 }
4086 }
4087
Aaron Ballman68af21c2014-01-03 19:26:43 +00004088 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004089 // Evaluate and cache the common expression. We treat it as a temporary,
4090 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004091 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004092 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004093 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004094
Richard Smith17100ba2012-02-16 02:46:34 +00004095 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004096 }
4097
Aaron Ballman68af21c2014-01-03 19:26:43 +00004098 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004099 bool IsBcpCall = false;
4100 // If the condition (ignoring parens) is a __builtin_constant_p call,
4101 // the result is a constant expression if it can be folded without
4102 // side-effects. This is an important GNU extension. See GCC PR38377
4103 // for discussion.
4104 if (const CallExpr *CallCE =
4105 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004106 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004107 IsBcpCall = true;
4108
4109 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4110 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004111 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004112 return false;
4113
Richard Smith6d4c6582013-11-05 22:18:15 +00004114 FoldConstant Fold(Info, IsBcpCall);
4115 if (!HandleConditionalOperator(E)) {
4116 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004117 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004118 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004119
4120 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004121 }
4122
Aaron Ballman68af21c2014-01-03 19:26:43 +00004123 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004124 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4125 return DerivedSuccess(*Value, E);
4126
4127 const Expr *Source = E->getSourceExpr();
4128 if (!Source)
4129 return Error(E);
4130 if (Source == E) { // sanity checking.
4131 assert(0 && "OpaqueValueExpr recursively refers to itself");
4132 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004133 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004134 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004135 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004136
Aaron Ballman68af21c2014-01-03 19:26:43 +00004137 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004138 APValue Result;
4139 if (!handleCallExpr(E, Result, nullptr))
4140 return false;
4141 return DerivedSuccess(Result, E);
4142 }
4143
4144 bool handleCallExpr(const CallExpr *E, APValue &Result,
4145 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004146 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004147 QualType CalleeType = Callee->getType();
4148
Craig Topper36250ad2014-05-12 05:36:57 +00004149 const FunctionDecl *FD = nullptr;
4150 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004151 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004152 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004153
Richard Smithe97cbd72011-11-11 04:05:33 +00004154 // Extract function decl and 'this' pointer from the callee.
4155 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004156 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004157 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4158 // Explicit bound member calls, such as x.f() or p->g();
4159 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004160 return false;
4161 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004162 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004163 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004164 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4165 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004166 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4167 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004168 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004169 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004170 return Error(Callee);
4171
4172 FD = dyn_cast<FunctionDecl>(Member);
4173 if (!FD)
4174 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004175 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004176 LValue Call;
4177 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004178 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004179
Richard Smitha8105bc2012-01-06 16:39:00 +00004180 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004181 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004182 FD = dyn_cast_or_null<FunctionDecl>(
4183 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004184 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004185 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004186
4187 // Overloaded operator calls to member functions are represented as normal
4188 // calls with '*this' as the first argument.
4189 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4190 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004191 // FIXME: When selecting an implicit conversion for an overloaded
4192 // operator delete, we sometimes try to evaluate calls to conversion
4193 // operators without a 'this' parameter!
4194 if (Args.empty())
4195 return Error(E);
4196
Richard Smithe97cbd72011-11-11 04:05:33 +00004197 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4198 return false;
4199 This = &ThisVal;
4200 Args = Args.slice(1);
4201 }
4202
4203 // Don't call function pointers which have been cast to some other type.
4204 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004205 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004206 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004207 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004208
Richard Smith47b34932012-02-01 02:39:43 +00004209 if (This && !This->checkSubobject(Info, E, CSK_This))
4210 return false;
4211
Richard Smith3607ffe2012-02-13 03:54:03 +00004212 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4213 // calls to such functions in constant expressions.
4214 if (This && !HasQualifier &&
4215 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4216 return Error(E, diag::note_constexpr_virtual_call);
4217
Craig Topper36250ad2014-05-12 05:36:57 +00004218 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004219 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004220
Richard Smith357362d2011-12-13 06:39:58 +00004221 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004222 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4223 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004224 return false;
4225
Richard Smith52a980a2015-08-28 02:43:42 +00004226 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004227 }
4228
Aaron Ballman68af21c2014-01-03 19:26:43 +00004229 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004230 return StmtVisitorTy::Visit(E->getInitializer());
4231 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004232 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004233 if (E->getNumInits() == 0)
4234 return DerivedZeroInitialization(E);
4235 if (E->getNumInits() == 1)
4236 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004237 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004238 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004239 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004240 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004241 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004242 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004243 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004244 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004245 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004246 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004247 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004248
Richard Smithd62306a2011-11-10 06:34:14 +00004249 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004250 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004251 assert(!E->isArrow() && "missing call to bound member function?");
4252
Richard Smith2e312c82012-03-03 22:46:17 +00004253 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004254 if (!Evaluate(Val, Info, E->getBase()))
4255 return false;
4256
4257 QualType BaseTy = E->getBase()->getType();
4258
4259 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004260 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004261 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004262 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004263 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4264
Richard Smith3229b742013-05-05 21:17:10 +00004265 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004266 SubobjectDesignator Designator(BaseTy);
4267 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004268
Richard Smith3229b742013-05-05 21:17:10 +00004269 APValue Result;
4270 return extractSubobject(Info, E, Obj, Designator, Result) &&
4271 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004272 }
4273
Aaron Ballman68af21c2014-01-03 19:26:43 +00004274 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004275 switch (E->getCastKind()) {
4276 default:
4277 break;
4278
Richard Smitha23ab512013-05-23 00:30:41 +00004279 case CK_AtomicToNonAtomic: {
4280 APValue AtomicVal;
4281 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4282 return false;
4283 return DerivedSuccess(AtomicVal, E);
4284 }
4285
Richard Smith11562c52011-10-28 17:51:58 +00004286 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004287 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004288 return StmtVisitorTy::Visit(E->getSubExpr());
4289
4290 case CK_LValueToRValue: {
4291 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004292 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4293 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004294 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004295 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004296 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004297 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004298 return false;
4299 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004300 }
4301 }
4302
Richard Smithf57d8cb2011-12-09 22:58:01 +00004303 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004304 }
4305
Aaron Ballman68af21c2014-01-03 19:26:43 +00004306 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004307 return VisitUnaryPostIncDec(UO);
4308 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004309 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004310 return VisitUnaryPostIncDec(UO);
4311 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004312 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004313 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004314 return Error(UO);
4315
4316 LValue LVal;
4317 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4318 return false;
4319 APValue RVal;
4320 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4321 UO->isIncrementOp(), &RVal))
4322 return false;
4323 return DerivedSuccess(RVal, UO);
4324 }
4325
Aaron Ballman68af21c2014-01-03 19:26:43 +00004326 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004327 // We will have checked the full-expressions inside the statement expression
4328 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004329 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004330 return Error(E);
4331
Richard Smith08d6a2c2013-07-24 07:11:57 +00004332 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004333 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004334 if (CS->body_empty())
4335 return true;
4336
Richard Smith51f03172013-06-20 03:00:05 +00004337 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4338 BE = CS->body_end();
4339 /**/; ++BI) {
4340 if (BI + 1 == BE) {
4341 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4342 if (!FinalExpr) {
4343 Info.Diag((*BI)->getLocStart(),
4344 diag::note_constexpr_stmt_expr_unsupported);
4345 return false;
4346 }
4347 return this->Visit(FinalExpr);
4348 }
4349
4350 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004351 StmtResult Result = { ReturnValue, nullptr };
4352 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004353 if (ESR != ESR_Succeeded) {
4354 // FIXME: If the statement-expression terminated due to 'return',
4355 // 'break', or 'continue', it would be nice to propagate that to
4356 // the outer statement evaluation rather than bailing out.
4357 if (ESR != ESR_Failed)
4358 Info.Diag((*BI)->getLocStart(),
4359 diag::note_constexpr_stmt_expr_unsupported);
4360 return false;
4361 }
4362 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004363
4364 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004365 }
4366
Richard Smith4a678122011-10-24 18:44:57 +00004367 /// Visit a value which is evaluated, but whose value is ignored.
4368 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004369 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004370 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004371};
4372
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004373}
Peter Collingbournee9200682011-05-13 03:29:01 +00004374
4375//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004376// Common base class for lvalue and temporary evaluation.
4377//===----------------------------------------------------------------------===//
4378namespace {
4379template<class Derived>
4380class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004381 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004382protected:
4383 LValue &Result;
4384 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004385 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004386
4387 bool Success(APValue::LValueBase B) {
4388 Result.set(B);
4389 return true;
4390 }
4391
4392public:
4393 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4394 ExprEvaluatorBaseTy(Info), Result(Result) {}
4395
Richard Smith2e312c82012-03-03 22:46:17 +00004396 bool Success(const APValue &V, const Expr *E) {
4397 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004398 return true;
4399 }
Richard Smith027bf112011-11-17 22:56:20 +00004400
Richard Smith027bf112011-11-17 22:56:20 +00004401 bool VisitMemberExpr(const MemberExpr *E) {
4402 // Handle non-static data members.
4403 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004404 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004405 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004406 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004407 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004408 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004409 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004410 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004411 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004412 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004413 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004414 BaseTy = E->getBase()->getType();
4415 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004416 if (!EvalOK) {
4417 if (!this->Info.allowInvalidBaseExpr())
4418 return false;
4419 Result.setInvalid(E->getBase());
4420 }
Richard Smith027bf112011-11-17 22:56:20 +00004421
Richard Smith1b78b3d2012-01-25 22:15:11 +00004422 const ValueDecl *MD = E->getMemberDecl();
4423 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4424 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4425 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4426 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004427 if (!HandleLValueMember(this->Info, E, Result, FD))
4428 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004429 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004430 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4431 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004432 } else
4433 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004434
Richard Smith1b78b3d2012-01-25 22:15:11 +00004435 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004436 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004437 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004438 RefValue))
4439 return false;
4440 return Success(RefValue, E);
4441 }
4442 return true;
4443 }
4444
4445 bool VisitBinaryOperator(const BinaryOperator *E) {
4446 switch (E->getOpcode()) {
4447 default:
4448 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4449
4450 case BO_PtrMemD:
4451 case BO_PtrMemI:
4452 return HandleMemberPointerAccess(this->Info, E, Result);
4453 }
4454 }
4455
4456 bool VisitCastExpr(const CastExpr *E) {
4457 switch (E->getCastKind()) {
4458 default:
4459 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4460
4461 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004462 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004463 if (!this->Visit(E->getSubExpr()))
4464 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004465
4466 // Now figure out the necessary offset to add to the base LV to get from
4467 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004468 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4469 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004470 }
4471 }
4472};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004473}
Richard Smith027bf112011-11-17 22:56:20 +00004474
4475//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004476// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004477//
4478// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4479// function designators (in C), decl references to void objects (in C), and
4480// temporaries (if building with -Wno-address-of-temporary).
4481//
4482// LValue evaluation produces values comprising a base expression of one of the
4483// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004484// - Declarations
4485// * VarDecl
4486// * FunctionDecl
4487// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004488// * CompoundLiteralExpr in C
4489// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004490// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004491// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004492// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004493// * ObjCEncodeExpr
4494// * AddrLabelExpr
4495// * BlockExpr
4496// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004497// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004498// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004499// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004500// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4501// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004502// * A MaterializeTemporaryExpr that has static storage duration, with no
4503// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004504// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004505//===----------------------------------------------------------------------===//
4506namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004507class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004508 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004509public:
Richard Smith027bf112011-11-17 22:56:20 +00004510 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4511 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004512
Richard Smith11562c52011-10-28 17:51:58 +00004513 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004514 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004515
Peter Collingbournee9200682011-05-13 03:29:01 +00004516 bool VisitDeclRefExpr(const DeclRefExpr *E);
4517 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004518 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004519 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4520 bool VisitMemberExpr(const MemberExpr *E);
4521 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4522 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004523 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004524 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004525 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4526 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004527 bool VisitUnaryReal(const UnaryOperator *E);
4528 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004529 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4530 return VisitUnaryPreIncDec(UO);
4531 }
4532 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4533 return VisitUnaryPreIncDec(UO);
4534 }
Richard Smith3229b742013-05-05 21:17:10 +00004535 bool VisitBinAssign(const BinaryOperator *BO);
4536 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004537
Peter Collingbournee9200682011-05-13 03:29:01 +00004538 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004539 switch (E->getCastKind()) {
4540 default:
Richard Smith027bf112011-11-17 22:56:20 +00004541 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004542
Eli Friedmance3e02a2011-10-11 00:13:24 +00004543 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004544 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004545 if (!Visit(E->getSubExpr()))
4546 return false;
4547 Result.Designator.setInvalid();
4548 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004549
Richard Smith027bf112011-11-17 22:56:20 +00004550 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004551 if (!Visit(E->getSubExpr()))
4552 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004553 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004554 }
4555 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004556};
4557} // end anonymous namespace
4558
Richard Smith11562c52011-10-28 17:51:58 +00004559/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004560/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004561/// * function designators in C, and
4562/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004563/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004564static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4565 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004566 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004567 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004568}
4569
Peter Collingbournee9200682011-05-13 03:29:01 +00004570bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004571 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004572 return Success(FD);
4573 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004574 return VisitVarDecl(E, VD);
4575 return Error(E);
4576}
Richard Smith733237d2011-10-24 23:14:33 +00004577
Richard Smith11562c52011-10-28 17:51:58 +00004578bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004579 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004580 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4581 Frame = Info.CurrentCall;
4582
Richard Smithfec09922011-11-01 16:57:24 +00004583 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004584 if (Frame) {
4585 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004586 return true;
4587 }
Richard Smithce40ad62011-11-12 22:28:03 +00004588 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004589 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004590
Richard Smith3229b742013-05-05 21:17:10 +00004591 APValue *V;
4592 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004593 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004594 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004595 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004596 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4597 return false;
4598 }
Richard Smith3229b742013-05-05 21:17:10 +00004599 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004600}
4601
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004602bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4603 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004604 // Walk through the expression to find the materialized temporary itself.
4605 SmallVector<const Expr *, 2> CommaLHSs;
4606 SmallVector<SubobjectAdjustment, 2> Adjustments;
4607 const Expr *Inner = E->GetTemporaryExpr()->
4608 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004609
Richard Smith84401042013-06-03 05:03:02 +00004610 // If we passed any comma operators, evaluate their LHSs.
4611 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4612 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4613 return false;
4614
Richard Smithe6c01442013-06-05 00:46:14 +00004615 // A materialized temporary with static storage duration can appear within the
4616 // result of a constant expression evaluation, so we need to preserve its
4617 // value for use outside this evaluation.
4618 APValue *Value;
4619 if (E->getStorageDuration() == SD_Static) {
4620 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004621 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004622 Result.set(E);
4623 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004624 Value = &Info.CurrentCall->
4625 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004626 Result.set(E, Info.CurrentCall->Index);
4627 }
4628
Richard Smithea4ad5d2013-06-06 08:19:16 +00004629 QualType Type = Inner->getType();
4630
Richard Smith84401042013-06-03 05:03:02 +00004631 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004632 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4633 (E->getStorageDuration() == SD_Static &&
4634 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4635 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004636 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004637 }
Richard Smith84401042013-06-03 05:03:02 +00004638
4639 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004640 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4641 --I;
4642 switch (Adjustments[I].Kind) {
4643 case SubobjectAdjustment::DerivedToBaseAdjustment:
4644 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4645 Type, Result))
4646 return false;
4647 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4648 break;
4649
4650 case SubobjectAdjustment::FieldAdjustment:
4651 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4652 return false;
4653 Type = Adjustments[I].Field->getType();
4654 break;
4655
4656 case SubobjectAdjustment::MemberPointerAdjustment:
4657 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4658 Adjustments[I].Ptr.RHS))
4659 return false;
4660 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4661 break;
4662 }
4663 }
4664
4665 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004666}
4667
Peter Collingbournee9200682011-05-13 03:29:01 +00004668bool
4669LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004670 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4671 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4672 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004673 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004674}
4675
Richard Smith6e525142011-12-27 12:18:28 +00004676bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004677 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004678 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004679
4680 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4681 << E->getExprOperand()->getType()
4682 << E->getExprOperand()->getSourceRange();
4683 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004684}
4685
Francois Pichet0066db92012-04-16 04:08:35 +00004686bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4687 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004688}
Francois Pichet0066db92012-04-16 04:08:35 +00004689
Peter Collingbournee9200682011-05-13 03:29:01 +00004690bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004691 // Handle static data members.
4692 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4693 VisitIgnoredValue(E->getBase());
4694 return VisitVarDecl(E, VD);
4695 }
4696
Richard Smith254a73d2011-10-28 22:34:42 +00004697 // Handle static member functions.
4698 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4699 if (MD->isStatic()) {
4700 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004701 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004702 }
4703 }
4704
Richard Smithd62306a2011-11-10 06:34:14 +00004705 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004706 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004707}
4708
Peter Collingbournee9200682011-05-13 03:29:01 +00004709bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004710 // FIXME: Deal with vectors as array subscript bases.
4711 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004712 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004713
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004714 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004715 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004716
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004717 APSInt Index;
4718 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004719 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004720
Richard Smith861b5b52013-05-07 23:34:45 +00004721 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4722 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004723}
Eli Friedman9a156e52008-11-12 09:44:48 +00004724
Peter Collingbournee9200682011-05-13 03:29:01 +00004725bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004726 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004727}
4728
Richard Smith66c96992012-02-18 22:04:06 +00004729bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4730 if (!Visit(E->getSubExpr()))
4731 return false;
4732 // __real is a no-op on scalar lvalues.
4733 if (E->getSubExpr()->getType()->isAnyComplexType())
4734 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4735 return true;
4736}
4737
4738bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4739 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4740 "lvalue __imag__ on scalar?");
4741 if (!Visit(E->getSubExpr()))
4742 return false;
4743 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4744 return true;
4745}
4746
Richard Smith243ef902013-05-05 23:31:59 +00004747bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004748 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004749 return Error(UO);
4750
4751 if (!this->Visit(UO->getSubExpr()))
4752 return false;
4753
Richard Smith243ef902013-05-05 23:31:59 +00004754 return handleIncDec(
4755 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004756 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004757}
4758
4759bool LValueExprEvaluator::VisitCompoundAssignOperator(
4760 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004761 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004762 return Error(CAO);
4763
Richard Smith3229b742013-05-05 21:17:10 +00004764 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004765
4766 // The overall lvalue result is the result of evaluating the LHS.
4767 if (!this->Visit(CAO->getLHS())) {
4768 if (Info.keepEvaluatingAfterFailure())
4769 Evaluate(RHS, this->Info, CAO->getRHS());
4770 return false;
4771 }
4772
Richard Smith3229b742013-05-05 21:17:10 +00004773 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4774 return false;
4775
Richard Smith43e77732013-05-07 04:50:00 +00004776 return handleCompoundAssignment(
4777 this->Info, CAO,
4778 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4779 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004780}
4781
4782bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004783 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004784 return Error(E);
4785
Richard Smith3229b742013-05-05 21:17:10 +00004786 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004787
4788 if (!this->Visit(E->getLHS())) {
4789 if (Info.keepEvaluatingAfterFailure())
4790 Evaluate(NewVal, this->Info, E->getRHS());
4791 return false;
4792 }
4793
Richard Smith3229b742013-05-05 21:17:10 +00004794 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4795 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004796
4797 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004798 NewVal);
4799}
4800
Eli Friedman9a156e52008-11-12 09:44:48 +00004801//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004802// Pointer Evaluation
4803//===----------------------------------------------------------------------===//
4804
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004805namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004806class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004807 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004808 LValue &Result;
4809
Peter Collingbournee9200682011-05-13 03:29:01 +00004810 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004811 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004812 return true;
4813 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004814public:
Mike Stump11289f42009-09-09 15:08:12 +00004815
John McCall45d55e42010-05-07 21:00:08 +00004816 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004817 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004818
Richard Smith2e312c82012-03-03 22:46:17 +00004819 bool Success(const APValue &V, const Expr *E) {
4820 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004821 return true;
4822 }
Richard Smithfddd3842011-12-30 21:15:51 +00004823 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004824 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004825 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004826
John McCall45d55e42010-05-07 21:00:08 +00004827 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004828 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004829 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004830 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004831 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004832 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004833 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004834 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004835 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004836 bool VisitCallExpr(const CallExpr *E);
4837 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004838 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004839 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004840 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004841 }
Richard Smithd62306a2011-11-10 06:34:14 +00004842 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004843 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004844 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004845 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004846 if (!Info.CurrentCall->This) {
4847 if (Info.getLangOpts().CPlusPlus11)
4848 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4849 else
4850 Info.Diag(E);
4851 return false;
4852 }
Richard Smithd62306a2011-11-10 06:34:14 +00004853 Result = *Info.CurrentCall->This;
4854 return true;
4855 }
John McCallc07a0c72011-02-17 10:25:35 +00004856
Eli Friedman449fe542009-03-23 04:56:01 +00004857 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004858};
Chris Lattner05706e882008-07-11 18:11:29 +00004859} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004860
John McCall45d55e42010-05-07 21:00:08 +00004861static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004862 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004863 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004864}
4865
John McCall45d55e42010-05-07 21:00:08 +00004866bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004867 if (E->getOpcode() != BO_Add &&
4868 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004869 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004870
Chris Lattner05706e882008-07-11 18:11:29 +00004871 const Expr *PExp = E->getLHS();
4872 const Expr *IExp = E->getRHS();
4873 if (IExp->getType()->isPointerType())
4874 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004875
Richard Smith253c2a32012-01-27 01:14:48 +00004876 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4877 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004878 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004879
John McCall45d55e42010-05-07 21:00:08 +00004880 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004881 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004882 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004883
4884 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004885 if (E->getOpcode() == BO_Sub)
4886 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004887
Ted Kremenek28831752012-08-23 20:46:57 +00004888 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004889 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4890 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004891}
Eli Friedman9a156e52008-11-12 09:44:48 +00004892
John McCall45d55e42010-05-07 21:00:08 +00004893bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4894 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004895}
Mike Stump11289f42009-09-09 15:08:12 +00004896
Peter Collingbournee9200682011-05-13 03:29:01 +00004897bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4898 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004899
Eli Friedman847a2bc2009-12-27 05:43:15 +00004900 switch (E->getCastKind()) {
4901 default:
4902 break;
4903
John McCalle3027922010-08-25 11:45:40 +00004904 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004905 case CK_CPointerToObjCPointerCast:
4906 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004907 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00004908 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004909 if (!Visit(SubExpr))
4910 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004911 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4912 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4913 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004914 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004915 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004916 if (SubExpr->getType()->isVoidPointerType())
4917 CCEDiag(E, diag::note_constexpr_invalid_cast)
4918 << 3 << SubExpr->getType();
4919 else
4920 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4921 }
Richard Smith96e0c102011-11-04 02:25:55 +00004922 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004923
Anders Carlsson18275092010-10-31 20:41:46 +00004924 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004925 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004926 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004927 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004928 if (!Result.Base && Result.Offset.isZero())
4929 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004930
Richard Smithd62306a2011-11-10 06:34:14 +00004931 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004932 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004933 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4934 castAs<PointerType>()->getPointeeType(),
4935 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004936
Richard Smith027bf112011-11-17 22:56:20 +00004937 case CK_BaseToDerived:
4938 if (!Visit(E->getSubExpr()))
4939 return false;
4940 if (!Result.Base && Result.Offset.isZero())
4941 return true;
4942 return HandleBaseToDerivedCast(Info, E, Result);
4943
Richard Smith0b0a0b62011-10-29 20:57:55 +00004944 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004945 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004946 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004947
John McCalle3027922010-08-25 11:45:40 +00004948 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004949 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4950
Richard Smith2e312c82012-03-03 22:46:17 +00004951 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004952 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004953 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004954
John McCall45d55e42010-05-07 21:00:08 +00004955 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004956 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4957 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004958 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004959 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004960 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004961 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004962 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004963 return true;
4964 } else {
4965 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004966 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004967 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004968 }
4969 }
John McCalle3027922010-08-25 11:45:40 +00004970 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004971 if (SubExpr->isGLValue()) {
4972 if (!EvaluateLValue(SubExpr, Result, Info))
4973 return false;
4974 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004975 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004976 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004977 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004978 return false;
4979 }
Richard Smith96e0c102011-11-04 02:25:55 +00004980 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004981 if (const ConstantArrayType *CAT
4982 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4983 Result.addArray(Info, E, CAT);
4984 else
4985 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004986 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004987
John McCalle3027922010-08-25 11:45:40 +00004988 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004989 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004990 }
4991
Richard Smith11562c52011-10-28 17:51:58 +00004992 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004993}
Chris Lattner05706e882008-07-11 18:11:29 +00004994
Hal Finkel0dd05d42014-10-03 17:18:37 +00004995static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
4996 // C++ [expr.alignof]p3:
4997 // When alignof is applied to a reference type, the result is the
4998 // alignment of the referenced type.
4999 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5000 T = Ref->getPointeeType();
5001
5002 // __alignof is defined to return the preferred alignment.
5003 return Info.Ctx.toCharUnitsFromBits(
5004 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5005}
5006
5007static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5008 E = E->IgnoreParens();
5009
5010 // The kinds of expressions that we have special-case logic here for
5011 // should be kept up to date with the special checks for those
5012 // expressions in Sema.
5013
5014 // alignof decl is always accepted, even if it doesn't make sense: we default
5015 // to 1 in those cases.
5016 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5017 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5018 /*RefAsPointee*/true);
5019
5020 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5021 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5022 /*RefAsPointee*/true);
5023
5024 return GetAlignOfType(Info, E->getType());
5025}
5026
Peter Collingbournee9200682011-05-13 03:29:01 +00005027bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005028 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005029 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005030
Alp Tokera724cff2013-12-28 21:59:02 +00005031 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005032 case Builtin::BI__builtin_addressof:
5033 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005034 case Builtin::BI__builtin_assume_aligned: {
5035 // We need to be very careful here because: if the pointer does not have the
5036 // asserted alignment, then the behavior is undefined, and undefined
5037 // behavior is non-constant.
5038 if (!EvaluatePointer(E->getArg(0), Result, Info))
5039 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005040
Hal Finkel0dd05d42014-10-03 17:18:37 +00005041 LValue OffsetResult(Result);
5042 APSInt Alignment;
5043 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5044 return false;
5045 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5046
5047 if (E->getNumArgs() > 2) {
5048 APSInt Offset;
5049 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5050 return false;
5051
5052 int64_t AdditionalOffset = -getExtValue(Offset);
5053 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5054 }
5055
5056 // If there is a base object, then it must have the correct alignment.
5057 if (OffsetResult.Base) {
5058 CharUnits BaseAlignment;
5059 if (const ValueDecl *VD =
5060 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5061 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5062 } else {
5063 BaseAlignment =
5064 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5065 }
5066
5067 if (BaseAlignment < Align) {
5068 Result.Designator.setInvalid();
5069 // FIXME: Quantities here cast to integers because the plural modifier
5070 // does not work on APSInts yet.
5071 CCEDiag(E->getArg(0),
5072 diag::note_constexpr_baa_insufficient_alignment) << 0
5073 << (int) BaseAlignment.getQuantity()
5074 << (unsigned) getExtValue(Alignment);
5075 return false;
5076 }
5077 }
5078
5079 // The offset must also have the correct alignment.
5080 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5081 Result.Designator.setInvalid();
5082 APSInt Offset(64, false);
5083 Offset = OffsetResult.Offset.getQuantity();
5084
5085 if (OffsetResult.Base)
5086 CCEDiag(E->getArg(0),
5087 diag::note_constexpr_baa_insufficient_alignment) << 1
5088 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5089 else
5090 CCEDiag(E->getArg(0),
5091 diag::note_constexpr_baa_value_insufficient_alignment)
5092 << Offset << (unsigned) getExtValue(Alignment);
5093
5094 return false;
5095 }
5096
5097 return true;
5098 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005099 default:
5100 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5101 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005102}
Chris Lattner05706e882008-07-11 18:11:29 +00005103
5104//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005105// Member Pointer Evaluation
5106//===----------------------------------------------------------------------===//
5107
5108namespace {
5109class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005110 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005111 MemberPtr &Result;
5112
5113 bool Success(const ValueDecl *D) {
5114 Result = MemberPtr(D);
5115 return true;
5116 }
5117public:
5118
5119 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5120 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5121
Richard Smith2e312c82012-03-03 22:46:17 +00005122 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005123 Result.setFrom(V);
5124 return true;
5125 }
Richard Smithfddd3842011-12-30 21:15:51 +00005126 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005127 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005128 }
5129
5130 bool VisitCastExpr(const CastExpr *E);
5131 bool VisitUnaryAddrOf(const UnaryOperator *E);
5132};
5133} // end anonymous namespace
5134
5135static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5136 EvalInfo &Info) {
5137 assert(E->isRValue() && E->getType()->isMemberPointerType());
5138 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5139}
5140
5141bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5142 switch (E->getCastKind()) {
5143 default:
5144 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5145
5146 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005147 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005148 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005149
5150 case CK_BaseToDerivedMemberPointer: {
5151 if (!Visit(E->getSubExpr()))
5152 return false;
5153 if (E->path_empty())
5154 return true;
5155 // Base-to-derived member pointer casts store the path in derived-to-base
5156 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5157 // the wrong end of the derived->base arc, so stagger the path by one class.
5158 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5159 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5160 PathI != PathE; ++PathI) {
5161 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5162 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5163 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005164 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005165 }
5166 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5167 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005168 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005169 return true;
5170 }
5171
5172 case CK_DerivedToBaseMemberPointer:
5173 if (!Visit(E->getSubExpr()))
5174 return false;
5175 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5176 PathE = E->path_end(); PathI != PathE; ++PathI) {
5177 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5178 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5179 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005180 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005181 }
5182 return true;
5183 }
5184}
5185
5186bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5187 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5188 // member can be formed.
5189 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5190}
5191
5192//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005193// Record Evaluation
5194//===----------------------------------------------------------------------===//
5195
5196namespace {
5197 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005198 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005199 const LValue &This;
5200 APValue &Result;
5201 public:
5202
5203 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5204 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5205
Richard Smith2e312c82012-03-03 22:46:17 +00005206 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005207 Result = V;
5208 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005209 }
Richard Smithfddd3842011-12-30 21:15:51 +00005210 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005211
Richard Smith52a980a2015-08-28 02:43:42 +00005212 bool VisitCallExpr(const CallExpr *E) {
5213 return handleCallExpr(E, Result, &This);
5214 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005215 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005216 bool VisitInitListExpr(const InitListExpr *E);
5217 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005218 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005219 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005220}
Richard Smithd62306a2011-11-10 06:34:14 +00005221
Richard Smithfddd3842011-12-30 21:15:51 +00005222/// Perform zero-initialization on an object of non-union class type.
5223/// C++11 [dcl.init]p5:
5224/// To zero-initialize an object or reference of type T means:
5225/// [...]
5226/// -- if T is a (possibly cv-qualified) non-union class type,
5227/// each non-static data member and each base-class subobject is
5228/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005229static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5230 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005231 const LValue &This, APValue &Result) {
5232 assert(!RD->isUnion() && "Expected non-union class type");
5233 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5234 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005235 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005236
John McCalld7bca762012-05-01 00:38:49 +00005237 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005238 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5239
5240 if (CD) {
5241 unsigned Index = 0;
5242 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005243 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005244 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5245 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005246 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5247 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005248 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005249 Result.getStructBase(Index)))
5250 return false;
5251 }
5252 }
5253
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005254 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005255 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005256 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005257 continue;
5258
5259 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005260 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005261 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005262
David Blaikie2d7c57e2012-04-30 02:36:29 +00005263 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005264 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005265 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005266 return false;
5267 }
5268
5269 return true;
5270}
5271
5272bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5273 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005274 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005275 if (RD->isUnion()) {
5276 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5277 // object's first non-static named data member is zero-initialized
5278 RecordDecl::field_iterator I = RD->field_begin();
5279 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005280 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005281 return true;
5282 }
5283
5284 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005285 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005286 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005287 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005288 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005289 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005290 }
5291
Richard Smith5d108602012-02-17 00:44:16 +00005292 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005293 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005294 return false;
5295 }
5296
Richard Smitha8105bc2012-01-06 16:39:00 +00005297 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005298}
5299
Richard Smithe97cbd72011-11-11 04:05:33 +00005300bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5301 switch (E->getCastKind()) {
5302 default:
5303 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5304
5305 case CK_ConstructorConversion:
5306 return Visit(E->getSubExpr());
5307
5308 case CK_DerivedToBase:
5309 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005310 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005311 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005312 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005313 if (!DerivedObject.isStruct())
5314 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005315
5316 // Derived-to-base rvalue conversion: just slice off the derived part.
5317 APValue *Value = &DerivedObject;
5318 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5319 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5320 PathE = E->path_end(); PathI != PathE; ++PathI) {
5321 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5322 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5323 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5324 RD = Base;
5325 }
5326 Result = *Value;
5327 return true;
5328 }
5329 }
5330}
5331
Richard Smithd62306a2011-11-10 06:34:14 +00005332bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5333 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005334 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005335 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5336
5337 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005338 const FieldDecl *Field = E->getInitializedFieldInUnion();
5339 Result = APValue(Field);
5340 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005341 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005342
5343 // If the initializer list for a union does not contain any elements, the
5344 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005345 // FIXME: The element should be initialized from an initializer list.
5346 // Is this difference ever observable for initializer lists which
5347 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005348 ImplicitValueInitExpr VIE(Field->getType());
5349 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5350
Richard Smithd62306a2011-11-10 06:34:14 +00005351 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005352 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5353 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005354
5355 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5356 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5357 isa<CXXDefaultInitExpr>(InitExpr));
5358
Richard Smithb228a862012-02-15 02:18:13 +00005359 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005360 }
5361
5362 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5363 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005364 Result = APValue(APValue::UninitStruct(), 0,
5365 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005366 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005367 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005368 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005369 // Anonymous bit-fields are not considered members of the class for
5370 // purposes of aggregate initialization.
5371 if (Field->isUnnamedBitfield())
5372 continue;
5373
5374 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005375
Richard Smith253c2a32012-01-27 01:14:48 +00005376 bool HaveInit = ElementNo < E->getNumInits();
5377
5378 // FIXME: Diagnostics here should point to the end of the initializer
5379 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005380 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005381 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005382 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005383
5384 // Perform an implicit value-initialization for members beyond the end of
5385 // the initializer list.
5386 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005387 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005388
Richard Smith852c9db2013-04-20 22:23:05 +00005389 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5390 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5391 isa<CXXDefaultInitExpr>(Init));
5392
Richard Smith49ca8aa2013-08-06 07:09:20 +00005393 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5394 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5395 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005396 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005397 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005398 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005399 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005400 }
5401 }
5402
Richard Smith253c2a32012-01-27 01:14:48 +00005403 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005404}
5405
5406bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5407 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005408 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5409
Richard Smithfddd3842011-12-30 21:15:51 +00005410 bool ZeroInit = E->requiresZeroInitialization();
5411 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005412 // If we've already performed zero-initialization, we're already done.
5413 if (!Result.isUninit())
5414 return true;
5415
Richard Smithda3f4fd2014-03-05 23:32:50 +00005416 // We can get here in two different ways:
5417 // 1) We're performing value-initialization, and should zero-initialize
5418 // the object, or
5419 // 2) We're performing default-initialization of an object with a trivial
5420 // constexpr default constructor, in which case we should start the
5421 // lifetimes of all the base subobjects (there can be no data member
5422 // subobjects in this case) per [basic.life]p1.
5423 // Either way, ZeroInitialization is appropriate.
5424 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005425 }
5426
Craig Topper36250ad2014-05-12 05:36:57 +00005427 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005428 FD->getBody(Definition);
5429
Richard Smith357362d2011-12-13 06:39:58 +00005430 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5431 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005432
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005433 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005434 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005435 if (const MaterializeTemporaryExpr *ME
5436 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5437 return Visit(ME->GetTemporaryExpr());
5438
Richard Smithfddd3842011-12-30 21:15:51 +00005439 if (ZeroInit && !ZeroInitialization(E))
5440 return false;
5441
Craig Topper5fc8fc22014-08-27 06:28:36 +00005442 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005443 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005444 cast<CXXConstructorDecl>(Definition), Info,
5445 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005446}
5447
Richard Smithcc1b96d2013-06-12 22:31:48 +00005448bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5449 const CXXStdInitializerListExpr *E) {
5450 const ConstantArrayType *ArrayType =
5451 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5452
5453 LValue Array;
5454 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5455 return false;
5456
5457 // Get a pointer to the first element of the array.
5458 Array.addArray(Info, E, ArrayType);
5459
5460 // FIXME: Perform the checks on the field types in SemaInit.
5461 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5462 RecordDecl::field_iterator Field = Record->field_begin();
5463 if (Field == Record->field_end())
5464 return Error(E);
5465
5466 // Start pointer.
5467 if (!Field->getType()->isPointerType() ||
5468 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5469 ArrayType->getElementType()))
5470 return Error(E);
5471
5472 // FIXME: What if the initializer_list type has base classes, etc?
5473 Result = APValue(APValue::UninitStruct(), 0, 2);
5474 Array.moveInto(Result.getStructField(0));
5475
5476 if (++Field == Record->field_end())
5477 return Error(E);
5478
5479 if (Field->getType()->isPointerType() &&
5480 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5481 ArrayType->getElementType())) {
5482 // End pointer.
5483 if (!HandleLValueArrayAdjustment(Info, E, Array,
5484 ArrayType->getElementType(),
5485 ArrayType->getSize().getZExtValue()))
5486 return false;
5487 Array.moveInto(Result.getStructField(1));
5488 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5489 // Length.
5490 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5491 else
5492 return Error(E);
5493
5494 if (++Field != Record->field_end())
5495 return Error(E);
5496
5497 return true;
5498}
5499
Richard Smithd62306a2011-11-10 06:34:14 +00005500static bool EvaluateRecord(const Expr *E, const LValue &This,
5501 APValue &Result, EvalInfo &Info) {
5502 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005503 "can't evaluate expression as a record rvalue");
5504 return RecordExprEvaluator(Info, This, Result).Visit(E);
5505}
5506
5507//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005508// Temporary Evaluation
5509//
5510// Temporaries are represented in the AST as rvalues, but generally behave like
5511// lvalues. The full-object of which the temporary is a subobject is implicitly
5512// materialized so that a reference can bind to it.
5513//===----------------------------------------------------------------------===//
5514namespace {
5515class TemporaryExprEvaluator
5516 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5517public:
5518 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5519 LValueExprEvaluatorBaseTy(Info, Result) {}
5520
5521 /// Visit an expression which constructs the value of this temporary.
5522 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005523 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005524 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5525 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005526 }
5527
5528 bool VisitCastExpr(const CastExpr *E) {
5529 switch (E->getCastKind()) {
5530 default:
5531 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5532
5533 case CK_ConstructorConversion:
5534 return VisitConstructExpr(E->getSubExpr());
5535 }
5536 }
5537 bool VisitInitListExpr(const InitListExpr *E) {
5538 return VisitConstructExpr(E);
5539 }
5540 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5541 return VisitConstructExpr(E);
5542 }
5543 bool VisitCallExpr(const CallExpr *E) {
5544 return VisitConstructExpr(E);
5545 }
Richard Smith513955c2014-12-17 19:24:30 +00005546 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5547 return VisitConstructExpr(E);
5548 }
Richard Smith027bf112011-11-17 22:56:20 +00005549};
5550} // end anonymous namespace
5551
5552/// Evaluate an expression of record type as a temporary.
5553static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005554 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005555 return TemporaryExprEvaluator(Info, Result).Visit(E);
5556}
5557
5558//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005559// Vector Evaluation
5560//===----------------------------------------------------------------------===//
5561
5562namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005563 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005564 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005565 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005566 public:
Mike Stump11289f42009-09-09 15:08:12 +00005567
Richard Smith2d406342011-10-22 21:10:00 +00005568 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5569 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005570
Richard Smith2d406342011-10-22 21:10:00 +00005571 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5572 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5573 // FIXME: remove this APValue copy.
5574 Result = APValue(V.data(), V.size());
5575 return true;
5576 }
Richard Smith2e312c82012-03-03 22:46:17 +00005577 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005578 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005579 Result = V;
5580 return true;
5581 }
Richard Smithfddd3842011-12-30 21:15:51 +00005582 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005583
Richard Smith2d406342011-10-22 21:10:00 +00005584 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005585 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005586 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005587 bool VisitInitListExpr(const InitListExpr *E);
5588 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005589 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005590 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005591 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005592 };
5593} // end anonymous namespace
5594
5595static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005596 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005597 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005598}
5599
Richard Smith2d406342011-10-22 21:10:00 +00005600bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5601 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005602 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005603
Richard Smith161f09a2011-12-06 22:44:34 +00005604 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005605 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005606
Eli Friedmanc757de22011-03-25 00:43:55 +00005607 switch (E->getCastKind()) {
5608 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005609 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005610 if (SETy->isIntegerType()) {
5611 APSInt IntResult;
5612 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005613 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005614 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005615 } else if (SETy->isRealFloatingType()) {
5616 APFloat F(0.0);
5617 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005618 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005619 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005620 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005621 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005622 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005623
5624 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005625 SmallVector<APValue, 4> Elts(NElts, Val);
5626 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005627 }
Eli Friedman803acb32011-12-22 03:51:45 +00005628 case CK_BitCast: {
5629 // Evaluate the operand into an APInt we can extract from.
5630 llvm::APInt SValInt;
5631 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5632 return false;
5633 // Extract the elements
5634 QualType EltTy = VTy->getElementType();
5635 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5636 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5637 SmallVector<APValue, 4> Elts;
5638 if (EltTy->isRealFloatingType()) {
5639 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005640 unsigned FloatEltSize = EltSize;
5641 if (&Sem == &APFloat::x87DoubleExtended)
5642 FloatEltSize = 80;
5643 for (unsigned i = 0; i < NElts; i++) {
5644 llvm::APInt Elt;
5645 if (BigEndian)
5646 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5647 else
5648 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005649 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005650 }
5651 } else if (EltTy->isIntegerType()) {
5652 for (unsigned i = 0; i < NElts; i++) {
5653 llvm::APInt Elt;
5654 if (BigEndian)
5655 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5656 else
5657 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5658 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5659 }
5660 } else {
5661 return Error(E);
5662 }
5663 return Success(Elts, E);
5664 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005665 default:
Richard Smith11562c52011-10-28 17:51:58 +00005666 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005667 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005668}
5669
Richard Smith2d406342011-10-22 21:10:00 +00005670bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005671VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005672 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005673 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005674 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005675
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005676 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005677 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005678
Eli Friedmanb9c71292012-01-03 23:24:20 +00005679 // The number of initializers can be less than the number of
5680 // vector elements. For OpenCL, this can be due to nested vector
5681 // initialization. For GCC compatibility, missing trailing elements
5682 // should be initialized with zeroes.
5683 unsigned CountInits = 0, CountElts = 0;
5684 while (CountElts < NumElements) {
5685 // Handle nested vector initialization.
5686 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005687 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005688 APValue v;
5689 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5690 return Error(E);
5691 unsigned vlen = v.getVectorLength();
5692 for (unsigned j = 0; j < vlen; j++)
5693 Elements.push_back(v.getVectorElt(j));
5694 CountElts += vlen;
5695 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005696 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005697 if (CountInits < NumInits) {
5698 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005699 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005700 } else // trailing integer zero.
5701 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5702 Elements.push_back(APValue(sInt));
5703 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005704 } else {
5705 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005706 if (CountInits < NumInits) {
5707 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005708 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005709 } else // trailing float zero.
5710 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5711 Elements.push_back(APValue(f));
5712 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005713 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005714 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005715 }
Richard Smith2d406342011-10-22 21:10:00 +00005716 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005717}
5718
Richard Smith2d406342011-10-22 21:10:00 +00005719bool
Richard Smithfddd3842011-12-30 21:15:51 +00005720VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005721 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005722 QualType EltTy = VT->getElementType();
5723 APValue ZeroElement;
5724 if (EltTy->isIntegerType())
5725 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5726 else
5727 ZeroElement =
5728 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5729
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005730 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005731 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005732}
5733
Richard Smith2d406342011-10-22 21:10:00 +00005734bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005735 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005736 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005737}
5738
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005739//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005740// Array Evaluation
5741//===----------------------------------------------------------------------===//
5742
5743namespace {
5744 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005745 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005746 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005747 APValue &Result;
5748 public:
5749
Richard Smithd62306a2011-11-10 06:34:14 +00005750 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5751 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005752
5753 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005754 assert((V.isArray() || V.isLValue()) &&
5755 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005756 Result = V;
5757 return true;
5758 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005759
Richard Smithfddd3842011-12-30 21:15:51 +00005760 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005761 const ConstantArrayType *CAT =
5762 Info.Ctx.getAsConstantArrayType(E->getType());
5763 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005764 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005765
5766 Result = APValue(APValue::UninitArray(), 0,
5767 CAT->getSize().getZExtValue());
5768 if (!Result.hasArrayFiller()) return true;
5769
Richard Smithfddd3842011-12-30 21:15:51 +00005770 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005771 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005772 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005773 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005774 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005775 }
5776
Richard Smith52a980a2015-08-28 02:43:42 +00005777 bool VisitCallExpr(const CallExpr *E) {
5778 return handleCallExpr(E, Result, &This);
5779 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005780 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005781 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005782 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5783 const LValue &Subobject,
5784 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005785 };
5786} // end anonymous namespace
5787
Richard Smithd62306a2011-11-10 06:34:14 +00005788static bool EvaluateArray(const Expr *E, const LValue &This,
5789 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005790 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005791 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005792}
5793
5794bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5795 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5796 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005797 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005798
Richard Smithca2cfbf2011-12-22 01:07:19 +00005799 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5800 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005801 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005802 LValue LV;
5803 if (!EvaluateLValue(E->getInit(0), LV, Info))
5804 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005805 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005806 LV.moveInto(Val);
5807 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005808 }
5809
Richard Smith253c2a32012-01-27 01:14:48 +00005810 bool Success = true;
5811
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005812 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5813 "zero-initialized array shouldn't have any initialized elts");
5814 APValue Filler;
5815 if (Result.isArray() && Result.hasArrayFiller())
5816 Filler = Result.getArrayFiller();
5817
Richard Smith9543c5e2013-04-22 14:44:29 +00005818 unsigned NumEltsToInit = E->getNumInits();
5819 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005820 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005821
5822 // If the initializer might depend on the array index, run it for each
5823 // array element. For now, just whitelist non-class value-initialization.
5824 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5825 NumEltsToInit = NumElts;
5826
5827 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005828
5829 // If the array was previously zero-initialized, preserve the
5830 // zero-initialized values.
5831 if (!Filler.isUninit()) {
5832 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5833 Result.getArrayInitializedElt(I) = Filler;
5834 if (Result.hasArrayFiller())
5835 Result.getArrayFiller() = Filler;
5836 }
5837
Richard Smithd62306a2011-11-10 06:34:14 +00005838 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005839 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005840 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5841 const Expr *Init =
5842 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005843 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005844 Info, Subobject, Init) ||
5845 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005846 CAT->getElementType(), 1)) {
5847 if (!Info.keepEvaluatingAfterFailure())
5848 return false;
5849 Success = false;
5850 }
Richard Smithd62306a2011-11-10 06:34:14 +00005851 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005852
Richard Smith9543c5e2013-04-22 14:44:29 +00005853 if (!Result.hasArrayFiller())
5854 return Success;
5855
5856 // If we get here, we have a trivial filler, which we can just evaluate
5857 // once and splat over the rest of the array elements.
5858 assert(FillerExpr && "no array filler for incomplete init list");
5859 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5860 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005861}
5862
Richard Smith027bf112011-11-17 22:56:20 +00005863bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005864 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5865}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005866
Richard Smith9543c5e2013-04-22 14:44:29 +00005867bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5868 const LValue &Subobject,
5869 APValue *Value,
5870 QualType Type) {
5871 bool HadZeroInit = !Value->isUninit();
5872
5873 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5874 unsigned N = CAT->getSize().getZExtValue();
5875
5876 // Preserve the array filler if we had prior zero-initialization.
5877 APValue Filler =
5878 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5879 : APValue();
5880
5881 *Value = APValue(APValue::UninitArray(), N, N);
5882
5883 if (HadZeroInit)
5884 for (unsigned I = 0; I != N; ++I)
5885 Value->getArrayInitializedElt(I) = Filler;
5886
5887 // Initialize the elements.
5888 LValue ArrayElt = Subobject;
5889 ArrayElt.addArray(Info, E, CAT);
5890 for (unsigned I = 0; I != N; ++I)
5891 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5892 CAT->getElementType()) ||
5893 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5894 CAT->getElementType(), 1))
5895 return false;
5896
5897 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005898 }
Richard Smith027bf112011-11-17 22:56:20 +00005899
Richard Smith9543c5e2013-04-22 14:44:29 +00005900 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005901 return Error(E);
5902
Richard Smith027bf112011-11-17 22:56:20 +00005903 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005904
Richard Smithfddd3842011-12-30 21:15:51 +00005905 bool ZeroInit = E->requiresZeroInitialization();
5906 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005907 if (HadZeroInit)
5908 return true;
5909
Richard Smithda3f4fd2014-03-05 23:32:50 +00005910 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5911 ImplicitValueInitExpr VIE(Type);
5912 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005913 }
5914
Craig Topper36250ad2014-05-12 05:36:57 +00005915 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005916 FD->getBody(Definition);
5917
Richard Smith357362d2011-12-13 06:39:58 +00005918 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5919 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005920
Richard Smith9eae7232012-01-12 18:54:33 +00005921 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005922 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005923 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005924 return false;
5925 }
5926
Craig Topper5fc8fc22014-08-27 06:28:36 +00005927 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005928 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005929 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005930 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005931}
5932
Richard Smithf3e9e432011-11-07 09:22:26 +00005933//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005934// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005935//
5936// As a GNU extension, we support casting pointers to sufficiently-wide integer
5937// types and back in constant folding. Integer values are thus represented
5938// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005939//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005940
5941namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005942class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005943 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005944 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005945public:
Richard Smith2e312c82012-03-03 22:46:17 +00005946 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005947 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005948
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005949 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005950 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005951 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005952 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005953 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005954 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005955 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005956 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005957 return true;
5958 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005959 bool Success(const llvm::APSInt &SI, const Expr *E) {
5960 return Success(SI, E, Result);
5961 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005962
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005963 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005964 assert(E->getType()->isIntegralOrEnumerationType() &&
5965 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005966 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005967 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005968 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005969 Result.getInt().setIsUnsigned(
5970 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005971 return true;
5972 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005973 bool Success(const llvm::APInt &I, const Expr *E) {
5974 return Success(I, E, Result);
5975 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005976
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005977 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005978 assert(E->getType()->isIntegralOrEnumerationType() &&
5979 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005980 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005981 return true;
5982 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005983 bool Success(uint64_t Value, const Expr *E) {
5984 return Success(Value, E, Result);
5985 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005986
Ken Dyckdbc01912011-03-11 02:13:43 +00005987 bool Success(CharUnits Size, const Expr *E) {
5988 return Success(Size.getQuantity(), E);
5989 }
5990
Richard Smith2e312c82012-03-03 22:46:17 +00005991 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005992 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005993 Result = V;
5994 return true;
5995 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005996 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005997 }
Mike Stump11289f42009-09-09 15:08:12 +00005998
Richard Smithfddd3842011-12-30 21:15:51 +00005999 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006000
Peter Collingbournee9200682011-05-13 03:29:01 +00006001 //===--------------------------------------------------------------------===//
6002 // Visitor Methods
6003 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006004
Chris Lattner7174bf32008-07-12 00:38:25 +00006005 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006006 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006007 }
6008 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006009 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006010 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006011
6012 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6013 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006014 if (CheckReferencedDecl(E, E->getDecl()))
6015 return true;
6016
6017 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006018 }
6019 bool VisitMemberExpr(const MemberExpr *E) {
6020 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00006021 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006022 return true;
6023 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006024
6025 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006026 }
6027
Peter Collingbournee9200682011-05-13 03:29:01 +00006028 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006029 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006030 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006031 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006032
Peter Collingbournee9200682011-05-13 03:29:01 +00006033 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006034 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006035
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006036 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006037 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006038 }
Mike Stump11289f42009-09-09 15:08:12 +00006039
Ted Kremeneke65b0862012-03-06 20:05:56 +00006040 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6041 return Success(E->getValue(), E);
6042 }
6043
Richard Smith4ce706a2011-10-11 21:43:33 +00006044 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006045 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006046 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006047 }
6048
Douglas Gregor29c42f22012-02-24 07:38:34 +00006049 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6050 return Success(E->getValue(), E);
6051 }
6052
John Wiegley6242b6a2011-04-28 00:16:57 +00006053 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6054 return Success(E->getValue(), E);
6055 }
6056
John Wiegleyf9f65842011-04-25 06:54:41 +00006057 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6058 return Success(E->getValue(), E);
6059 }
6060
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006061 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006062 bool VisitUnaryImag(const UnaryOperator *E);
6063
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006064 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006065 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006066
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006067private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006068 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006069 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006070};
Chris Lattner05706e882008-07-11 18:11:29 +00006071} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006072
Richard Smith11562c52011-10-28 17:51:58 +00006073/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6074/// produce either the integer value or a pointer.
6075///
6076/// GCC has a heinous extension which folds casts between pointer types and
6077/// pointer-sized integral types. We support this by allowing the evaluation of
6078/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6079/// Some simple arithmetic on such values is supported (they are treated much
6080/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006081static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006082 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006083 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006084 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006085}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006086
Richard Smithf57d8cb2011-12-09 22:58:01 +00006087static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006088 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006089 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006090 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006091 if (!Val.isInt()) {
6092 // FIXME: It would be better to produce the diagnostic for casting
6093 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006094 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006095 return false;
6096 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006097 Result = Val.getInt();
6098 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006099}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006100
Richard Smithf57d8cb2011-12-09 22:58:01 +00006101/// Check whether the given declaration can be directly converted to an integral
6102/// rvalue. If not, no diagnostic is produced; there are other things we can
6103/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006104bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006105 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006106 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006107 // Check for signedness/width mismatches between E type and ECD value.
6108 bool SameSign = (ECD->getInitVal().isSigned()
6109 == E->getType()->isSignedIntegerOrEnumerationType());
6110 bool SameWidth = (ECD->getInitVal().getBitWidth()
6111 == Info.Ctx.getIntWidth(E->getType()));
6112 if (SameSign && SameWidth)
6113 return Success(ECD->getInitVal(), E);
6114 else {
6115 // Get rid of mismatch (otherwise Success assertions will fail)
6116 // by computing a new value matching the type of E.
6117 llvm::APSInt Val = ECD->getInitVal();
6118 if (!SameSign)
6119 Val.setIsSigned(!ECD->getInitVal().isSigned());
6120 if (!SameWidth)
6121 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6122 return Success(Val, E);
6123 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006124 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006125 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006126}
6127
Chris Lattner86ee2862008-10-06 06:40:35 +00006128/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6129/// as GCC.
6130static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6131 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006132 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006133 enum gcc_type_class {
6134 no_type_class = -1,
6135 void_type_class, integer_type_class, char_type_class,
6136 enumeral_type_class, boolean_type_class,
6137 pointer_type_class, reference_type_class, offset_type_class,
6138 real_type_class, complex_type_class,
6139 function_type_class, method_type_class,
6140 record_type_class, union_type_class,
6141 array_type_class, string_type_class,
6142 lang_type_class
6143 };
Mike Stump11289f42009-09-09 15:08:12 +00006144
6145 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006146 // ideal, however it is what gcc does.
6147 if (E->getNumArgs() == 0)
6148 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006149
Chris Lattner86ee2862008-10-06 06:40:35 +00006150 QualType ArgTy = E->getArg(0)->getType();
6151 if (ArgTy->isVoidType())
6152 return void_type_class;
6153 else if (ArgTy->isEnumeralType())
6154 return enumeral_type_class;
6155 else if (ArgTy->isBooleanType())
6156 return boolean_type_class;
6157 else if (ArgTy->isCharType())
6158 return string_type_class; // gcc doesn't appear to use char_type_class
6159 else if (ArgTy->isIntegerType())
6160 return integer_type_class;
6161 else if (ArgTy->isPointerType())
6162 return pointer_type_class;
6163 else if (ArgTy->isReferenceType())
6164 return reference_type_class;
6165 else if (ArgTy->isRealType())
6166 return real_type_class;
6167 else if (ArgTy->isComplexType())
6168 return complex_type_class;
6169 else if (ArgTy->isFunctionType())
6170 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00006171 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00006172 return record_type_class;
6173 else if (ArgTy->isUnionType())
6174 return union_type_class;
6175 else if (ArgTy->isArrayType())
6176 return array_type_class;
6177 else if (ArgTy->isUnionType())
6178 return union_type_class;
6179 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00006180 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006181}
6182
Richard Smith5fab0c92011-12-28 19:48:30 +00006183/// EvaluateBuiltinConstantPForLValue - Determine the result of
6184/// __builtin_constant_p when applied to the given lvalue.
6185///
6186/// An lvalue is only "constant" if it is a pointer or reference to the first
6187/// character of a string literal.
6188template<typename LValue>
6189static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006190 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006191 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6192}
6193
6194/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6195/// GCC as we can manage.
6196static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6197 QualType ArgType = Arg->getType();
6198
6199 // __builtin_constant_p always has one operand. The rules which gcc follows
6200 // are not precisely documented, but are as follows:
6201 //
6202 // - If the operand is of integral, floating, complex or enumeration type,
6203 // and can be folded to a known value of that type, it returns 1.
6204 // - If the operand and can be folded to a pointer to the first character
6205 // of a string literal (or such a pointer cast to an integral type), it
6206 // returns 1.
6207 //
6208 // Otherwise, it returns 0.
6209 //
6210 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6211 // its support for this does not currently work.
6212 if (ArgType->isIntegralOrEnumerationType()) {
6213 Expr::EvalResult Result;
6214 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6215 return false;
6216
6217 APValue &V = Result.Val;
6218 if (V.getKind() == APValue::Int)
6219 return true;
6220
6221 return EvaluateBuiltinConstantPForLValue(V);
6222 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6223 return Arg->isEvaluatable(Ctx);
6224 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6225 LValue LV;
6226 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006227 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006228 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6229 : EvaluatePointer(Arg, LV, Info)) &&
6230 !Status.HasSideEffects)
6231 return EvaluateBuiltinConstantPForLValue(LV);
6232 }
6233
6234 // Anything else isn't considered to be sufficiently constant.
6235 return false;
6236}
6237
John McCall95007602010-05-10 23:27:23 +00006238/// Retrieves the "underlying object type" of the given expression,
6239/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006240static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006241 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6242 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006243 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006244 } else if (const Expr *E = B.get<const Expr*>()) {
6245 if (isa<CompoundLiteralExpr>(E))
6246 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006247 }
6248
6249 return QualType();
6250}
6251
George Burgess IV3a03fab2015-09-04 21:28:13 +00006252/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006253/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6254/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006255/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6256///
6257/// Always returns an RValue with a pointer representation.
6258static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6259 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6260
6261 auto *NoParens = E->IgnoreParens();
6262 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006263 if (Cast == nullptr)
6264 return NoParens;
6265
6266 // We only conservatively allow a few kinds of casts, because this code is
6267 // inherently a simple solution that seeks to support the common case.
6268 auto CastKind = Cast->getCastKind();
6269 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6270 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006271 return NoParens;
6272
6273 auto *SubExpr = Cast->getSubExpr();
6274 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6275 return NoParens;
6276 return ignorePointerCastsAndParens(SubExpr);
6277}
6278
George Burgess IVbdb5b262015-08-19 02:19:07 +00006279bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6280 unsigned Type) {
6281 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006282 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006283 {
6284 // The operand of __builtin_object_size is never evaluated for side-effects.
6285 // If there are any, but we can determine the pointed-to object anyway, then
6286 // ignore the side-effects.
6287 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006288 FoldOffsetRAII Fold(Info, Type & 1);
6289 const Expr *Ptr = ignorePointerCastsAndParens(E->getArg(0));
6290 if (!EvaluatePointer(Ptr, Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006291 return false;
6292 }
John McCall95007602010-05-10 23:27:23 +00006293
George Burgess IVbdb5b262015-08-19 02:19:07 +00006294 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006295 // If we point to before the start of the object, there are no accessible
6296 // bytes.
6297 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006298 return Success(0, E);
6299
George Burgess IV3a03fab2015-09-04 21:28:13 +00006300 // In the case where we're not dealing with a subobject, we discard the
6301 // subobject bit.
6302 if (!Base.Designator.Invalid && Base.Designator.Entries.empty())
6303 Type = Type & ~1U;
6304
6305 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6306 // exist. If we can't verify the base, then we can't do that.
6307 //
6308 // As a special case, we produce a valid object size for an unknown object
6309 // with a known designator if Type & 1 is 1. For instance:
6310 //
6311 // extern struct X { char buff[32]; int a, b, c; } *p;
6312 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6313 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6314 //
6315 // This matches GCC's behavior.
6316 if ((Type & 1) == 0 && Base.InvalidBase)
Nico Weber19999b42015-08-18 20:32:55 +00006317 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006318
6319 // If Type & 1 is 0, the object in question is the complete object; reset to
6320 // a complete object designator in that case.
6321 //
6322 // If Type is 1 and we've lost track of the subobject, just find the complete
6323 // object instead. (If Type is 3, that's not correct behavior and we should
6324 // return 0 instead.)
6325 LValue End = Base;
6326 if (((Type & 1) == 0) || (End.Designator.Invalid && Type == 1)) {
6327 QualType T = getObjectType(End.getLValueBase());
6328 if (T.isNull())
6329 End.Designator.setInvalid();
6330 else {
6331 End.Designator = SubobjectDesignator(T);
6332 End.Offset = CharUnits::Zero();
6333 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006334 }
John McCall95007602010-05-10 23:27:23 +00006335
George Burgess IVbdb5b262015-08-19 02:19:07 +00006336 // If it is not possible to determine which objects ptr points to at compile
6337 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6338 // and (size_t) 0 for type 2 or 3.
6339 if (End.Designator.Invalid)
6340 return false;
6341
6342 // According to the GCC documentation, we want the size of the subobject
6343 // denoted by the pointer. But that's not quite right -- what we actually
6344 // want is the size of the immediately-enclosing array, if there is one.
6345 int64_t AmountToAdd = 1;
6346 if (End.Designator.MostDerivedArraySize &&
6347 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6348 // We got a pointer to an array. Step to its end.
6349 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3a03fab2015-09-04 21:28:13 +00006350 End.Designator.Entries.back().ArrayIndex;
6351 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006352 // We're already pointing at the end of the object.
6353 AmountToAdd = 0;
6354 }
6355
George Burgess IV3a03fab2015-09-04 21:28:13 +00006356 QualType PointeeType = End.Designator.MostDerivedType;
6357 assert(!PointeeType.isNull());
6358 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006359 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006360
George Burgess IVbdb5b262015-08-19 02:19:07 +00006361 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6362 AmountToAdd))
6363 return false;
John McCall95007602010-05-10 23:27:23 +00006364
George Burgess IVbdb5b262015-08-19 02:19:07 +00006365 auto EndOffset = End.getLValueOffset();
6366 if (BaseOffset > EndOffset)
6367 return Success(0, E);
6368
6369 return Success(EndOffset - BaseOffset, E);
John McCall95007602010-05-10 23:27:23 +00006370}
6371
Peter Collingbournee9200682011-05-13 03:29:01 +00006372bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006373 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006374 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006375 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006376
6377 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006378 // The type was checked when we built the expression.
6379 unsigned Type =
6380 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6381 assert(Type <= 3 && "unexpected type");
6382
6383 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006384 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006385
Richard Smith0421ce72012-08-07 04:16:51 +00006386 // If evaluating the argument has side-effects, we can't determine the size
6387 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6388 // handle all cases where the expression has side-effects.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006389 // Likewise, if Type is 3, we must handle this because CodeGen cannot give a
6390 // conservatively correct answer in that case.
6391 if (E->getArg(0)->HasSideEffects(Info.Ctx) || Type == 3)
6392 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006393
Richard Smith01ade172012-05-23 04:13:20 +00006394 // Expression had no side effects, but we couldn't statically determine the
6395 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006396 switch (Info.EvalMode) {
6397 case EvalInfo::EM_ConstantExpression:
6398 case EvalInfo::EM_PotentialConstantExpression:
6399 case EvalInfo::EM_ConstantFold:
6400 case EvalInfo::EM_EvaluateForOverflow:
6401 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006402 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006403 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006404 return Error(E);
6405 case EvalInfo::EM_ConstantExpressionUnevaluated:
6406 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006407 // Reduce it to a constant now.
6408 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006409 }
Mike Stump722cedf2009-10-26 18:35:08 +00006410 }
6411
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006412 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006413 case Builtin::BI__builtin_bswap32:
6414 case Builtin::BI__builtin_bswap64: {
6415 APSInt Val;
6416 if (!EvaluateInteger(E->getArg(0), Val, Info))
6417 return false;
6418
6419 return Success(Val.byteSwap(), E);
6420 }
6421
Richard Smith8889a3d2013-06-13 06:26:32 +00006422 case Builtin::BI__builtin_classify_type:
6423 return Success(EvaluateBuiltinClassifyType(E), E);
6424
6425 // FIXME: BI__builtin_clrsb
6426 // FIXME: BI__builtin_clrsbl
6427 // FIXME: BI__builtin_clrsbll
6428
Richard Smith80b3c8e2013-06-13 05:04:16 +00006429 case Builtin::BI__builtin_clz:
6430 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006431 case Builtin::BI__builtin_clzll:
6432 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006433 APSInt Val;
6434 if (!EvaluateInteger(E->getArg(0), Val, Info))
6435 return false;
6436 if (!Val)
6437 return Error(E);
6438
6439 return Success(Val.countLeadingZeros(), E);
6440 }
6441
Richard Smith8889a3d2013-06-13 06:26:32 +00006442 case Builtin::BI__builtin_constant_p:
6443 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6444
Richard Smith80b3c8e2013-06-13 05:04:16 +00006445 case Builtin::BI__builtin_ctz:
6446 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006447 case Builtin::BI__builtin_ctzll:
6448 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006449 APSInt Val;
6450 if (!EvaluateInteger(E->getArg(0), Val, Info))
6451 return false;
6452 if (!Val)
6453 return Error(E);
6454
6455 return Success(Val.countTrailingZeros(), E);
6456 }
6457
Richard Smith8889a3d2013-06-13 06:26:32 +00006458 case Builtin::BI__builtin_eh_return_data_regno: {
6459 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6460 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6461 return Success(Operand, E);
6462 }
6463
6464 case Builtin::BI__builtin_expect:
6465 return Visit(E->getArg(0));
6466
6467 case Builtin::BI__builtin_ffs:
6468 case Builtin::BI__builtin_ffsl:
6469 case Builtin::BI__builtin_ffsll: {
6470 APSInt Val;
6471 if (!EvaluateInteger(E->getArg(0), Val, Info))
6472 return false;
6473
6474 unsigned N = Val.countTrailingZeros();
6475 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6476 }
6477
6478 case Builtin::BI__builtin_fpclassify: {
6479 APFloat Val(0.0);
6480 if (!EvaluateFloat(E->getArg(5), Val, Info))
6481 return false;
6482 unsigned Arg;
6483 switch (Val.getCategory()) {
6484 case APFloat::fcNaN: Arg = 0; break;
6485 case APFloat::fcInfinity: Arg = 1; break;
6486 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6487 case APFloat::fcZero: Arg = 4; break;
6488 }
6489 return Visit(E->getArg(Arg));
6490 }
6491
6492 case Builtin::BI__builtin_isinf_sign: {
6493 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006494 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006495 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6496 }
6497
Richard Smithea3019d2013-10-15 19:07:14 +00006498 case Builtin::BI__builtin_isinf: {
6499 APFloat Val(0.0);
6500 return EvaluateFloat(E->getArg(0), Val, Info) &&
6501 Success(Val.isInfinity() ? 1 : 0, E);
6502 }
6503
6504 case Builtin::BI__builtin_isfinite: {
6505 APFloat Val(0.0);
6506 return EvaluateFloat(E->getArg(0), Val, Info) &&
6507 Success(Val.isFinite() ? 1 : 0, E);
6508 }
6509
6510 case Builtin::BI__builtin_isnan: {
6511 APFloat Val(0.0);
6512 return EvaluateFloat(E->getArg(0), Val, Info) &&
6513 Success(Val.isNaN() ? 1 : 0, E);
6514 }
6515
6516 case Builtin::BI__builtin_isnormal: {
6517 APFloat Val(0.0);
6518 return EvaluateFloat(E->getArg(0), Val, Info) &&
6519 Success(Val.isNormal() ? 1 : 0, E);
6520 }
6521
Richard Smith8889a3d2013-06-13 06:26:32 +00006522 case Builtin::BI__builtin_parity:
6523 case Builtin::BI__builtin_parityl:
6524 case Builtin::BI__builtin_parityll: {
6525 APSInt Val;
6526 if (!EvaluateInteger(E->getArg(0), Val, Info))
6527 return false;
6528
6529 return Success(Val.countPopulation() % 2, E);
6530 }
6531
Richard Smith80b3c8e2013-06-13 05:04:16 +00006532 case Builtin::BI__builtin_popcount:
6533 case Builtin::BI__builtin_popcountl:
6534 case Builtin::BI__builtin_popcountll: {
6535 APSInt Val;
6536 if (!EvaluateInteger(E->getArg(0), Val, Info))
6537 return false;
6538
6539 return Success(Val.countPopulation(), E);
6540 }
6541
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006542 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006543 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006544 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006545 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006546 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6547 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006548 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006549 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006550 case Builtin::BI__builtin_strlen: {
6551 // As an extension, we support __builtin_strlen() as a constant expression,
6552 // and support folding strlen() to a constant.
6553 LValue String;
6554 if (!EvaluatePointer(E->getArg(0), String, Info))
6555 return false;
6556
6557 // Fast path: if it's a string literal, search the string value.
6558 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6559 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006560 // The string literal may have embedded null characters. Find the first
6561 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006562 StringRef Str = S->getBytes();
6563 int64_t Off = String.Offset.getQuantity();
6564 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6565 S->getCharByteWidth() == 1) {
6566 Str = Str.substr(Off);
6567
6568 StringRef::size_type Pos = Str.find(0);
6569 if (Pos != StringRef::npos)
6570 Str = Str.substr(0, Pos);
6571
6572 return Success(Str.size(), E);
6573 }
6574
6575 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006576 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006577
6578 // Slow path: scan the bytes of the string looking for the terminating 0.
6579 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6580 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6581 APValue Char;
6582 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6583 !Char.isInt())
6584 return false;
6585 if (!Char.getInt())
6586 return Success(Strlen, E);
6587 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6588 return false;
6589 }
6590 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006591
Richard Smith01ba47d2012-04-13 00:45:38 +00006592 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006593 case Builtin::BI__atomic_is_lock_free:
6594 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006595 APSInt SizeVal;
6596 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6597 return false;
6598
6599 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6600 // of two less than the maximum inline atomic width, we know it is
6601 // lock-free. If the size isn't a power of two, or greater than the
6602 // maximum alignment where we promote atomics, we know it is not lock-free
6603 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6604 // the answer can only be determined at runtime; for example, 16-byte
6605 // atomics have lock-free implementations on some, but not all,
6606 // x86-64 processors.
6607
6608 // Check power-of-two.
6609 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006610 if (Size.isPowerOfTwo()) {
6611 // Check against inlining width.
6612 unsigned InlineWidthBits =
6613 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6614 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6615 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6616 Size == CharUnits::One() ||
6617 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6618 Expr::NPC_NeverValueDependent))
6619 // OK, we will inline appropriately-aligned operations of this size,
6620 // and _Atomic(T) is appropriately-aligned.
6621 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006622
Richard Smith01ba47d2012-04-13 00:45:38 +00006623 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6624 castAs<PointerType>()->getPointeeType();
6625 if (!PointeeType->isIncompleteType() &&
6626 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6627 // OK, we will inline operations on this object.
6628 return Success(1, E);
6629 }
6630 }
6631 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006632
Richard Smith01ba47d2012-04-13 00:45:38 +00006633 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6634 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006635 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006636 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006637}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006638
Richard Smith8b3497e2011-10-31 01:37:14 +00006639static bool HasSameBase(const LValue &A, const LValue &B) {
6640 if (!A.getLValueBase())
6641 return !B.getLValueBase();
6642 if (!B.getLValueBase())
6643 return false;
6644
Richard Smithce40ad62011-11-12 22:28:03 +00006645 if (A.getLValueBase().getOpaqueValue() !=
6646 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006647 const Decl *ADecl = GetLValueBaseDecl(A);
6648 if (!ADecl)
6649 return false;
6650 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006651 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006652 return false;
6653 }
6654
6655 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006656 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006657}
6658
Richard Smithd20f1e62014-10-21 23:01:04 +00006659/// \brief Determine whether this is a pointer past the end of the complete
6660/// object referred to by the lvalue.
6661static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6662 const LValue &LV) {
6663 // A null pointer can be viewed as being "past the end" but we don't
6664 // choose to look at it that way here.
6665 if (!LV.getLValueBase())
6666 return false;
6667
6668 // If the designator is valid and refers to a subobject, we're not pointing
6669 // past the end.
6670 if (!LV.getLValueDesignator().Invalid &&
6671 !LV.getLValueDesignator().isOnePastTheEnd())
6672 return false;
6673
David Majnemerc378ca52015-08-29 08:32:55 +00006674 // A pointer to an incomplete type might be past-the-end if the type's size is
6675 // zero. We cannot tell because the type is incomplete.
6676 QualType Ty = getType(LV.getLValueBase());
6677 if (Ty->isIncompleteType())
6678 return true;
6679
Richard Smithd20f1e62014-10-21 23:01:04 +00006680 // We're a past-the-end pointer if we point to the byte after the object,
6681 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00006682 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00006683 return LV.getLValueOffset() == Size;
6684}
6685
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006686namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006687
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006688/// \brief Data recursive integer evaluator of certain binary operators.
6689///
6690/// We use a data recursive algorithm for binary operators so that we are able
6691/// to handle extreme cases of chained binary operators without causing stack
6692/// overflow.
6693class DataRecursiveIntBinOpEvaluator {
6694 struct EvalResult {
6695 APValue Val;
6696 bool Failed;
6697
6698 EvalResult() : Failed(false) { }
6699
6700 void swap(EvalResult &RHS) {
6701 Val.swap(RHS.Val);
6702 Failed = RHS.Failed;
6703 RHS.Failed = false;
6704 }
6705 };
6706
6707 struct Job {
6708 const Expr *E;
6709 EvalResult LHSResult; // meaningful only for binary operator expression.
6710 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006711
David Blaikie73726062015-08-12 23:09:24 +00006712 Job() = default;
6713 Job(Job &&J)
6714 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
6715 StoredInfo(J.StoredInfo), OldEvalStatus(J.OldEvalStatus) {
6716 J.StoredInfo = nullptr;
6717 }
6718
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006719 void startSpeculativeEval(EvalInfo &Info) {
6720 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006721 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006722 StoredInfo = &Info;
6723 }
6724 ~Job() {
6725 if (StoredInfo) {
6726 StoredInfo->EvalStatus = OldEvalStatus;
6727 }
6728 }
6729 private:
David Blaikie73726062015-08-12 23:09:24 +00006730 EvalInfo *StoredInfo = nullptr; // non-null if status changed.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006731 Expr::EvalStatus OldEvalStatus;
6732 };
6733
6734 SmallVector<Job, 16> Queue;
6735
6736 IntExprEvaluator &IntEval;
6737 EvalInfo &Info;
6738 APValue &FinalResult;
6739
6740public:
6741 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6742 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6743
6744 /// \brief True if \param E is a binary operator that we are going to handle
6745 /// data recursively.
6746 /// We handle binary operators that are comma, logical, or that have operands
6747 /// with integral or enumeration type.
6748 static bool shouldEnqueue(const BinaryOperator *E) {
6749 return E->getOpcode() == BO_Comma ||
6750 E->isLogicalOp() ||
6751 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6752 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006753 }
6754
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006755 bool Traverse(const BinaryOperator *E) {
6756 enqueue(E);
6757 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006758 while (!Queue.empty())
6759 process(PrevResult);
6760
6761 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006762
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006763 FinalResult.swap(PrevResult.Val);
6764 return true;
6765 }
6766
6767private:
6768 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6769 return IntEval.Success(Value, E, Result);
6770 }
6771 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6772 return IntEval.Success(Value, E, Result);
6773 }
6774 bool Error(const Expr *E) {
6775 return IntEval.Error(E);
6776 }
6777 bool Error(const Expr *E, diag::kind D) {
6778 return IntEval.Error(E, D);
6779 }
6780
6781 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6782 return Info.CCEDiag(E, D);
6783 }
6784
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006785 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6786 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006787 bool &SuppressRHSDiags);
6788
6789 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6790 const BinaryOperator *E, APValue &Result);
6791
6792 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6793 Result.Failed = !Evaluate(Result.Val, Info, E);
6794 if (Result.Failed)
6795 Result.Val = APValue();
6796 }
6797
Richard Trieuba4d0872012-03-21 23:30:30 +00006798 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006799
6800 void enqueue(const Expr *E) {
6801 E = E->IgnoreParens();
6802 Queue.resize(Queue.size()+1);
6803 Queue.back().E = E;
6804 Queue.back().Kind = Job::AnyExprKind;
6805 }
6806};
6807
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006808}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006809
6810bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006811 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006812 bool &SuppressRHSDiags) {
6813 if (E->getOpcode() == BO_Comma) {
6814 // Ignore LHS but note if we could not evaluate it.
6815 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006816 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006817 return true;
6818 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006819
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006820 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006821 bool LHSAsBool;
6822 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006823 // We were able to evaluate the LHS, see if we can get away with not
6824 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006825 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6826 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006827 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006828 }
6829 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006830 LHSResult.Failed = true;
6831
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006832 // Since we weren't able to evaluate the left hand side, it
6833 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006834 if (!Info.noteSideEffect())
6835 return false;
6836
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006837 // We can't evaluate the LHS; however, sometimes the result
6838 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6839 // Don't ignore RHS and suppress diagnostics from this arm.
6840 SuppressRHSDiags = true;
6841 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006842
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006843 return true;
6844 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006845
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006846 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6847 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006848
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006849 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006850 return false; // Ignore RHS;
6851
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006852 return true;
6853}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006854
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006855bool DataRecursiveIntBinOpEvaluator::
6856 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6857 const BinaryOperator *E, APValue &Result) {
6858 if (E->getOpcode() == BO_Comma) {
6859 if (RHSResult.Failed)
6860 return false;
6861 Result = RHSResult.Val;
6862 return true;
6863 }
6864
6865 if (E->isLogicalOp()) {
6866 bool lhsResult, rhsResult;
6867 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6868 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6869
6870 if (LHSIsOK) {
6871 if (RHSIsOK) {
6872 if (E->getOpcode() == BO_LOr)
6873 return Success(lhsResult || rhsResult, E, Result);
6874 else
6875 return Success(lhsResult && rhsResult, E, Result);
6876 }
6877 } else {
6878 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006879 // We can't evaluate the LHS; however, sometimes the result
6880 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6881 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006882 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006883 }
6884 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006885
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006886 return false;
6887 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006888
6889 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6890 E->getRHS()->getType()->isIntegralOrEnumerationType());
6891
6892 if (LHSResult.Failed || RHSResult.Failed)
6893 return false;
6894
6895 const APValue &LHSVal = LHSResult.Val;
6896 const APValue &RHSVal = RHSResult.Val;
6897
6898 // Handle cases like (unsigned long)&a + 4.
6899 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6900 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006901 CharUnits AdditionalOffset =
6902 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006903 if (E->getOpcode() == BO_Add)
6904 Result.getLValueOffset() += AdditionalOffset;
6905 else
6906 Result.getLValueOffset() -= AdditionalOffset;
6907 return true;
6908 }
6909
6910 // Handle cases like 4 + (unsigned long)&a
6911 if (E->getOpcode() == BO_Add &&
6912 RHSVal.isLValue() && LHSVal.isInt()) {
6913 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006914 Result.getLValueOffset() +=
6915 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006916 return true;
6917 }
6918
6919 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6920 // Handle (intptr_t)&&A - (intptr_t)&&B.
6921 if (!LHSVal.getLValueOffset().isZero() ||
6922 !RHSVal.getLValueOffset().isZero())
6923 return false;
6924 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6925 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6926 if (!LHSExpr || !RHSExpr)
6927 return false;
6928 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6929 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6930 if (!LHSAddrExpr || !RHSAddrExpr)
6931 return false;
6932 // Make sure both labels come from the same function.
6933 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6934 RHSAddrExpr->getLabel()->getDeclContext())
6935 return false;
6936 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6937 return true;
6938 }
Richard Smith43e77732013-05-07 04:50:00 +00006939
6940 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006941 if (!LHSVal.isInt() || !RHSVal.isInt())
6942 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006943
6944 // Set up the width and signedness manually, in case it can't be deduced
6945 // from the operation we're performing.
6946 // FIXME: Don't do this in the cases where we can deduce it.
6947 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6948 E->getType()->isUnsignedIntegerOrEnumerationType());
6949 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6950 RHSVal.getInt(), Value))
6951 return false;
6952 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006953}
6954
Richard Trieuba4d0872012-03-21 23:30:30 +00006955void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006956 Job &job = Queue.back();
6957
6958 switch (job.Kind) {
6959 case Job::AnyExprKind: {
6960 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6961 if (shouldEnqueue(Bop)) {
6962 job.Kind = Job::BinOpKind;
6963 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006964 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006965 }
6966 }
6967
6968 EvaluateExpr(job.E, Result);
6969 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006970 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006971 }
6972
6973 case Job::BinOpKind: {
6974 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006975 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006976 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006977 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006978 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006979 }
6980 if (SuppressRHSDiags)
6981 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006982 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006983 job.Kind = Job::BinOpVisitedLHSKind;
6984 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006985 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006986 }
6987
6988 case Job::BinOpVisitedLHSKind: {
6989 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6990 EvalResult RHS;
6991 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006992 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006993 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006994 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006995 }
6996 }
6997
6998 llvm_unreachable("Invalid Job::Kind!");
6999}
7000
7001bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Josh Magee4d1a79b2015-02-04 21:50:20 +00007002 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007003 return Error(E);
7004
7005 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7006 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007007
Anders Carlssonacc79812008-11-16 07:17:21 +00007008 QualType LHSTy = E->getLHS()->getType();
7009 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007010
Chandler Carruthb29a7432014-10-11 11:03:30 +00007011 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007012 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007013 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007014 if (E->isAssignmentOp()) {
7015 LValue LV;
7016 EvaluateLValue(E->getLHS(), LV, Info);
7017 LHSOK = false;
7018 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007019 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7020 if (LHSOK) {
7021 LHS.makeComplexFloat();
7022 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7023 }
7024 } else {
7025 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7026 }
Richard Smith253c2a32012-01-27 01:14:48 +00007027 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007028 return false;
7029
Chandler Carruthb29a7432014-10-11 11:03:30 +00007030 if (E->getRHS()->getType()->isRealFloatingType()) {
7031 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7032 return false;
7033 RHS.makeComplexFloat();
7034 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7035 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007036 return false;
7037
7038 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007039 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007040 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007041 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007042 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7043
John McCalle3027922010-08-25 11:45:40 +00007044 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007045 return Success((CR_r == APFloat::cmpEqual &&
7046 CR_i == APFloat::cmpEqual), E);
7047 else {
John McCalle3027922010-08-25 11:45:40 +00007048 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007049 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007050 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007051 CR_r == APFloat::cmpLessThan ||
7052 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007053 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007054 CR_i == APFloat::cmpLessThan ||
7055 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007056 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007057 } else {
John McCalle3027922010-08-25 11:45:40 +00007058 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007059 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7060 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7061 else {
John McCalle3027922010-08-25 11:45:40 +00007062 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007063 "Invalid compex comparison.");
7064 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7065 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7066 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007067 }
7068 }
Mike Stump11289f42009-09-09 15:08:12 +00007069
Anders Carlssonacc79812008-11-16 07:17:21 +00007070 if (LHSTy->isRealFloatingType() &&
7071 RHSTy->isRealFloatingType()) {
7072 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007073
Richard Smith253c2a32012-01-27 01:14:48 +00007074 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7075 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007076 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007077
Richard Smith253c2a32012-01-27 01:14:48 +00007078 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007079 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007080
Anders Carlssonacc79812008-11-16 07:17:21 +00007081 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007082
Anders Carlssonacc79812008-11-16 07:17:21 +00007083 switch (E->getOpcode()) {
7084 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007085 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007086 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007087 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007088 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007089 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007090 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007091 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007092 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007093 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007094 E);
John McCalle3027922010-08-25 11:45:40 +00007095 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007096 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007097 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007098 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007099 || CR == APFloat::cmpLessThan
7100 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007101 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007102 }
Mike Stump11289f42009-09-09 15:08:12 +00007103
Eli Friedmana38da572009-04-28 19:17:36 +00007104 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007105 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007106 LValue LHSValue, RHSValue;
7107
7108 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
7109 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007110 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007111
Richard Smith253c2a32012-01-27 01:14:48 +00007112 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007113 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007114
Richard Smith8b3497e2011-10-31 01:37:14 +00007115 // Reject differing bases from the normal codepath; we special-case
7116 // comparisons to null.
7117 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007118 if (E->getOpcode() == BO_Sub) {
7119 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007120 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
7121 return false;
7122 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007123 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007124 if (!LHSExpr || !RHSExpr)
7125 return false;
7126 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7127 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7128 if (!LHSAddrExpr || !RHSAddrExpr)
7129 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007130 // Make sure both labels come from the same function.
7131 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7132 RHSAddrExpr->getLabel()->getDeclContext())
7133 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007134 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007135 return true;
7136 }
Richard Smith83c68212011-10-31 05:11:32 +00007137 // Inequalities and subtractions between unrelated pointers have
7138 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007139 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007140 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007141 // A constant address may compare equal to the address of a symbol.
7142 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007143 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007144 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7145 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007146 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007147 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007148 // distinct addresses. In clang, the result of such a comparison is
7149 // unspecified, so it is not a constant expression. However, we do know
7150 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007151 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7152 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007153 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007154 // We can't tell whether weak symbols will end up pointing to the same
7155 // object.
7156 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007157 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007158 // We can't compare the address of the start of one object with the
7159 // past-the-end address of another object, per C++ DR1652.
7160 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7161 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7162 (RHSValue.Base && RHSValue.Offset.isZero() &&
7163 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7164 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007165 // We can't tell whether an object is at the same address as another
7166 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007167 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7168 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007169 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007170 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007171 // (Note that clang defaults to -fmerge-all-constants, which can
7172 // lead to inconsistent results for comparisons involving the address
7173 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007174 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007175 }
Eli Friedman64004332009-03-23 04:38:34 +00007176
Richard Smith1b470412012-02-01 08:10:20 +00007177 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7178 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7179
Richard Smith84f6dcf2012-02-02 01:16:57 +00007180 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7181 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7182
John McCalle3027922010-08-25 11:45:40 +00007183 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007184 // C++11 [expr.add]p6:
7185 // Unless both pointers point to elements of the same array object, or
7186 // one past the last element of the array object, the behavior is
7187 // undefined.
7188 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7189 !AreElementsOfSameArray(getType(LHSValue.Base),
7190 LHSDesignator, RHSDesignator))
7191 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7192
Chris Lattner882bdf22010-04-20 17:13:14 +00007193 QualType Type = E->getLHS()->getType();
7194 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007195
Richard Smithd62306a2011-11-10 06:34:14 +00007196 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007197 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007198 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007199
Richard Smith84c6b3d2013-09-10 21:34:14 +00007200 // As an extension, a type may have zero size (empty struct or union in
7201 // C, array of zero length). Pointer subtraction in such cases has
7202 // undefined behavior, so is not constant.
7203 if (ElementSize.isZero()) {
7204 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7205 << ElementType;
7206 return false;
7207 }
7208
Richard Smith1b470412012-02-01 08:10:20 +00007209 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7210 // and produce incorrect results when it overflows. Such behavior
7211 // appears to be non-conforming, but is common, so perhaps we should
7212 // assume the standard intended for such cases to be undefined behavior
7213 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007214
Richard Smith1b470412012-02-01 08:10:20 +00007215 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7216 // overflow in the final conversion to ptrdiff_t.
7217 APSInt LHS(
7218 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7219 APSInt RHS(
7220 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7221 APSInt ElemSize(
7222 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7223 APSInt TrueResult = (LHS - RHS) / ElemSize;
7224 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7225
7226 if (Result.extend(65) != TrueResult)
7227 HandleOverflow(Info, E, TrueResult, E->getType());
7228 return Success(Result, E);
7229 }
Richard Smithde21b242012-01-31 06:41:30 +00007230
7231 // C++11 [expr.rel]p3:
7232 // Pointers to void (after pointer conversions) can be compared, with a
7233 // result defined as follows: If both pointers represent the same
7234 // address or are both the null pointer value, the result is true if the
7235 // operator is <= or >= and false otherwise; otherwise the result is
7236 // unspecified.
7237 // We interpret this as applying to pointers to *cv* void.
7238 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007239 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007240 CCEDiag(E, diag::note_constexpr_void_comparison);
7241
Richard Smith84f6dcf2012-02-02 01:16:57 +00007242 // C++11 [expr.rel]p2:
7243 // - If two pointers point to non-static data members of the same object,
7244 // or to subobjects or array elements fo such members, recursively, the
7245 // pointer to the later declared member compares greater provided the
7246 // two members have the same access control and provided their class is
7247 // not a union.
7248 // [...]
7249 // - Otherwise pointer comparisons are unspecified.
7250 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7251 E->isRelationalOp()) {
7252 bool WasArrayIndex;
7253 unsigned Mismatch =
7254 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7255 RHSDesignator, WasArrayIndex);
7256 // At the point where the designators diverge, the comparison has a
7257 // specified value if:
7258 // - we are comparing array indices
7259 // - we are comparing fields of a union, or fields with the same access
7260 // Otherwise, the result is unspecified and thus the comparison is not a
7261 // constant expression.
7262 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7263 Mismatch < RHSDesignator.Entries.size()) {
7264 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7265 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7266 if (!LF && !RF)
7267 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7268 else if (!LF)
7269 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7270 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7271 << RF->getParent() << RF;
7272 else if (!RF)
7273 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7274 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7275 << LF->getParent() << LF;
7276 else if (!LF->getParent()->isUnion() &&
7277 LF->getAccess() != RF->getAccess())
7278 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7279 << LF << LF->getAccess() << RF << RF->getAccess()
7280 << LF->getParent();
7281 }
7282 }
7283
Eli Friedman6c31cb42012-04-16 04:30:08 +00007284 // The comparison here must be unsigned, and performed with the same
7285 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007286 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7287 uint64_t CompareLHS = LHSOffset.getQuantity();
7288 uint64_t CompareRHS = RHSOffset.getQuantity();
7289 assert(PtrSize <= 64 && "Unexpected pointer width");
7290 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7291 CompareLHS &= Mask;
7292 CompareRHS &= Mask;
7293
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007294 // If there is a base and this is a relational operator, we can only
7295 // compare pointers within the object in question; otherwise, the result
7296 // depends on where the object is located in memory.
7297 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7298 QualType BaseTy = getType(LHSValue.Base);
7299 if (BaseTy->isIncompleteType())
7300 return Error(E);
7301 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7302 uint64_t OffsetLimit = Size.getQuantity();
7303 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7304 return Error(E);
7305 }
7306
Richard Smith8b3497e2011-10-31 01:37:14 +00007307 switch (E->getOpcode()) {
7308 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007309 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7310 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7311 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7312 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7313 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7314 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007315 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007316 }
7317 }
Richard Smith7bb00672012-02-01 01:42:44 +00007318
7319 if (LHSTy->isMemberPointerType()) {
7320 assert(E->isEqualityOp() && "unexpected member pointer operation");
7321 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7322
7323 MemberPtr LHSValue, RHSValue;
7324
7325 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7326 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7327 return false;
7328
7329 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7330 return false;
7331
7332 // C++11 [expr.eq]p2:
7333 // If both operands are null, they compare equal. Otherwise if only one is
7334 // null, they compare unequal.
7335 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7336 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7337 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7338 }
7339
7340 // Otherwise if either is a pointer to a virtual member function, the
7341 // result is unspecified.
7342 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7343 if (MD->isVirtual())
7344 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7345 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7346 if (MD->isVirtual())
7347 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7348
7349 // Otherwise they compare equal if and only if they would refer to the
7350 // same member of the same most derived object or the same subobject if
7351 // they were dereferenced with a hypothetical object of the associated
7352 // class type.
7353 bool Equal = LHSValue == RHSValue;
7354 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7355 }
7356
Richard Smithab44d9b2012-02-14 22:35:28 +00007357 if (LHSTy->isNullPtrType()) {
7358 assert(E->isComparisonOp() && "unexpected nullptr operation");
7359 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7360 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7361 // are compared, the result is true of the operator is <=, >= or ==, and
7362 // false otherwise.
7363 BinaryOperator::Opcode Opcode = E->getOpcode();
7364 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7365 }
7366
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007367 assert((!LHSTy->isIntegralOrEnumerationType() ||
7368 !RHSTy->isIntegralOrEnumerationType()) &&
7369 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7370 // We can't continue from here for non-integral types.
7371 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007372}
7373
Peter Collingbournee190dee2011-03-11 19:24:49 +00007374/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7375/// a result as the expression's type.
7376bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7377 const UnaryExprOrTypeTraitExpr *E) {
7378 switch(E->getKind()) {
7379 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007380 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007381 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007382 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007383 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007384 }
Eli Friedman64004332009-03-23 04:38:34 +00007385
Peter Collingbournee190dee2011-03-11 19:24:49 +00007386 case UETT_VecStep: {
7387 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007388
Peter Collingbournee190dee2011-03-11 19:24:49 +00007389 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007390 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007391
Peter Collingbournee190dee2011-03-11 19:24:49 +00007392 // The vec_step built-in functions that take a 3-component
7393 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7394 if (n == 3)
7395 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007396
Peter Collingbournee190dee2011-03-11 19:24:49 +00007397 return Success(n, E);
7398 } else
7399 return Success(1, E);
7400 }
7401
7402 case UETT_SizeOf: {
7403 QualType SrcTy = E->getTypeOfArgument();
7404 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7405 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007406 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7407 SrcTy = Ref->getPointeeType();
7408
Richard Smithd62306a2011-11-10 06:34:14 +00007409 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007410 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007411 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007412 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007413 }
Alexey Bataev00396512015-07-02 03:40:19 +00007414 case UETT_OpenMPRequiredSimdAlign:
7415 assert(E->isArgumentType());
7416 return Success(
7417 Info.Ctx.toCharUnitsFromBits(
7418 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7419 .getQuantity(),
7420 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007421 }
7422
7423 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007424}
7425
Peter Collingbournee9200682011-05-13 03:29:01 +00007426bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007427 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007428 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007429 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007430 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007431 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007432 for (unsigned i = 0; i != n; ++i) {
7433 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7434 switch (ON.getKind()) {
7435 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007436 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007437 APSInt IdxResult;
7438 if (!EvaluateInteger(Idx, IdxResult, Info))
7439 return false;
7440 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7441 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007442 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007443 CurrentType = AT->getElementType();
7444 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7445 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007446 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007447 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007448
Douglas Gregor882211c2010-04-28 22:16:22 +00007449 case OffsetOfExpr::OffsetOfNode::Field: {
7450 FieldDecl *MemberDecl = ON.getField();
7451 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007452 if (!RT)
7453 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007454 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007455 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007456 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007457 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007458 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007459 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007460 CurrentType = MemberDecl->getType().getNonReferenceType();
7461 break;
7462 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007463
Douglas Gregor882211c2010-04-28 22:16:22 +00007464 case OffsetOfExpr::OffsetOfNode::Identifier:
7465 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007466
Douglas Gregord1702062010-04-29 00:18:15 +00007467 case OffsetOfExpr::OffsetOfNode::Base: {
7468 CXXBaseSpecifier *BaseSpec = ON.getBase();
7469 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007470 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007471
7472 // Find the layout of the class whose base we are looking into.
7473 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007474 if (!RT)
7475 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007476 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007477 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007478 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7479
7480 // Find the base class itself.
7481 CurrentType = BaseSpec->getType();
7482 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7483 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007484 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007485
7486 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007487 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007488 break;
7489 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007490 }
7491 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007492 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007493}
7494
Chris Lattnere13042c2008-07-11 19:10:17 +00007495bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007496 switch (E->getOpcode()) {
7497 default:
7498 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7499 // See C99 6.6p3.
7500 return Error(E);
7501 case UO_Extension:
7502 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7503 // If so, we could clear the diagnostic ID.
7504 return Visit(E->getSubExpr());
7505 case UO_Plus:
7506 // The result is just the value.
7507 return Visit(E->getSubExpr());
7508 case UO_Minus: {
7509 if (!Visit(E->getSubExpr()))
7510 return false;
7511 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007512 const APSInt &Value = Result.getInt();
7513 if (Value.isSigned() && Value.isMinSignedValue())
7514 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7515 E->getType());
7516 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007517 }
7518 case UO_Not: {
7519 if (!Visit(E->getSubExpr()))
7520 return false;
7521 if (!Result.isInt()) return Error(E);
7522 return Success(~Result.getInt(), E);
7523 }
7524 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007525 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007526 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007527 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007528 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007529 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007530 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007531}
Mike Stump11289f42009-09-09 15:08:12 +00007532
Chris Lattner477c4be2008-07-12 01:15:53 +00007533/// HandleCast - This is used to evaluate implicit or explicit casts where the
7534/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007535bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7536 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007537 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007538 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007539
Eli Friedmanc757de22011-03-25 00:43:55 +00007540 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007541 case CK_BaseToDerived:
7542 case CK_DerivedToBase:
7543 case CK_UncheckedDerivedToBase:
7544 case CK_Dynamic:
7545 case CK_ToUnion:
7546 case CK_ArrayToPointerDecay:
7547 case CK_FunctionToPointerDecay:
7548 case CK_NullToPointer:
7549 case CK_NullToMemberPointer:
7550 case CK_BaseToDerivedMemberPointer:
7551 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007552 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007553 case CK_ConstructorConversion:
7554 case CK_IntegralToPointer:
7555 case CK_ToVoid:
7556 case CK_VectorSplat:
7557 case CK_IntegralToFloating:
7558 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007559 case CK_CPointerToObjCPointerCast:
7560 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007561 case CK_AnyPointerToBlockPointerCast:
7562 case CK_ObjCObjectLValueCast:
7563 case CK_FloatingRealToComplex:
7564 case CK_FloatingComplexToReal:
7565 case CK_FloatingComplexCast:
7566 case CK_FloatingComplexToIntegralComplex:
7567 case CK_IntegralRealToComplex:
7568 case CK_IntegralComplexCast:
7569 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007570 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007571 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007572 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007573 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007574 llvm_unreachable("invalid cast kind for integral value");
7575
Eli Friedman9faf2f92011-03-25 19:07:11 +00007576 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007577 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007578 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007579 case CK_ARCProduceObject:
7580 case CK_ARCConsumeObject:
7581 case CK_ARCReclaimReturnedObject:
7582 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007583 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007584 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007585
Richard Smith4ef685b2012-01-17 21:17:26 +00007586 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007587 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007588 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007589 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007590 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007591
7592 case CK_MemberPointerToBoolean:
7593 case CK_PointerToBoolean:
7594 case CK_IntegralToBoolean:
7595 case CK_FloatingToBoolean:
7596 case CK_FloatingComplexToBoolean:
7597 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007598 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007599 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007600 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007601 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007602 }
7603
Eli Friedmanc757de22011-03-25 00:43:55 +00007604 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007605 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007606 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007607
Eli Friedman742421e2009-02-20 01:15:07 +00007608 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007609 // Allow casts of address-of-label differences if they are no-ops
7610 // or narrowing. (The narrowing case isn't actually guaranteed to
7611 // be constant-evaluatable except in some narrow cases which are hard
7612 // to detect here. We let it through on the assumption the user knows
7613 // what they are doing.)
7614 if (Result.isAddrLabelDiff())
7615 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007616 // Only allow casts of lvalues if they are lossless.
7617 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7618 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007619
Richard Smith911e1422012-01-30 22:27:01 +00007620 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7621 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007622 }
Mike Stump11289f42009-09-09 15:08:12 +00007623
Eli Friedmanc757de22011-03-25 00:43:55 +00007624 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007625 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7626
John McCall45d55e42010-05-07 21:00:08 +00007627 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007628 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007629 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007630
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007631 if (LV.getLValueBase()) {
7632 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007633 // FIXME: Allow a larger integer size than the pointer size, and allow
7634 // narrowing back down to pointer width in subsequent integral casts.
7635 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007636 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007637 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007638
Richard Smithcf74da72011-11-16 07:18:12 +00007639 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007640 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007641 return true;
7642 }
7643
Ken Dyck02990832010-01-15 12:37:54 +00007644 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7645 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007646 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007647 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007648
Eli Friedmanc757de22011-03-25 00:43:55 +00007649 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007650 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007651 if (!EvaluateComplex(SubExpr, C, Info))
7652 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007653 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007654 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007655
Eli Friedmanc757de22011-03-25 00:43:55 +00007656 case CK_FloatingToIntegral: {
7657 APFloat F(0.0);
7658 if (!EvaluateFloat(SubExpr, F, Info))
7659 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007660
Richard Smith357362d2011-12-13 06:39:58 +00007661 APSInt Value;
7662 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7663 return false;
7664 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007665 }
7666 }
Mike Stump11289f42009-09-09 15:08:12 +00007667
Eli Friedmanc757de22011-03-25 00:43:55 +00007668 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007669}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007670
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007671bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7672 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007673 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007674 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7675 return false;
7676 if (!LV.isComplexInt())
7677 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007678 return Success(LV.getComplexIntReal(), E);
7679 }
7680
7681 return Visit(E->getSubExpr());
7682}
7683
Eli Friedman4e7a2412009-02-27 04:45:43 +00007684bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007685 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007686 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007687 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7688 return false;
7689 if (!LV.isComplexInt())
7690 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007691 return Success(LV.getComplexIntImag(), E);
7692 }
7693
Richard Smith4a678122011-10-24 18:44:57 +00007694 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007695 return Success(0, E);
7696}
7697
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007698bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7699 return Success(E->getPackLength(), E);
7700}
7701
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007702bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7703 return Success(E->getValue(), E);
7704}
7705
Chris Lattner05706e882008-07-11 18:11:29 +00007706//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007707// Float Evaluation
7708//===----------------------------------------------------------------------===//
7709
7710namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007711class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007712 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007713 APFloat &Result;
7714public:
7715 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007716 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007717
Richard Smith2e312c82012-03-03 22:46:17 +00007718 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007719 Result = V.getFloat();
7720 return true;
7721 }
Eli Friedman24c01542008-08-22 00:06:13 +00007722
Richard Smithfddd3842011-12-30 21:15:51 +00007723 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007724 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7725 return true;
7726 }
7727
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007728 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007729
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007730 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007731 bool VisitBinaryOperator(const BinaryOperator *E);
7732 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007733 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007734
John McCallb1fb0d32010-05-07 22:08:54 +00007735 bool VisitUnaryReal(const UnaryOperator *E);
7736 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007737
Richard Smithfddd3842011-12-30 21:15:51 +00007738 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007739};
7740} // end anonymous namespace
7741
7742static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007743 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007744 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007745}
7746
Jay Foad39c79802011-01-12 09:06:06 +00007747static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007748 QualType ResultTy,
7749 const Expr *Arg,
7750 bool SNaN,
7751 llvm::APFloat &Result) {
7752 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7753 if (!S) return false;
7754
7755 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7756
7757 llvm::APInt fill;
7758
7759 // Treat empty strings as if they were zero.
7760 if (S->getString().empty())
7761 fill = llvm::APInt(32, 0);
7762 else if (S->getString().getAsInteger(0, fill))
7763 return false;
7764
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00007765 if (Context.getTargetInfo().isNan2008()) {
7766 if (SNaN)
7767 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7768 else
7769 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7770 } else {
7771 // Prior to IEEE 754-2008, architectures were allowed to choose whether
7772 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7773 // a different encoding to what became a standard in 2008, and for pre-
7774 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7775 // sNaN. This is now known as "legacy NaN" encoding.
7776 if (SNaN)
7777 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7778 else
7779 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7780 }
7781
John McCall16291492010-02-28 13:00:19 +00007782 return true;
7783}
7784
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007785bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007786 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007787 default:
7788 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7789
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007790 case Builtin::BI__builtin_huge_val:
7791 case Builtin::BI__builtin_huge_valf:
7792 case Builtin::BI__builtin_huge_vall:
7793 case Builtin::BI__builtin_inf:
7794 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007795 case Builtin::BI__builtin_infl: {
7796 const llvm::fltSemantics &Sem =
7797 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007798 Result = llvm::APFloat::getInf(Sem);
7799 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007800 }
Mike Stump11289f42009-09-09 15:08:12 +00007801
John McCall16291492010-02-28 13:00:19 +00007802 case Builtin::BI__builtin_nans:
7803 case Builtin::BI__builtin_nansf:
7804 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007805 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7806 true, Result))
7807 return Error(E);
7808 return true;
John McCall16291492010-02-28 13:00:19 +00007809
Chris Lattner0b7282e2008-10-06 06:31:58 +00007810 case Builtin::BI__builtin_nan:
7811 case Builtin::BI__builtin_nanf:
7812 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007813 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007814 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007815 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7816 false, Result))
7817 return Error(E);
7818 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007819
7820 case Builtin::BI__builtin_fabs:
7821 case Builtin::BI__builtin_fabsf:
7822 case Builtin::BI__builtin_fabsl:
7823 if (!EvaluateFloat(E->getArg(0), Result, Info))
7824 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007825
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007826 if (Result.isNegative())
7827 Result.changeSign();
7828 return true;
7829
Richard Smith8889a3d2013-06-13 06:26:32 +00007830 // FIXME: Builtin::BI__builtin_powi
7831 // FIXME: Builtin::BI__builtin_powif
7832 // FIXME: Builtin::BI__builtin_powil
7833
Mike Stump11289f42009-09-09 15:08:12 +00007834 case Builtin::BI__builtin_copysign:
7835 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007836 case Builtin::BI__builtin_copysignl: {
7837 APFloat RHS(0.);
7838 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7839 !EvaluateFloat(E->getArg(1), RHS, Info))
7840 return false;
7841 Result.copySign(RHS);
7842 return true;
7843 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007844 }
7845}
7846
John McCallb1fb0d32010-05-07 22:08:54 +00007847bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007848 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7849 ComplexValue CV;
7850 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7851 return false;
7852 Result = CV.FloatReal;
7853 return true;
7854 }
7855
7856 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007857}
7858
7859bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007860 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7861 ComplexValue CV;
7862 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7863 return false;
7864 Result = CV.FloatImag;
7865 return true;
7866 }
7867
Richard Smith4a678122011-10-24 18:44:57 +00007868 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007869 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7870 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007871 return true;
7872}
7873
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007874bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007875 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007876 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007877 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007878 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007879 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007880 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7881 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007882 Result.changeSign();
7883 return true;
7884 }
7885}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007886
Eli Friedman24c01542008-08-22 00:06:13 +00007887bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007888 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7889 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007890
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007891 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007892 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7893 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007894 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007895 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7896 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007897}
7898
7899bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7900 Result = E->getValue();
7901 return true;
7902}
7903
Peter Collingbournee9200682011-05-13 03:29:01 +00007904bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7905 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007906
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007907 switch (E->getCastKind()) {
7908 default:
Richard Smith11562c52011-10-28 17:51:58 +00007909 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007910
7911 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007912 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007913 return EvaluateInteger(SubExpr, IntResult, Info) &&
7914 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7915 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007916 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007917
7918 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007919 if (!Visit(SubExpr))
7920 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007921 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7922 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007923 }
John McCalld7646252010-11-14 08:17:51 +00007924
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007925 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007926 ComplexValue V;
7927 if (!EvaluateComplex(SubExpr, V, Info))
7928 return false;
7929 Result = V.getComplexFloatReal();
7930 return true;
7931 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007932 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007933}
7934
Eli Friedman24c01542008-08-22 00:06:13 +00007935//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007936// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007937//===----------------------------------------------------------------------===//
7938
7939namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007940class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007941 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007942 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007943
Anders Carlsson537969c2008-11-16 20:27:53 +00007944public:
John McCall93d91dc2010-05-07 17:22:02 +00007945 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007946 : ExprEvaluatorBaseTy(info), Result(Result) {}
7947
Richard Smith2e312c82012-03-03 22:46:17 +00007948 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007949 Result.setFrom(V);
7950 return true;
7951 }
Mike Stump11289f42009-09-09 15:08:12 +00007952
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007953 bool ZeroInitialization(const Expr *E);
7954
Anders Carlsson537969c2008-11-16 20:27:53 +00007955 //===--------------------------------------------------------------------===//
7956 // Visitor Methods
7957 //===--------------------------------------------------------------------===//
7958
Peter Collingbournee9200682011-05-13 03:29:01 +00007959 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007960 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007961 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007962 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007963 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007964};
7965} // end anonymous namespace
7966
John McCall93d91dc2010-05-07 17:22:02 +00007967static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7968 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007969 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007970 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007971}
7972
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007973bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007974 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007975 if (ElemTy->isRealFloatingType()) {
7976 Result.makeComplexFloat();
7977 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7978 Result.FloatReal = Zero;
7979 Result.FloatImag = Zero;
7980 } else {
7981 Result.makeComplexInt();
7982 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7983 Result.IntReal = Zero;
7984 Result.IntImag = Zero;
7985 }
7986 return true;
7987}
7988
Peter Collingbournee9200682011-05-13 03:29:01 +00007989bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7990 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007991
7992 if (SubExpr->getType()->isRealFloatingType()) {
7993 Result.makeComplexFloat();
7994 APFloat &Imag = Result.FloatImag;
7995 if (!EvaluateFloat(SubExpr, Imag, Info))
7996 return false;
7997
7998 Result.FloatReal = APFloat(Imag.getSemantics());
7999 return true;
8000 } else {
8001 assert(SubExpr->getType()->isIntegerType() &&
8002 "Unexpected imaginary literal.");
8003
8004 Result.makeComplexInt();
8005 APSInt &Imag = Result.IntImag;
8006 if (!EvaluateInteger(SubExpr, Imag, Info))
8007 return false;
8008
8009 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8010 return true;
8011 }
8012}
8013
Peter Collingbournee9200682011-05-13 03:29:01 +00008014bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008015
John McCallfcef3cf2010-12-14 17:51:41 +00008016 switch (E->getCastKind()) {
8017 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008018 case CK_BaseToDerived:
8019 case CK_DerivedToBase:
8020 case CK_UncheckedDerivedToBase:
8021 case CK_Dynamic:
8022 case CK_ToUnion:
8023 case CK_ArrayToPointerDecay:
8024 case CK_FunctionToPointerDecay:
8025 case CK_NullToPointer:
8026 case CK_NullToMemberPointer:
8027 case CK_BaseToDerivedMemberPointer:
8028 case CK_DerivedToBaseMemberPointer:
8029 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008030 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008031 case CK_ConstructorConversion:
8032 case CK_IntegralToPointer:
8033 case CK_PointerToIntegral:
8034 case CK_PointerToBoolean:
8035 case CK_ToVoid:
8036 case CK_VectorSplat:
8037 case CK_IntegralCast:
8038 case CK_IntegralToBoolean:
8039 case CK_IntegralToFloating:
8040 case CK_FloatingToIntegral:
8041 case CK_FloatingToBoolean:
8042 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008043 case CK_CPointerToObjCPointerCast:
8044 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008045 case CK_AnyPointerToBlockPointerCast:
8046 case CK_ObjCObjectLValueCast:
8047 case CK_FloatingComplexToReal:
8048 case CK_FloatingComplexToBoolean:
8049 case CK_IntegralComplexToReal:
8050 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008051 case CK_ARCProduceObject:
8052 case CK_ARCConsumeObject:
8053 case CK_ARCReclaimReturnedObject:
8054 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008055 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008056 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008057 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008058 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008059 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008060 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008061
John McCallfcef3cf2010-12-14 17:51:41 +00008062 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008063 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008064 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008065 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008066
8067 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008068 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008069 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008070 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008071
8072 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008073 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008074 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008075 return false;
8076
John McCallfcef3cf2010-12-14 17:51:41 +00008077 Result.makeComplexFloat();
8078 Result.FloatImag = APFloat(Real.getSemantics());
8079 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008080 }
8081
John McCallfcef3cf2010-12-14 17:51:41 +00008082 case CK_FloatingComplexCast: {
8083 if (!Visit(E->getSubExpr()))
8084 return false;
8085
8086 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8087 QualType From
8088 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8089
Richard Smith357362d2011-12-13 06:39:58 +00008090 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8091 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008092 }
8093
8094 case CK_FloatingComplexToIntegralComplex: {
8095 if (!Visit(E->getSubExpr()))
8096 return false;
8097
8098 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8099 QualType From
8100 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8101 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008102 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8103 To, Result.IntReal) &&
8104 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8105 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008106 }
8107
8108 case CK_IntegralRealToComplex: {
8109 APSInt &Real = Result.IntReal;
8110 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8111 return false;
8112
8113 Result.makeComplexInt();
8114 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8115 return true;
8116 }
8117
8118 case CK_IntegralComplexCast: {
8119 if (!Visit(E->getSubExpr()))
8120 return false;
8121
8122 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8123 QualType From
8124 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8125
Richard Smith911e1422012-01-30 22:27:01 +00008126 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8127 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008128 return true;
8129 }
8130
8131 case CK_IntegralComplexToFloatingComplex: {
8132 if (!Visit(E->getSubExpr()))
8133 return false;
8134
Ted Kremenek28831752012-08-23 20:46:57 +00008135 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008136 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008137 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008138 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008139 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8140 To, Result.FloatReal) &&
8141 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8142 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008143 }
8144 }
8145
8146 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008147}
8148
John McCall93d91dc2010-05-07 17:22:02 +00008149bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008150 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008151 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8152
Chandler Carrutha216cad2014-10-11 00:57:18 +00008153 // Track whether the LHS or RHS is real at the type system level. When this is
8154 // the case we can simplify our evaluation strategy.
8155 bool LHSReal = false, RHSReal = false;
8156
8157 bool LHSOK;
8158 if (E->getLHS()->getType()->isRealFloatingType()) {
8159 LHSReal = true;
8160 APFloat &Real = Result.FloatReal;
8161 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8162 if (LHSOK) {
8163 Result.makeComplexFloat();
8164 Result.FloatImag = APFloat(Real.getSemantics());
8165 }
8166 } else {
8167 LHSOK = Visit(E->getLHS());
8168 }
Richard Smith253c2a32012-01-27 01:14:48 +00008169 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008170 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008171
John McCall93d91dc2010-05-07 17:22:02 +00008172 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008173 if (E->getRHS()->getType()->isRealFloatingType()) {
8174 RHSReal = true;
8175 APFloat &Real = RHS.FloatReal;
8176 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8177 return false;
8178 RHS.makeComplexFloat();
8179 RHS.FloatImag = APFloat(Real.getSemantics());
8180 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008181 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008182
Chandler Carrutha216cad2014-10-11 00:57:18 +00008183 assert(!(LHSReal && RHSReal) &&
8184 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008185 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008186 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008187 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008188 if (Result.isComplexFloat()) {
8189 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8190 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008191 if (LHSReal)
8192 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8193 else if (!RHSReal)
8194 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8195 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008196 } else {
8197 Result.getComplexIntReal() += RHS.getComplexIntReal();
8198 Result.getComplexIntImag() += RHS.getComplexIntImag();
8199 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008200 break;
John McCalle3027922010-08-25 11:45:40 +00008201 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008202 if (Result.isComplexFloat()) {
8203 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8204 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008205 if (LHSReal) {
8206 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8207 Result.getComplexFloatImag().changeSign();
8208 } else if (!RHSReal) {
8209 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8210 APFloat::rmNearestTiesToEven);
8211 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008212 } else {
8213 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8214 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8215 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008216 break;
John McCalle3027922010-08-25 11:45:40 +00008217 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008218 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008219 // This is an implementation of complex multiplication according to the
8220 // constraints laid out in C11 Annex G. The implemantion uses the
8221 // following naming scheme:
8222 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008223 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008224 APFloat &A = LHS.getComplexFloatReal();
8225 APFloat &B = LHS.getComplexFloatImag();
8226 APFloat &C = RHS.getComplexFloatReal();
8227 APFloat &D = RHS.getComplexFloatImag();
8228 APFloat &ResR = Result.getComplexFloatReal();
8229 APFloat &ResI = Result.getComplexFloatImag();
8230 if (LHSReal) {
8231 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8232 ResR = A * C;
8233 ResI = A * D;
8234 } else if (RHSReal) {
8235 ResR = C * A;
8236 ResI = C * B;
8237 } else {
8238 // In the fully general case, we need to handle NaNs and infinities
8239 // robustly.
8240 APFloat AC = A * C;
8241 APFloat BD = B * D;
8242 APFloat AD = A * D;
8243 APFloat BC = B * C;
8244 ResR = AC - BD;
8245 ResI = AD + BC;
8246 if (ResR.isNaN() && ResI.isNaN()) {
8247 bool Recalc = false;
8248 if (A.isInfinity() || B.isInfinity()) {
8249 A = APFloat::copySign(
8250 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8251 B = APFloat::copySign(
8252 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8253 if (C.isNaN())
8254 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8255 if (D.isNaN())
8256 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8257 Recalc = true;
8258 }
8259 if (C.isInfinity() || D.isInfinity()) {
8260 C = APFloat::copySign(
8261 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8262 D = APFloat::copySign(
8263 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8264 if (A.isNaN())
8265 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8266 if (B.isNaN())
8267 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8268 Recalc = true;
8269 }
8270 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8271 AD.isInfinity() || BC.isInfinity())) {
8272 if (A.isNaN())
8273 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8274 if (B.isNaN())
8275 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8276 if (C.isNaN())
8277 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8278 if (D.isNaN())
8279 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8280 Recalc = true;
8281 }
8282 if (Recalc) {
8283 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8284 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8285 }
8286 }
8287 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008288 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008289 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008290 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008291 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8292 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008293 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008294 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8295 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8296 }
8297 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008298 case BO_Div:
8299 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008300 // This is an implementation of complex division according to the
8301 // constraints laid out in C11 Annex G. The implemantion uses the
8302 // following naming scheme:
8303 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008304 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008305 APFloat &A = LHS.getComplexFloatReal();
8306 APFloat &B = LHS.getComplexFloatImag();
8307 APFloat &C = RHS.getComplexFloatReal();
8308 APFloat &D = RHS.getComplexFloatImag();
8309 APFloat &ResR = Result.getComplexFloatReal();
8310 APFloat &ResI = Result.getComplexFloatImag();
8311 if (RHSReal) {
8312 ResR = A / C;
8313 ResI = B / C;
8314 } else {
8315 if (LHSReal) {
8316 // No real optimizations we can do here, stub out with zero.
8317 B = APFloat::getZero(A.getSemantics());
8318 }
8319 int DenomLogB = 0;
8320 APFloat MaxCD = maxnum(abs(C), abs(D));
8321 if (MaxCD.isFinite()) {
8322 DenomLogB = ilogb(MaxCD);
8323 C = scalbn(C, -DenomLogB);
8324 D = scalbn(D, -DenomLogB);
8325 }
8326 APFloat Denom = C * C + D * D;
8327 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8328 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8329 if (ResR.isNaN() && ResI.isNaN()) {
8330 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8331 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8332 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8333 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8334 D.isFinite()) {
8335 A = APFloat::copySign(
8336 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8337 B = APFloat::copySign(
8338 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8339 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8340 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8341 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8342 C = APFloat::copySign(
8343 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8344 D = APFloat::copySign(
8345 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8346 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8347 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8348 }
8349 }
8350 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008351 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008352 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8353 return Error(E, diag::note_expr_divide_by_zero);
8354
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008355 ComplexValue LHS = Result;
8356 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8357 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8358 Result.getComplexIntReal() =
8359 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8360 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8361 Result.getComplexIntImag() =
8362 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8363 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8364 }
8365 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008366 }
8367
John McCall93d91dc2010-05-07 17:22:02 +00008368 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008369}
8370
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008371bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8372 // Get the operand value into 'Result'.
8373 if (!Visit(E->getSubExpr()))
8374 return false;
8375
8376 switch (E->getOpcode()) {
8377 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008378 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008379 case UO_Extension:
8380 return true;
8381 case UO_Plus:
8382 // The result is always just the subexpr.
8383 return true;
8384 case UO_Minus:
8385 if (Result.isComplexFloat()) {
8386 Result.getComplexFloatReal().changeSign();
8387 Result.getComplexFloatImag().changeSign();
8388 }
8389 else {
8390 Result.getComplexIntReal() = -Result.getComplexIntReal();
8391 Result.getComplexIntImag() = -Result.getComplexIntImag();
8392 }
8393 return true;
8394 case UO_Not:
8395 if (Result.isComplexFloat())
8396 Result.getComplexFloatImag().changeSign();
8397 else
8398 Result.getComplexIntImag() = -Result.getComplexIntImag();
8399 return true;
8400 }
8401}
8402
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008403bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8404 if (E->getNumInits() == 2) {
8405 if (E->getType()->isComplexType()) {
8406 Result.makeComplexFloat();
8407 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8408 return false;
8409 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8410 return false;
8411 } else {
8412 Result.makeComplexInt();
8413 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8414 return false;
8415 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8416 return false;
8417 }
8418 return true;
8419 }
8420 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8421}
8422
Anders Carlsson537969c2008-11-16 20:27:53 +00008423//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008424// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8425// implicit conversion.
8426//===----------------------------------------------------------------------===//
8427
8428namespace {
8429class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008430 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008431 APValue &Result;
8432public:
8433 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8434 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8435
8436 bool Success(const APValue &V, const Expr *E) {
8437 Result = V;
8438 return true;
8439 }
8440
8441 bool ZeroInitialization(const Expr *E) {
8442 ImplicitValueInitExpr VIE(
8443 E->getType()->castAs<AtomicType>()->getValueType());
8444 return Evaluate(Result, Info, &VIE);
8445 }
8446
8447 bool VisitCastExpr(const CastExpr *E) {
8448 switch (E->getCastKind()) {
8449 default:
8450 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8451 case CK_NonAtomicToAtomic:
8452 return Evaluate(Result, Info, E->getSubExpr());
8453 }
8454 }
8455};
8456} // end anonymous namespace
8457
8458static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8459 assert(E->isRValue() && E->getType()->isAtomicType());
8460 return AtomicExprEvaluator(Info, Result).Visit(E);
8461}
8462
8463//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008464// Void expression evaluation, primarily for a cast to void on the LHS of a
8465// comma operator
8466//===----------------------------------------------------------------------===//
8467
8468namespace {
8469class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008470 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008471public:
8472 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8473
Richard Smith2e312c82012-03-03 22:46:17 +00008474 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008475
8476 bool VisitCastExpr(const CastExpr *E) {
8477 switch (E->getCastKind()) {
8478 default:
8479 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8480 case CK_ToVoid:
8481 VisitIgnoredValue(E->getSubExpr());
8482 return true;
8483 }
8484 }
Hal Finkela8443c32014-07-17 14:49:58 +00008485
8486 bool VisitCallExpr(const CallExpr *E) {
8487 switch (E->getBuiltinCallee()) {
8488 default:
8489 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8490 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008491 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008492 // The argument is not evaluated!
8493 return true;
8494 }
8495 }
Richard Smith42d3af92011-12-07 00:43:50 +00008496};
8497} // end anonymous namespace
8498
8499static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8500 assert(E->isRValue() && E->getType()->isVoidType());
8501 return VoidExprEvaluator(Info).Visit(E);
8502}
8503
8504//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008505// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008506//===----------------------------------------------------------------------===//
8507
Richard Smith2e312c82012-03-03 22:46:17 +00008508static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008509 // In C, function designators are not lvalues, but we evaluate them as if they
8510 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008511 QualType T = E->getType();
8512 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008513 LValue LV;
8514 if (!EvaluateLValue(E, LV, Info))
8515 return false;
8516 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008517 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008518 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008519 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008520 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008521 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008522 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008523 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008524 LValue LV;
8525 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008526 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008527 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008528 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008529 llvm::APFloat F(0.0);
8530 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008531 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008532 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008533 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008534 ComplexValue C;
8535 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008536 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008537 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008538 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008539 MemberPtr P;
8540 if (!EvaluateMemberPointer(E, P, Info))
8541 return false;
8542 P.moveInto(Result);
8543 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008544 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008545 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008546 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008547 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8548 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008549 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008550 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008551 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008552 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008553 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008554 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8555 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008556 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008557 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008558 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008559 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008560 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008561 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008562 if (!EvaluateVoid(E, Info))
8563 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008564 } else if (T->isAtomicType()) {
8565 if (!EvaluateAtomic(E, Result, Info))
8566 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008567 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008568 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008569 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008570 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008571 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008572 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008573 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008574
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008575 return true;
8576}
8577
Richard Smithb228a862012-02-15 02:18:13 +00008578/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8579/// cases, the in-place evaluation is essential, since later initializers for
8580/// an object can indirectly refer to subobjects which were initialized earlier.
8581static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008582 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008583 assert(!E->isValueDependent());
8584
Richard Smith7525ff62013-05-09 07:14:00 +00008585 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008586 return false;
8587
8588 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008589 // Evaluate arrays and record types in-place, so that later initializers can
8590 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008591 if (E->getType()->isArrayType())
8592 return EvaluateArray(E, This, Result, Info);
8593 else if (E->getType()->isRecordType())
8594 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008595 }
8596
8597 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008598 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008599}
8600
Richard Smithf57d8cb2011-12-09 22:58:01 +00008601/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8602/// lvalue-to-rvalue cast if it is an lvalue.
8603static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008604 if (E->getType().isNull())
8605 return false;
8606
Richard Smithfddd3842011-12-30 21:15:51 +00008607 if (!CheckLiteralType(Info, E))
8608 return false;
8609
Richard Smith2e312c82012-03-03 22:46:17 +00008610 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008611 return false;
8612
8613 if (E->isGLValue()) {
8614 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008615 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008616 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008617 return false;
8618 }
8619
Richard Smith2e312c82012-03-03 22:46:17 +00008620 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008621 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008622}
Richard Smith11562c52011-10-28 17:51:58 +00008623
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008624static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8625 const ASTContext &Ctx, bool &IsConst) {
8626 // Fast-path evaluations of integer literals, since we sometimes see files
8627 // containing vast quantities of these.
8628 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8629 Result.Val = APValue(APSInt(L->getValue(),
8630 L->getType()->isUnsignedIntegerType()));
8631 IsConst = true;
8632 return true;
8633 }
James Dennett0492ef02014-03-14 17:44:10 +00008634
8635 // This case should be rare, but we need to check it before we check on
8636 // the type below.
8637 if (Exp->getType().isNull()) {
8638 IsConst = false;
8639 return true;
8640 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008641
8642 // FIXME: Evaluating values of large array and record types can cause
8643 // performance problems. Only do so in C++11 for now.
8644 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8645 Exp->getType()->isRecordType()) &&
8646 !Ctx.getLangOpts().CPlusPlus11) {
8647 IsConst = false;
8648 return true;
8649 }
8650 return false;
8651}
8652
8653
Richard Smith7b553f12011-10-29 00:50:52 +00008654/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008655/// any crazy technique (that has nothing to do with language standards) that
8656/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008657/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8658/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008659bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008660 bool IsConst;
8661 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8662 return IsConst;
8663
Richard Smith6d4c6582013-11-05 22:18:15 +00008664 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008665 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008666}
8667
Jay Foad39c79802011-01-12 09:06:06 +00008668bool Expr::EvaluateAsBooleanCondition(bool &Result,
8669 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008670 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008671 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008672 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008673}
8674
Richard Smith5fab0c92011-12-28 19:48:30 +00008675bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8676 SideEffectsKind AllowSideEffects) const {
8677 if (!getType()->isIntegralOrEnumerationType())
8678 return false;
8679
Richard Smith11562c52011-10-28 17:51:58 +00008680 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008681 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8682 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008683 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008684
Richard Smith11562c52011-10-28 17:51:58 +00008685 Result = ExprResult.Val.getInt();
8686 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008687}
8688
Jay Foad39c79802011-01-12 09:06:06 +00008689bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008690 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008691
John McCall45d55e42010-05-07 21:00:08 +00008692 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008693 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8694 !CheckLValueConstantExpression(Info, getExprLoc(),
8695 Ctx.getLValueReferenceType(getType()), LV))
8696 return false;
8697
Richard Smith2e312c82012-03-03 22:46:17 +00008698 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008699 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008700}
8701
Richard Smithd0b4dd62011-12-19 06:19:21 +00008702bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8703 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008704 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008705 // FIXME: Evaluating initializers for large array and record types can cause
8706 // performance problems. Only do so in C++11 for now.
8707 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008708 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008709 return false;
8710
Richard Smithd0b4dd62011-12-19 06:19:21 +00008711 Expr::EvalStatus EStatus;
8712 EStatus.Diag = &Notes;
8713
Richard Smith6d4c6582013-11-05 22:18:15 +00008714 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008715 InitInfo.setEvaluatingDecl(VD, Value);
8716
8717 LValue LVal;
8718 LVal.set(VD);
8719
Richard Smithfddd3842011-12-30 21:15:51 +00008720 // C++11 [basic.start.init]p2:
8721 // Variables with static storage duration or thread storage duration shall be
8722 // zero-initialized before any other initialization takes place.
8723 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008724 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008725 !VD->getType()->isReferenceType()) {
8726 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008727 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008728 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008729 return false;
8730 }
8731
Richard Smith7525ff62013-05-09 07:14:00 +00008732 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8733 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008734 EStatus.HasSideEffects)
8735 return false;
8736
8737 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8738 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008739}
8740
Richard Smith7b553f12011-10-29 00:50:52 +00008741/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8742/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008743bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008744 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008745 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008746}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008747
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008748APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008749 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008750 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008751 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008752 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008753 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008754 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008755 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008756
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008757 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008758}
John McCall864e3962010-05-07 05:32:02 +00008759
Richard Smithe9ff7702013-11-05 22:23:30 +00008760void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008761 bool IsConst;
8762 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008763 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008764 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008765 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8766 }
8767}
8768
Richard Smithe6c01442013-06-05 00:46:14 +00008769bool Expr::EvalResult::isGlobalLValue() const {
8770 assert(Val.isLValue());
8771 return IsGlobalLValue(Val.getLValueBase());
8772}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008773
8774
John McCall864e3962010-05-07 05:32:02 +00008775/// isIntegerConstantExpr - this recursive routine will test if an expression is
8776/// an integer constant expression.
8777
8778/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8779/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008780
8781// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008782// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8783// and a (possibly null) SourceLocation indicating the location of the problem.
8784//
John McCall864e3962010-05-07 05:32:02 +00008785// Note that to reduce code duplication, this helper does no evaluation
8786// itself; the caller checks whether the expression is evaluatable, and
8787// in the rare cases where CheckICE actually cares about the evaluated
8788// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008789
Dan Gohman28ade552010-07-26 21:25:24 +00008790namespace {
8791
Richard Smith9e575da2012-12-28 13:25:52 +00008792enum ICEKind {
8793 /// This expression is an ICE.
8794 IK_ICE,
8795 /// This expression is not an ICE, but if it isn't evaluated, it's
8796 /// a legal subexpression for an ICE. This return value is used to handle
8797 /// the comma operator in C99 mode, and non-constant subexpressions.
8798 IK_ICEIfUnevaluated,
8799 /// This expression is not an ICE, and is not a legal subexpression for one.
8800 IK_NotICE
8801};
8802
John McCall864e3962010-05-07 05:32:02 +00008803struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008804 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008805 SourceLocation Loc;
8806
Richard Smith9e575da2012-12-28 13:25:52 +00008807 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008808};
8809
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008810}
Dan Gohman28ade552010-07-26 21:25:24 +00008811
Richard Smith9e575da2012-12-28 13:25:52 +00008812static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8813
8814static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008815
Craig Toppera31a8822013-08-22 07:09:37 +00008816static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008817 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008818 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008819 !EVResult.Val.isInt())
8820 return ICEDiag(IK_NotICE, E->getLocStart());
8821
John McCall864e3962010-05-07 05:32:02 +00008822 return NoDiag();
8823}
8824
Craig Toppera31a8822013-08-22 07:09:37 +00008825static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008826 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008827 if (!E->getType()->isIntegralOrEnumerationType())
8828 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008829
8830 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008831#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008832#define STMT(Node, Base) case Expr::Node##Class:
8833#define EXPR(Node, Base)
8834#include "clang/AST/StmtNodes.inc"
8835 case Expr::PredefinedExprClass:
8836 case Expr::FloatingLiteralClass:
8837 case Expr::ImaginaryLiteralClass:
8838 case Expr::StringLiteralClass:
8839 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008840 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00008841 case Expr::MemberExprClass:
8842 case Expr::CompoundAssignOperatorClass:
8843 case Expr::CompoundLiteralExprClass:
8844 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008845 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00008846 case Expr::NoInitExprClass:
8847 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00008848 case Expr::ImplicitValueInitExprClass:
8849 case Expr::ParenListExprClass:
8850 case Expr::VAArgExprClass:
8851 case Expr::AddrLabelExprClass:
8852 case Expr::StmtExprClass:
8853 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008854 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008855 case Expr::CXXDynamicCastExprClass:
8856 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008857 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008858 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008859 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008860 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008861 case Expr::CXXThisExprClass:
8862 case Expr::CXXThrowExprClass:
8863 case Expr::CXXNewExprClass:
8864 case Expr::CXXDeleteExprClass:
8865 case Expr::CXXPseudoDestructorExprClass:
8866 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00008867 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00008868 case Expr::DependentScopeDeclRefExprClass:
8869 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008870 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008871 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008872 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008873 case Expr::CXXTemporaryObjectExprClass:
8874 case Expr::CXXUnresolvedConstructExprClass:
8875 case Expr::CXXDependentScopeMemberExprClass:
8876 case Expr::UnresolvedMemberExprClass:
8877 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008878 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008879 case Expr::ObjCArrayLiteralClass:
8880 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008881 case Expr::ObjCEncodeExprClass:
8882 case Expr::ObjCMessageExprClass:
8883 case Expr::ObjCSelectorExprClass:
8884 case Expr::ObjCProtocolExprClass:
8885 case Expr::ObjCIvarRefExprClass:
8886 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008887 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008888 case Expr::ObjCIsaExprClass:
8889 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008890 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008891 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008892 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008893 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008894 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008895 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008896 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008897 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008898 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008899 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008900 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008901 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008902 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00008903 case Expr::CXXFoldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008904 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008905
Richard Smithf137f932014-01-25 20:50:08 +00008906 case Expr::InitListExprClass: {
8907 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8908 // form "T x = { a };" is equivalent to "T x = a;".
8909 // Unless we're initializing a reference, T is a scalar as it is known to be
8910 // of integral or enumeration type.
8911 if (E->isRValue())
8912 if (cast<InitListExpr>(E)->getNumInits() == 1)
8913 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8914 return ICEDiag(IK_NotICE, E->getLocStart());
8915 }
8916
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008917 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008918 case Expr::GNUNullExprClass:
8919 // GCC considers the GNU __null value to be an integral constant expression.
8920 return NoDiag();
8921
John McCall7c454bb2011-07-15 05:09:51 +00008922 case Expr::SubstNonTypeTemplateParmExprClass:
8923 return
8924 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8925
John McCall864e3962010-05-07 05:32:02 +00008926 case Expr::ParenExprClass:
8927 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008928 case Expr::GenericSelectionExprClass:
8929 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008930 case Expr::IntegerLiteralClass:
8931 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008932 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008933 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008934 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008935 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008936 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008937 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008938 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008939 return NoDiag();
8940 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008941 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008942 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8943 // constant expressions, but they can never be ICEs because an ICE cannot
8944 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008945 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008946 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008947 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008948 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008949 }
Richard Smith6365c912012-02-24 22:12:32 +00008950 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008951 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8952 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008953 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008954 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008955 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008956 // Parameter variables are never constants. Without this check,
8957 // getAnyInitializer() can find a default argument, which leads
8958 // to chaos.
8959 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008960 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008961
8962 // C++ 7.1.5.1p2
8963 // A variable of non-volatile const-qualified integral or enumeration
8964 // type initialized by an ICE can be used in ICEs.
8965 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008966 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008967 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008968
Richard Smithd0b4dd62011-12-19 06:19:21 +00008969 const VarDecl *VD;
8970 // Look for a declaration of this variable that has an initializer, and
8971 // check whether it is an ICE.
8972 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8973 return NoDiag();
8974 else
Richard Smith9e575da2012-12-28 13:25:52 +00008975 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008976 }
8977 }
Richard Smith9e575da2012-12-28 13:25:52 +00008978 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008979 }
John McCall864e3962010-05-07 05:32:02 +00008980 case Expr::UnaryOperatorClass: {
8981 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8982 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008983 case UO_PostInc:
8984 case UO_PostDec:
8985 case UO_PreInc:
8986 case UO_PreDec:
8987 case UO_AddrOf:
8988 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008989 // C99 6.6/3 allows increment and decrement within unevaluated
8990 // subexpressions of constant expressions, but they can never be ICEs
8991 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008992 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008993 case UO_Extension:
8994 case UO_LNot:
8995 case UO_Plus:
8996 case UO_Minus:
8997 case UO_Not:
8998 case UO_Real:
8999 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009000 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009001 }
Richard Smith9e575da2012-12-28 13:25:52 +00009002
John McCall864e3962010-05-07 05:32:02 +00009003 // OffsetOf falls through here.
9004 }
9005 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009006 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9007 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9008 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9009 // compliance: we should warn earlier for offsetof expressions with
9010 // array subscripts that aren't ICEs, and if the array subscripts
9011 // are ICEs, the value of the offsetof must be an integer constant.
9012 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009013 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009014 case Expr::UnaryExprOrTypeTraitExprClass: {
9015 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9016 if ((Exp->getKind() == UETT_SizeOf) &&
9017 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009018 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009019 return NoDiag();
9020 }
9021 case Expr::BinaryOperatorClass: {
9022 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9023 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009024 case BO_PtrMemD:
9025 case BO_PtrMemI:
9026 case BO_Assign:
9027 case BO_MulAssign:
9028 case BO_DivAssign:
9029 case BO_RemAssign:
9030 case BO_AddAssign:
9031 case BO_SubAssign:
9032 case BO_ShlAssign:
9033 case BO_ShrAssign:
9034 case BO_AndAssign:
9035 case BO_XorAssign:
9036 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009037 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9038 // constant expressions, but they can never be ICEs because an ICE cannot
9039 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009040 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009041
John McCalle3027922010-08-25 11:45:40 +00009042 case BO_Mul:
9043 case BO_Div:
9044 case BO_Rem:
9045 case BO_Add:
9046 case BO_Sub:
9047 case BO_Shl:
9048 case BO_Shr:
9049 case BO_LT:
9050 case BO_GT:
9051 case BO_LE:
9052 case BO_GE:
9053 case BO_EQ:
9054 case BO_NE:
9055 case BO_And:
9056 case BO_Xor:
9057 case BO_Or:
9058 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009059 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9060 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009061 if (Exp->getOpcode() == BO_Div ||
9062 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009063 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009064 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009065 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009066 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009067 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009068 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009069 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009070 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009071 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009072 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009073 }
9074 }
9075 }
John McCalle3027922010-08-25 11:45:40 +00009076 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009077 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009078 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9079 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009080 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9081 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009082 } else {
9083 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009084 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009085 }
9086 }
Richard Smith9e575da2012-12-28 13:25:52 +00009087 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009088 }
John McCalle3027922010-08-25 11:45:40 +00009089 case BO_LAnd:
9090 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009091 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9092 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009093 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009094 // Rare case where the RHS has a comma "side-effect"; we need
9095 // to actually check the condition to see whether the side
9096 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009097 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009098 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009099 return RHSResult;
9100 return NoDiag();
9101 }
9102
Richard Smith9e575da2012-12-28 13:25:52 +00009103 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009104 }
9105 }
9106 }
9107 case Expr::ImplicitCastExprClass:
9108 case Expr::CStyleCastExprClass:
9109 case Expr::CXXFunctionalCastExprClass:
9110 case Expr::CXXStaticCastExprClass:
9111 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009112 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009113 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009114 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009115 if (isa<ExplicitCastExpr>(E)) {
9116 if (const FloatingLiteral *FL
9117 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9118 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9119 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9120 APSInt IgnoredVal(DestWidth, !DestSigned);
9121 bool Ignored;
9122 // If the value does not fit in the destination type, the behavior is
9123 // undefined, so we are not required to treat it as a constant
9124 // expression.
9125 if (FL->getValue().convertToInteger(IgnoredVal,
9126 llvm::APFloat::rmTowardZero,
9127 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009128 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009129 return NoDiag();
9130 }
9131 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009132 switch (cast<CastExpr>(E)->getCastKind()) {
9133 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009134 case CK_AtomicToNonAtomic:
9135 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009136 case CK_NoOp:
9137 case CK_IntegralToBoolean:
9138 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009139 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009140 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009141 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009142 }
John McCall864e3962010-05-07 05:32:02 +00009143 }
John McCallc07a0c72011-02-17 10:25:35 +00009144 case Expr::BinaryConditionalOperatorClass: {
9145 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9146 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009147 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009148 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009149 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9150 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9151 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009152 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009153 return FalseResult;
9154 }
John McCall864e3962010-05-07 05:32:02 +00009155 case Expr::ConditionalOperatorClass: {
9156 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9157 // If the condition (ignoring parens) is a __builtin_constant_p call,
9158 // then only the true side is actually considered in an integer constant
9159 // expression, and it is fully evaluated. This is an important GNU
9160 // extension. See GCC PR38377 for discussion.
9161 if (const CallExpr *CallCE
9162 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009163 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009164 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009165 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009166 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009167 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009168
Richard Smithf57d8cb2011-12-09 22:58:01 +00009169 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9170 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009171
Richard Smith9e575da2012-12-28 13:25:52 +00009172 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009173 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009174 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009175 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009176 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009177 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009178 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009179 return NoDiag();
9180 // Rare case where the diagnostics depend on which side is evaluated
9181 // Note that if we get here, CondResult is 0, and at least one of
9182 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009183 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009184 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009185 return TrueResult;
9186 }
9187 case Expr::CXXDefaultArgExprClass:
9188 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009189 case Expr::CXXDefaultInitExprClass:
9190 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009191 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009192 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009193 }
9194 }
9195
David Blaikiee4d798f2012-01-20 21:50:17 +00009196 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009197}
9198
Richard Smithf57d8cb2011-12-09 22:58:01 +00009199/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009200static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009201 const Expr *E,
9202 llvm::APSInt *Value,
9203 SourceLocation *Loc) {
9204 if (!E->getType()->isIntegralOrEnumerationType()) {
9205 if (Loc) *Loc = E->getExprLoc();
9206 return false;
9207 }
9208
Richard Smith66e05fe2012-01-18 05:21:49 +00009209 APValue Result;
9210 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009211 return false;
9212
Richard Smith98710fc2014-11-13 23:03:19 +00009213 if (!Result.isInt()) {
9214 if (Loc) *Loc = E->getExprLoc();
9215 return false;
9216 }
9217
Richard Smith66e05fe2012-01-18 05:21:49 +00009218 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009219 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009220}
9221
Craig Toppera31a8822013-08-22 07:09:37 +00009222bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9223 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009224 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009225 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009226
Richard Smith9e575da2012-12-28 13:25:52 +00009227 ICEDiag D = CheckICE(this, Ctx);
9228 if (D.Kind != IK_ICE) {
9229 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009230 return false;
9231 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009232 return true;
9233}
9234
Craig Toppera31a8822013-08-22 07:09:37 +00009235bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009236 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009237 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009238 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9239
9240 if (!isIntegerConstantExpr(Ctx, Loc))
9241 return false;
9242 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00009243 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009244 return true;
9245}
Richard Smith66e05fe2012-01-18 05:21:49 +00009246
Craig Toppera31a8822013-08-22 07:09:37 +00009247bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009248 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009249}
9250
Craig Toppera31a8822013-08-22 07:09:37 +00009251bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009252 SourceLocation *Loc) const {
9253 // We support this checking in C++98 mode in order to diagnose compatibility
9254 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009255 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009256
Richard Smith98a0a492012-02-14 21:38:30 +00009257 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009258 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009259 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009260 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009261 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009262
9263 APValue Scratch;
9264 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9265
9266 if (!Diags.empty()) {
9267 IsConstExpr = false;
9268 if (Loc) *Loc = Diags[0].first;
9269 } else if (!IsConstExpr) {
9270 // FIXME: This shouldn't happen.
9271 if (Loc) *Loc = getExprLoc();
9272 }
9273
9274 return IsConstExpr;
9275}
Richard Smith253c2a32012-01-27 01:14:48 +00009276
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009277bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9278 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009279 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009280 Expr::EvalStatus Status;
9281 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9282
9283 ArgVector ArgValues(Args.size());
9284 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9285 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009286 if ((*I)->isValueDependent() ||
9287 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009288 // If evaluation fails, throw away the argument entirely.
9289 ArgValues[I - Args.begin()] = APValue();
9290 if (Info.EvalStatus.HasSideEffects)
9291 return false;
9292 }
9293
9294 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009295 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009296 ArgValues.data());
9297 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9298}
9299
Richard Smith253c2a32012-01-27 01:14:48 +00009300bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009301 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009302 PartialDiagnosticAt> &Diags) {
9303 // FIXME: It would be useful to check constexpr function templates, but at the
9304 // moment the constant expression evaluator cannot cope with the non-rigorous
9305 // ASTs which we build for dependent expressions.
9306 if (FD->isDependentContext())
9307 return true;
9308
9309 Expr::EvalStatus Status;
9310 Status.Diag = &Diags;
9311
Richard Smith6d4c6582013-11-05 22:18:15 +00009312 EvalInfo Info(FD->getASTContext(), Status,
9313 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009314
9315 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009316 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009317
Richard Smith7525ff62013-05-09 07:14:00 +00009318 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009319 // is a temporary being used as the 'this' pointer.
9320 LValue This;
9321 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009322 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009323
Richard Smith253c2a32012-01-27 01:14:48 +00009324 ArrayRef<const Expr*> Args;
9325
9326 SourceLocation Loc = FD->getLocation();
9327
Richard Smith2e312c82012-03-03 22:46:17 +00009328 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009329 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9330 // Evaluate the call as a constant initializer, to allow the construction
9331 // of objects of non-literal types.
9332 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009333 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009334 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009335 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009336 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009337
9338 return Diags.empty();
9339}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009340
9341bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9342 const FunctionDecl *FD,
9343 SmallVectorImpl<
9344 PartialDiagnosticAt> &Diags) {
9345 Expr::EvalStatus Status;
9346 Status.Diag = &Diags;
9347
9348 EvalInfo Info(FD->getASTContext(), Status,
9349 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9350
9351 // Fabricate a call stack frame to give the arguments a plausible cover story.
9352 ArrayRef<const Expr*> Args;
9353 ArgVector ArgValues(0);
9354 bool Success = EvaluateArgs(Args, ArgValues, Info);
9355 (void)Success;
9356 assert(Success &&
9357 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009358 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009359
9360 APValue ResultScratch;
9361 Evaluate(ResultScratch, Info, E);
9362 return Diags.empty();
9363}