blob: a25a6c7e51358fce5a73fa1f6e6289dc0c38ecea [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"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000047#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000048#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000049#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000050#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000051
Anders Carlsson7a241ba2008-07-03 04:20:39 +000052using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000053using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000054using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000055
Richard Smithb228a862012-02-15 02:18:13 +000056static bool IsGlobalLValue(APValue::LValueBase B);
57
John McCall93d91dc2010-05-07 17:22:02 +000058namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000059 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000060 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000061 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000062
Richard Smithb228a862012-02-15 02:18:13 +000063 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000064 if (!B) return QualType();
65 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
66 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000067
68 const Expr *Base = B.get<const Expr*>();
69
70 // For a materialized temporary, the type of the temporary we materialized
71 // may not be the type of the expression.
72 if (const MaterializeTemporaryExpr *MTE =
73 dyn_cast<MaterializeTemporaryExpr>(Base)) {
74 SmallVector<const Expr *, 2> CommaLHSs;
75 SmallVector<SubobjectAdjustment, 2> Adjustments;
76 const Expr *Temp = MTE->GetTemporaryExpr();
77 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
78 Adjustments);
79 // Keep any cv-qualifiers from the reference if we generated a temporary
80 // for it.
81 if (Inner != Temp)
82 return Inner->getType();
83 }
84
85 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000086 }
87
Richard Smithd62306a2011-11-10 06:34:14 +000088 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000089 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000092 APValue::BaseOrMemberType Value;
93 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000094 return Value;
95 }
96
97 /// Get an LValue path entry, which is known to not be an array index, as a
98 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000099 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000100 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000101 }
102 /// Get an LValue path entry, which is known to not be an array index, as a
103 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000104 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000105 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000106 }
107 /// Determine whether this LValue path entry for a base class names a virtual
108 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000109 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000110 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000111 }
112
Richard Smitha8105bc2012-01-06 16:39:00 +0000113 /// Find the path length and type of the most-derived subobject in the given
114 /// path, and find the size of the containing array, if any.
115 static
116 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
117 ArrayRef<APValue::LValuePathEntry> Path,
George Burgess IVa51c4072015-10-16 01:49:01 +0000118 uint64_t &ArraySize, QualType &Type,
119 bool &IsArray) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 unsigned MostDerivedLength = 0;
121 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000122 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 if (Type->isArrayType()) {
124 const ConstantArrayType *CAT =
125 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
126 Type = CAT->getElementType();
127 ArraySize = CAT->getSize().getZExtValue();
128 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000129 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000130 } else if (Type->isAnyComplexType()) {
131 const ComplexType *CT = Type->castAs<ComplexType>();
132 Type = CT->getElementType();
133 ArraySize = 2;
134 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000135 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000136 } else if (const FieldDecl *FD = getAsField(Path[I])) {
137 Type = FD->getType();
138 ArraySize = 0;
139 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000140 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 } else {
Richard Smith80815602011-11-07 05:07:52 +0000142 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000143 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000144 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000145 }
Richard Smith80815602011-11-07 05:07:52 +0000146 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000147 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000148 }
149
Richard Smitha8105bc2012-01-06 16:39:00 +0000150 // The order of this enum is important for diagnostics.
151 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000152 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000153 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000154 };
155
Richard Smith96e0c102011-11-04 02:25:55 +0000156 /// A path from a glvalue to a subobject of that glvalue.
157 struct SubobjectDesignator {
158 /// True if the subobject was named in a manner not supported by C++11. Such
159 /// lvalues can still be folded, but they are not core constant expressions
160 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000161 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000162
Richard Smitha8105bc2012-01-06 16:39:00 +0000163 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000164 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000165
George Burgess IVa51c4072015-10-16 01:49:01 +0000166 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000167 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000168
Richard Smitha8105bc2012-01-06 16:39:00 +0000169 /// The length of the path to the most-derived object of which this is a
170 /// subobject.
George Burgess IVa51c4072015-10-16 01:49:01 +0000171 unsigned MostDerivedPathLength : 29;
Richard Smitha8105bc2012-01-06 16:39:00 +0000172
George Burgess IVa51c4072015-10-16 01:49:01 +0000173 /// The size of the array of which the most-derived object is an element.
174 /// This will always be 0 if the most-derived object is not an array
175 /// element. 0 is not an indicator of whether or not the most-derived object
176 /// is an array, however, because 0-length arrays are allowed.
Richard Smitha8105bc2012-01-06 16:39:00 +0000177 uint64_t MostDerivedArraySize;
178
179 /// The type of the most derived object referred to by this address.
180 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000181
Richard Smith80815602011-11-07 05:07:52 +0000182 typedef APValue::LValuePathEntry PathEntry;
183
Richard Smith96e0c102011-11-04 02:25:55 +0000184 /// The entries on the path from the glvalue to the designated subobject.
185 SmallVector<PathEntry, 8> Entries;
186
Richard Smitha8105bc2012-01-06 16:39:00 +0000187 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000188
Richard Smitha8105bc2012-01-06 16:39:00 +0000189 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000190 : Invalid(false), IsOnePastTheEnd(false),
191 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
192 MostDerivedArraySize(0), MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000193
194 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000195 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
196 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
197 MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000198 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000199 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000200 ArrayRef<PathEntry> VEntries = V.getLValuePath();
201 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000202 if (V.getLValueBase()) {
203 bool IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000204 MostDerivedPathLength =
205 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
206 V.getLValuePath(), MostDerivedArraySize,
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 MostDerivedType, IsArray);
208 MostDerivedIsArrayElement = IsArray;
209 }
Richard Smith80815602011-11-07 05:07:52 +0000210 }
211 }
212
Richard Smith96e0c102011-11-04 02:25:55 +0000213 void setInvalid() {
214 Invalid = true;
215 Entries.clear();
216 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000217
218 /// Determine whether this is a one-past-the-end pointer.
219 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000220 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000221 if (IsOnePastTheEnd)
222 return true;
George Burgess IVa51c4072015-10-16 01:49:01 +0000223 if (MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
225 return true;
226 return false;
227 }
228
229 /// Check that this refers to a valid subobject.
230 bool isValidSubobject() const {
231 if (Invalid)
232 return false;
233 return !isOnePastTheEnd();
234 }
235 /// Check that this refers to a valid subobject, and if not, produce a
236 /// relevant diagnostic and set the designator as invalid.
237 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
238
239 /// Update this designator to refer to the first element within this array.
240 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000241 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000243 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000244
245 // This is a most-derived object.
246 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000247 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 MostDerivedArraySize = CAT->getSize().getZExtValue();
249 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000250 }
251 /// Update this designator to refer to the given base or member of this
252 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000254 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000255 APValue::BaseOrMemberType Value(D, Virtual);
256 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000257 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000258
259 // If this isn't a base class, it's a new most-derived object.
260 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
261 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000262 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 MostDerivedArraySize = 0;
264 MostDerivedPathLength = Entries.size();
265 }
Richard Smith96e0c102011-11-04 02:25:55 +0000266 }
Richard Smith66c96992012-02-18 22:04:06 +0000267 /// Update this designator to refer to the given complex component.
268 void addComplexUnchecked(QualType EltTy, bool Imag) {
269 PathEntry Entry;
270 Entry.ArrayIndex = Imag;
271 Entries.push_back(Entry);
272
273 // This is technically a most-derived object, though in practice this
274 // is unlikely to matter.
275 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000276 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000277 MostDerivedArraySize = 2;
278 MostDerivedPathLength = Entries.size();
279 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000280 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000281 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000283 if (Invalid) return;
George Burgess IVa51c4072015-10-16 01:49:01 +0000284 if (MostDerivedPathLength == Entries.size() &&
285 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000286 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000287 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
288 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
289 setInvalid();
290 }
Richard Smith96e0c102011-11-04 02:25:55 +0000291 return;
292 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000293 // [expr.add]p4: For the purposes of these operators, a pointer to a
294 // nonarray object behaves the same as a pointer to the first element of
295 // an array of length one with the type of the object as its element type.
296 if (IsOnePastTheEnd && N == (uint64_t)-1)
297 IsOnePastTheEnd = false;
298 else if (!IsOnePastTheEnd && N == 1)
299 IsOnePastTheEnd = true;
300 else if (N != 0) {
301 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000302 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000303 }
Richard Smith96e0c102011-11-04 02:25:55 +0000304 }
305 };
306
Richard Smith254a73d2011-10-28 22:34:42 +0000307 /// A stack frame in the constexpr call stack.
308 struct CallStackFrame {
309 EvalInfo &Info;
310
311 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000313
Richard Smithf6f003a2011-12-16 19:06:07 +0000314 /// CallLoc - The location of the call expression for this call.
315 SourceLocation CallLoc;
316
317 /// Callee - The function which was called.
318 const FunctionDecl *Callee;
319
Richard Smithb228a862012-02-15 02:18:13 +0000320 /// Index - The call index of this call.
321 unsigned Index;
322
Richard Smithd62306a2011-11-10 06:34:14 +0000323 /// This - The binding for the this pointer in this call, if any.
324 const LValue *This;
325
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000326 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000327 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000328 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000329
Eli Friedman4830ec82012-06-25 21:21:08 +0000330 // Note that we intentionally use std::map here so that references to
331 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000332 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000333 typedef MapTy::const_iterator temp_iterator;
334 /// Temporaries - Temporary lvalues materialized within this stack frame.
335 MapTy Temporaries;
336
Richard Smithf6f003a2011-12-16 19:06:07 +0000337 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
338 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000339 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000340 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000341
342 APValue *getTemporary(const void *Key) {
343 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000344 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000345 }
346 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000347 };
348
Richard Smith852c9db2013-04-20 22:23:05 +0000349 /// Temporarily override 'this'.
350 class ThisOverrideRAII {
351 public:
352 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
353 : Frame(Frame), OldThis(Frame.This) {
354 if (Enable)
355 Frame.This = NewThis;
356 }
357 ~ThisOverrideRAII() {
358 Frame.This = OldThis;
359 }
360 private:
361 CallStackFrame &Frame;
362 const LValue *OldThis;
363 };
364
Richard Smith92b1ce02011-12-12 09:28:41 +0000365 /// A partial diagnostic which we might know in advance that we are not going
366 /// to emit.
367 class OptionalDiagnostic {
368 PartialDiagnostic *Diag;
369
370 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000371 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
372 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000373
374 template<typename T>
375 OptionalDiagnostic &operator<<(const T &v) {
376 if (Diag)
377 *Diag << v;
378 return *this;
379 }
Richard Smithfe800032012-01-31 04:08:20 +0000380
381 OptionalDiagnostic &operator<<(const APSInt &I) {
382 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000383 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000384 I.toString(Buffer);
385 *Diag << StringRef(Buffer.data(), Buffer.size());
386 }
387 return *this;
388 }
389
390 OptionalDiagnostic &operator<<(const APFloat &F) {
391 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000392 // FIXME: Force the precision of the source value down so we don't
393 // print digits which are usually useless (we don't really care here if
394 // we truncate a digit by accident in edge cases). Ideally,
395 // APFloat::toString would automatically print the shortest
396 // representation which rounds to the correct value, but it's a bit
397 // tricky to implement.
398 unsigned precision =
399 llvm::APFloat::semanticsPrecision(F.getSemantics());
400 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000401 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000402 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000403 *Diag << StringRef(Buffer.data(), Buffer.size());
404 }
405 return *this;
406 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000407 };
408
Richard Smith08d6a2c2013-07-24 07:11:57 +0000409 /// A cleanup, and a flag indicating whether it is lifetime-extended.
410 class Cleanup {
411 llvm::PointerIntPair<APValue*, 1, bool> Value;
412
413 public:
414 Cleanup(APValue *Val, bool IsLifetimeExtended)
415 : Value(Val, IsLifetimeExtended) {}
416
417 bool isLifetimeExtended() const { return Value.getInt(); }
418 void endLifetime() {
419 *Value.getPointer() = APValue();
420 }
421 };
422
Richard Smithb228a862012-02-15 02:18:13 +0000423 /// EvalInfo - This is a private struct used by the evaluator to capture
424 /// information about a subexpression as it is folded. It retains information
425 /// about the AST context, but also maintains information about the folded
426 /// expression.
427 ///
428 /// If an expression could be evaluated, it is still possible it is not a C
429 /// "integer constant expression" or constant expression. If not, this struct
430 /// captures information about how and why not.
431 ///
432 /// One bit of information passed *into* the request for constant folding
433 /// indicates whether the subexpression is "evaluated" or not according to C
434 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
435 /// evaluate the expression regardless of what the RHS is, but C only allows
436 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000438 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000439
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000440 /// EvalStatus - Contains information about the evaluation.
441 Expr::EvalStatus &EvalStatus;
442
443 /// CurrentCall - The top of the constexpr call stack.
444 CallStackFrame *CurrentCall;
445
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000446 /// CallStackDepth - The number of calls in the call stack right now.
447 unsigned CallStackDepth;
448
Richard Smithb228a862012-02-15 02:18:13 +0000449 /// NextCallIndex - The next call index to assign.
450 unsigned NextCallIndex;
451
Richard Smitha3d3bd22013-05-08 02:12:03 +0000452 /// StepsLeft - The remaining number of evaluation steps we're permitted
453 /// to perform. This is essentially a limit for the number of statements
454 /// we will evaluate.
455 unsigned StepsLeft;
456
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000457 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000458 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000459 CallStackFrame BottomFrame;
460
Richard Smith08d6a2c2013-07-24 07:11:57 +0000461 /// A stack of values whose lifetimes end at the end of some surrounding
462 /// evaluation frame.
463 llvm::SmallVector<Cleanup, 16> CleanupStack;
464
Richard Smithd62306a2011-11-10 06:34:14 +0000465 /// EvaluatingDecl - This is the declaration whose initializer is being
466 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000467 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000468
469 /// EvaluatingDeclValue - This is the value being constructed for the
470 /// declaration whose initializer is being evaluated, if any.
471 APValue *EvaluatingDeclValue;
472
Richard Smith357362d2011-12-13 06:39:58 +0000473 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
474 /// notes attached to it will also be stored, otherwise they will not be.
475 bool HasActiveDiagnostic;
476
Richard Smith0c6124b2015-12-03 01:36:22 +0000477 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
478 /// fold (not just why it's not strictly a constant expression)?
479 bool HasFoldFailureDiagnostic;
480
George Burgess IV8c892b52016-05-25 22:31:54 +0000481 /// \brief Whether or not we're currently speculatively evaluating.
482 bool IsSpeculativelyEvaluating;
483
Richard Smith6d4c6582013-11-05 22:18:15 +0000484 enum EvaluationMode {
485 /// Evaluate as a constant expression. Stop if we find that the expression
486 /// is not a constant expression.
487 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000488
Richard Smith6d4c6582013-11-05 22:18:15 +0000489 /// Evaluate as a potential constant expression. Keep going if we hit a
490 /// construct that we can't evaluate yet (because we don't yet know the
491 /// value of something) but stop if we hit something that could never be
492 /// a constant expression.
493 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000494
Richard Smith6d4c6582013-11-05 22:18:15 +0000495 /// Fold the expression to a constant. Stop if we hit a side-effect that
496 /// we can't model.
497 EM_ConstantFold,
498
499 /// Evaluate the expression looking for integer overflow and similar
500 /// issues. Don't worry about side-effects, and try to visit all
501 /// subexpressions.
502 EM_EvaluateForOverflow,
503
504 /// Evaluate in any way we know how. Don't worry about side-effects that
505 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000506 EM_IgnoreSideEffects,
507
508 /// Evaluate as a constant expression. Stop if we find that the expression
509 /// is not a constant expression. Some expressions can be retried in the
510 /// optimizer if we don't constant fold them here, but in an unevaluated
511 /// context we try to fold them immediately since the optimizer never
512 /// gets a chance to look at it.
513 EM_ConstantExpressionUnevaluated,
514
515 /// Evaluate as a potential constant expression. Keep going if we hit a
516 /// construct that we can't evaluate yet (because we don't yet know the
517 /// value of something) but stop if we hit something that could never be
518 /// a constant expression. Some expressions can be retried in the
519 /// optimizer if we don't constant fold them here, but in an unevaluated
520 /// context we try to fold them immediately since the optimizer never
521 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000522 EM_PotentialConstantExpressionUnevaluated,
523
524 /// Evaluate as a constant expression. Continue evaluating if we find a
525 /// MemberExpr with a base that can't be evaluated.
526 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000527 } EvalMode;
528
529 /// Are we checking whether the expression is a potential constant
530 /// expression?
531 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000532 return EvalMode == EM_PotentialConstantExpression ||
533 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000534 }
535
536 /// Are we checking an expression for overflow?
537 // FIXME: We should check for any kind of undefined or suspicious behavior
538 // in such constructs, not just overflow.
539 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
540
541 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000542 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000543 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000544 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000545 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
546 EvaluatingDecl((const ValueDecl *)nullptr),
547 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000548 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
549 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000550
Richard Smith7525ff62013-05-09 07:14:00 +0000551 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
552 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000553 EvaluatingDeclValue = &Value;
554 }
555
David Blaikiebbafb8a2012-03-11 07:00:24 +0000556 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000557
Richard Smith357362d2011-12-13 06:39:58 +0000558 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000559 // Don't perform any constexpr calls (other than the call we're checking)
560 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000561 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000562 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000563 if (NextCallIndex == 0) {
564 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000565 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000566 return false;
567 }
Richard Smith357362d2011-12-13 06:39:58 +0000568 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
569 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000570 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000571 << getLangOpts().ConstexprCallDepth;
572 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000573 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000574
Richard Smithb228a862012-02-15 02:18:13 +0000575 CallStackFrame *getCallFrame(unsigned CallIndex) {
576 assert(CallIndex && "no call index in getCallFrame");
577 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
578 // be null in this loop.
579 CallStackFrame *Frame = CurrentCall;
580 while (Frame->Index > CallIndex)
581 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000582 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000583 }
584
Richard Smitha3d3bd22013-05-08 02:12:03 +0000585 bool nextStep(const Stmt *S) {
586 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000587 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000588 return false;
589 }
590 --StepsLeft;
591 return true;
592 }
593
Richard Smith357362d2011-12-13 06:39:58 +0000594 private:
595 /// Add a diagnostic to the diagnostics list.
596 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
597 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
598 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
599 return EvalStatus.Diag->back().second;
600 }
601
Richard Smithf6f003a2011-12-16 19:06:07 +0000602 /// Add notes containing a call stack to the current point of evaluation.
603 void addCallStack(unsigned Limit);
604
Faisal Valie690b7a2016-07-02 22:34:24 +0000605 private:
606 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
607 unsigned ExtraNotes, bool IsCCEDiag) {
608
Richard Smith92b1ce02011-12-12 09:28:41 +0000609 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000610 // If we have a prior diagnostic, it will be noting that the expression
611 // isn't a constant expression. This diagnostic is more important,
612 // unless we require this evaluation to produce a constant expression.
613 //
614 // FIXME: We might want to show both diagnostics to the user in
615 // EM_ConstantFold mode.
616 if (!EvalStatus.Diag->empty()) {
617 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000618 case EM_ConstantFold:
619 case EM_IgnoreSideEffects:
620 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000621 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000622 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000623 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000624 case EM_ConstantExpression:
625 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000626 case EM_ConstantExpressionUnevaluated:
627 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000628 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000629 HasActiveDiagnostic = false;
630 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000631 }
632 }
633
Richard Smithf6f003a2011-12-16 19:06:07 +0000634 unsigned CallStackNotes = CallStackDepth - 1;
635 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
636 if (Limit)
637 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000638 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000639 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000640
Richard Smith357362d2011-12-13 06:39:58 +0000641 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000642 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000643 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000644 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
645 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000646 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000647 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000648 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000649 }
Richard Smith357362d2011-12-13 06:39:58 +0000650 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000651 return OptionalDiagnostic();
652 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000653 public:
654 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
655 OptionalDiagnostic
656 FFDiag(SourceLocation Loc,
657 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
658 unsigned ExtraNotes = 0) {
659 return Diag(Loc, DiagId, ExtraNotes, false);
660 }
661
662 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000663 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000664 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000665 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000666 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000667 HasActiveDiagnostic = false;
668 return OptionalDiagnostic();
669 }
670
Richard Smith92b1ce02011-12-12 09:28:41 +0000671 /// Diagnose that the evaluation does not produce a C++11 core constant
672 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000673 ///
674 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
675 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000676 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000677 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000678 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000679 // Don't override a previous diagnostic. Don't bother collecting
680 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000681 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000682 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000683 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000684 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000685 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000686 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000687 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
688 = diag::note_invalid_subexpr_in_const_expr,
689 unsigned ExtraNotes = 0) {
690 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
691 }
Richard Smith357362d2011-12-13 06:39:58 +0000692 /// Add a note to a prior diagnostic.
693 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
694 if (!HasActiveDiagnostic)
695 return OptionalDiagnostic();
696 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000697 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000698
699 /// Add a stack of notes to a prior diagnostic.
700 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
701 if (HasActiveDiagnostic) {
702 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
703 Diags.begin(), Diags.end());
704 }
705 }
Richard Smith253c2a32012-01-27 01:14:48 +0000706
Richard Smith6d4c6582013-11-05 22:18:15 +0000707 /// Should we continue evaluation after encountering a side-effect that we
708 /// couldn't model?
709 bool keepEvaluatingAfterSideEffect() {
710 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000711 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000712 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000713 case EM_EvaluateForOverflow:
714 case EM_IgnoreSideEffects:
715 return true;
716
Richard Smith6d4c6582013-11-05 22:18:15 +0000717 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000718 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000719 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000720 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000721 return false;
722 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000723 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000724 }
725
726 /// Note that we have had a side-effect, and determine whether we should
727 /// keep evaluating.
728 bool noteSideEffect() {
729 EvalStatus.HasSideEffects = true;
730 return keepEvaluatingAfterSideEffect();
731 }
732
Richard Smithce8eca52015-12-08 03:21:47 +0000733 /// Should we continue evaluation after encountering undefined behavior?
734 bool keepEvaluatingAfterUndefinedBehavior() {
735 switch (EvalMode) {
736 case EM_EvaluateForOverflow:
737 case EM_IgnoreSideEffects:
738 case EM_ConstantFold:
739 case EM_DesignatorFold:
740 return true;
741
742 case EM_PotentialConstantExpression:
743 case EM_PotentialConstantExpressionUnevaluated:
744 case EM_ConstantExpression:
745 case EM_ConstantExpressionUnevaluated:
746 return false;
747 }
748 llvm_unreachable("Missed EvalMode case");
749 }
750
751 /// Note that we hit something that was technically undefined behavior, but
752 /// that we can evaluate past it (such as signed overflow or floating-point
753 /// division by zero.)
754 bool noteUndefinedBehavior() {
755 EvalStatus.HasUndefinedBehavior = true;
756 return keepEvaluatingAfterUndefinedBehavior();
757 }
758
Richard Smith253c2a32012-01-27 01:14:48 +0000759 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000760 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000761 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000762 if (!StepsLeft)
763 return false;
764
765 switch (EvalMode) {
766 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000767 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000768 case EM_EvaluateForOverflow:
769 return true;
770
771 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000772 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000773 case EM_ConstantFold:
774 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000775 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 return false;
777 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000778 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000779 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000780
George Burgess IV8c892b52016-05-25 22:31:54 +0000781 /// Notes that we failed to evaluate an expression that other expressions
782 /// directly depend on, and determine if we should keep evaluating. This
783 /// should only be called if we actually intend to keep evaluating.
784 ///
785 /// Call noteSideEffect() instead if we may be able to ignore the value that
786 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
787 ///
788 /// (Foo(), 1) // use noteSideEffect
789 /// (Foo() || true) // use noteSideEffect
790 /// Foo() + 1 // use noteFailure
791 LLVM_ATTRIBUTE_UNUSED_RESULT bool noteFailure() {
792 // Failure when evaluating some expression often means there is some
793 // subexpression whose evaluation was skipped. Therefore, (because we
794 // don't track whether we skipped an expression when unwinding after an
795 // evaluation failure) every evaluation failure that bubbles up from a
796 // subexpression implies that a side-effect has potentially happened. We
797 // skip setting the HasSideEffects flag to true until we decide to
798 // continue evaluating after that point, which happens here.
799 bool KeepGoing = keepEvaluatingAfterFailure();
800 EvalStatus.HasSideEffects |= KeepGoing;
801 return KeepGoing;
802 }
803
George Burgess IV3a03fab2015-09-04 21:28:13 +0000804 bool allowInvalidBaseExpr() const {
805 return EvalMode == EM_DesignatorFold;
806 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000807 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000808
809 /// Object used to treat all foldable expressions as constant expressions.
810 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000811 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000812 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000813 bool HadNoPriorDiags;
814 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000815
Richard Smith6d4c6582013-11-05 22:18:15 +0000816 explicit FoldConstant(EvalInfo &Info, bool Enabled)
817 : Info(Info),
818 Enabled(Enabled),
819 HadNoPriorDiags(Info.EvalStatus.Diag &&
820 Info.EvalStatus.Diag->empty() &&
821 !Info.EvalStatus.HasSideEffects),
822 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000823 if (Enabled &&
824 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
825 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000826 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000827 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000828 void keepDiagnostics() { Enabled = false; }
829 ~FoldConstant() {
830 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000831 !Info.EvalStatus.HasSideEffects)
832 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000834 }
835 };
Richard Smith17100ba2012-02-16 02:46:34 +0000836
George Burgess IV3a03fab2015-09-04 21:28:13 +0000837 /// RAII object used to treat the current evaluation as the correct pointer
838 /// offset fold for the current EvalMode
839 struct FoldOffsetRAII {
840 EvalInfo &Info;
841 EvalInfo::EvaluationMode OldMode;
842 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
843 : Info(Info), OldMode(Info.EvalMode) {
844 if (!Info.checkingPotentialConstantExpression())
845 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
846 : EvalInfo::EM_ConstantFold;
847 }
848
849 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
850 };
851
George Burgess IV8c892b52016-05-25 22:31:54 +0000852 /// RAII object used to optionally suppress diagnostics and side-effects from
853 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000854 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000855 /// Pair of EvalInfo, and a bit that stores whether or not we were
856 /// speculatively evaluating when we created this RAII.
857 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000858 Expr::EvalStatus Old;
859
George Burgess IV8c892b52016-05-25 22:31:54 +0000860 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
861 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
862 Old = Other.Old;
863 Other.InfoAndOldSpecEval.setPointer(nullptr);
864 }
865
866 void maybeRestoreState() {
867 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
868 if (!Info)
869 return;
870
871 Info->EvalStatus = Old;
872 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
873 }
874
Richard Smith17100ba2012-02-16 02:46:34 +0000875 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000876 SpeculativeEvaluationRAII() = default;
877
878 SpeculativeEvaluationRAII(
879 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
880 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
881 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000882 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000883 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000884 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000885
886 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
887 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
888 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000889 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000890
891 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
892 maybeRestoreState();
893 moveFromAndCancel(std::move(Other));
894 return *this;
895 }
896
897 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000898 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000899
900 /// RAII object wrapping a full-expression or block scope, and handling
901 /// the ending of the lifetime of temporaries created within it.
902 template<bool IsFullExpression>
903 class ScopeRAII {
904 EvalInfo &Info;
905 unsigned OldStackSize;
906 public:
907 ScopeRAII(EvalInfo &Info)
908 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
909 ~ScopeRAII() {
910 // Body moved to a static method to encourage the compiler to inline away
911 // instances of this class.
912 cleanup(Info, OldStackSize);
913 }
914 private:
915 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
916 unsigned NewEnd = OldStackSize;
917 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
918 I != N; ++I) {
919 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
920 // Full-expression cleanup of a lifetime-extended temporary: nothing
921 // to do, just move this cleanup to the right place in the stack.
922 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
923 ++NewEnd;
924 } else {
925 // End the lifetime of the object.
926 Info.CleanupStack[I].endLifetime();
927 }
928 }
929 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
930 Info.CleanupStack.end());
931 }
932 };
933 typedef ScopeRAII<false> BlockScopeRAII;
934 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000935}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000936
Richard Smitha8105bc2012-01-06 16:39:00 +0000937bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
938 CheckSubobjectKind CSK) {
939 if (Invalid)
940 return false;
941 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000942 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000943 << CSK;
944 setInvalid();
945 return false;
946 }
947 return true;
948}
949
950void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
951 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000952 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000953 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000954 << static_cast<int>(N) << /*array*/ 0
955 << static_cast<unsigned>(MostDerivedArraySize);
956 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000957 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000958 << static_cast<int>(N) << /*non-array*/ 1;
959 setInvalid();
960}
961
Richard Smithf6f003a2011-12-16 19:06:07 +0000962CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
963 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000964 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000965 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000966 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000967 Info.CurrentCall = this;
968 ++Info.CallStackDepth;
969}
970
971CallStackFrame::~CallStackFrame() {
972 assert(Info.CurrentCall == this && "calls retired out of order");
973 --Info.CallStackDepth;
974 Info.CurrentCall = Caller;
975}
976
Richard Smith08d6a2c2013-07-24 07:11:57 +0000977APValue &CallStackFrame::createTemporary(const void *Key,
978 bool IsLifetimeExtended) {
979 APValue &Result = Temporaries[Key];
980 assert(Result.isUninit() && "temporary created multiple times");
981 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
982 return Result;
983}
984
Richard Smith84401042013-06-03 05:03:02 +0000985static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000986
987void EvalInfo::addCallStack(unsigned Limit) {
988 // Determine which calls to skip, if any.
989 unsigned ActiveCalls = CallStackDepth - 1;
990 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
991 if (Limit && Limit < ActiveCalls) {
992 SkipStart = Limit / 2 + Limit % 2;
993 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000994 }
995
Richard Smithf6f003a2011-12-16 19:06:07 +0000996 // Walk the call stack and add the diagnostics.
997 unsigned CallIdx = 0;
998 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
999 Frame = Frame->Caller, ++CallIdx) {
1000 // Skip this call?
1001 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1002 if (CallIdx == SkipStart) {
1003 // Note that we're skipping calls.
1004 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1005 << unsigned(ActiveCalls - Limit);
1006 }
1007 continue;
1008 }
1009
Richard Smith5179eb72016-06-28 19:03:57 +00001010 // Use a different note for an inheriting constructor, because from the
1011 // user's perspective it's not really a function at all.
1012 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1013 if (CD->isInheritingConstructor()) {
1014 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1015 << CD->getParent();
1016 continue;
1017 }
1018 }
1019
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001020 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001021 llvm::raw_svector_ostream Out(Buffer);
1022 describeCall(Frame, Out);
1023 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1024 }
1025}
1026
1027namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001028 struct ComplexValue {
1029 private:
1030 bool IsInt;
1031
1032 public:
1033 APSInt IntReal, IntImag;
1034 APFloat FloatReal, FloatImag;
1035
1036 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
1037
1038 void makeComplexFloat() { IsInt = false; }
1039 bool isComplexFloat() const { return !IsInt; }
1040 APFloat &getComplexFloatReal() { return FloatReal; }
1041 APFloat &getComplexFloatImag() { return FloatImag; }
1042
1043 void makeComplexInt() { IsInt = true; }
1044 bool isComplexInt() const { return IsInt; }
1045 APSInt &getComplexIntReal() { return IntReal; }
1046 APSInt &getComplexIntImag() { return IntImag; }
1047
Richard Smith2e312c82012-03-03 22:46:17 +00001048 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001049 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001050 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001051 else
Richard Smith2e312c82012-03-03 22:46:17 +00001052 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001053 }
Richard Smith2e312c82012-03-03 22:46:17 +00001054 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001055 assert(v.isComplexFloat() || v.isComplexInt());
1056 if (v.isComplexFloat()) {
1057 makeComplexFloat();
1058 FloatReal = v.getComplexFloatReal();
1059 FloatImag = v.getComplexFloatImag();
1060 } else {
1061 makeComplexInt();
1062 IntReal = v.getComplexIntReal();
1063 IntImag = v.getComplexIntImag();
1064 }
1065 }
John McCall93d91dc2010-05-07 17:22:02 +00001066 };
John McCall45d55e42010-05-07 21:00:08 +00001067
1068 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001069 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001070 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001071 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001072 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001073 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +00001074
Richard Smithce40ad62011-11-12 22:28:03 +00001075 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001076 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001077 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001078 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001079 SubobjectDesignator &getLValueDesignator() { return Designator; }
1080 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +00001081
Richard Smith2e312c82012-03-03 22:46:17 +00001082 void moveInto(APValue &V) const {
1083 if (Designator.Invalid)
1084 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1085 else
1086 V = APValue(Base, Offset, Designator.Entries,
1087 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +00001088 }
Richard Smith2e312c82012-03-03 22:46:17 +00001089 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001090 assert(V.isLValue());
1091 Base = V.getLValueBase();
1092 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001093 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001094 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001095 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +00001096 }
1097
George Burgess IV3a03fab2015-09-04 21:28:13 +00001098 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +00001099 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +00001100 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001101 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001102 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001103 Designator = SubobjectDesignator(getType(B));
1104 }
1105
George Burgess IV3a03fab2015-09-04 21:28:13 +00001106 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1107 set(B, I, true);
1108 }
1109
Richard Smitha8105bc2012-01-06 16:39:00 +00001110 // Check that this LValue is not based on a null pointer. If it is, produce
1111 // a diagnostic and mark the designator as invalid.
1112 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1113 CheckSubobjectKind CSK) {
1114 if (Designator.Invalid)
1115 return false;
1116 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001117 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001118 << CSK;
1119 Designator.setInvalid();
1120 return false;
1121 }
1122 return true;
1123 }
1124
1125 // Check this LValue refers to an object. If not, set the designator to be
1126 // invalid and emit a diagnostic.
1127 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001128 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001129 Designator.checkSubobject(Info, E, CSK);
1130 }
1131
1132 void addDecl(EvalInfo &Info, const Expr *E,
1133 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001134 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1135 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001136 }
1137 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001138 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1139 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001140 }
Richard Smith66c96992012-02-18 22:04:06 +00001141 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001142 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1143 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001144 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001145 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001146 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001147 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001148 }
John McCall45d55e42010-05-07 21:00:08 +00001149 };
Richard Smith027bf112011-11-17 22:56:20 +00001150
1151 struct MemberPtr {
1152 MemberPtr() {}
1153 explicit MemberPtr(const ValueDecl *Decl) :
1154 DeclAndIsDerivedMember(Decl, false), Path() {}
1155
1156 /// The member or (direct or indirect) field referred to by this member
1157 /// pointer, or 0 if this is a null member pointer.
1158 const ValueDecl *getDecl() const {
1159 return DeclAndIsDerivedMember.getPointer();
1160 }
1161 /// Is this actually a member of some type derived from the relevant class?
1162 bool isDerivedMember() const {
1163 return DeclAndIsDerivedMember.getInt();
1164 }
1165 /// Get the class which the declaration actually lives in.
1166 const CXXRecordDecl *getContainingRecord() const {
1167 return cast<CXXRecordDecl>(
1168 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1169 }
1170
Richard Smith2e312c82012-03-03 22:46:17 +00001171 void moveInto(APValue &V) const {
1172 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001173 }
Richard Smith2e312c82012-03-03 22:46:17 +00001174 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001175 assert(V.isMemberPointer());
1176 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1177 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1178 Path.clear();
1179 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1180 Path.insert(Path.end(), P.begin(), P.end());
1181 }
1182
1183 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1184 /// whether the member is a member of some class derived from the class type
1185 /// of the member pointer.
1186 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1187 /// Path - The path of base/derived classes from the member declaration's
1188 /// class (exclusive) to the class type of the member pointer (inclusive).
1189 SmallVector<const CXXRecordDecl*, 4> Path;
1190
1191 /// Perform a cast towards the class of the Decl (either up or down the
1192 /// hierarchy).
1193 bool castBack(const CXXRecordDecl *Class) {
1194 assert(!Path.empty());
1195 const CXXRecordDecl *Expected;
1196 if (Path.size() >= 2)
1197 Expected = Path[Path.size() - 2];
1198 else
1199 Expected = getContainingRecord();
1200 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1201 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1202 // if B does not contain the original member and is not a base or
1203 // derived class of the class containing the original member, the result
1204 // of the cast is undefined.
1205 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1206 // (D::*). We consider that to be a language defect.
1207 return false;
1208 }
1209 Path.pop_back();
1210 return true;
1211 }
1212 /// Perform a base-to-derived member pointer cast.
1213 bool castToDerived(const CXXRecordDecl *Derived) {
1214 if (!getDecl())
1215 return true;
1216 if (!isDerivedMember()) {
1217 Path.push_back(Derived);
1218 return true;
1219 }
1220 if (!castBack(Derived))
1221 return false;
1222 if (Path.empty())
1223 DeclAndIsDerivedMember.setInt(false);
1224 return true;
1225 }
1226 /// Perform a derived-to-base member pointer cast.
1227 bool castToBase(const CXXRecordDecl *Base) {
1228 if (!getDecl())
1229 return true;
1230 if (Path.empty())
1231 DeclAndIsDerivedMember.setInt(true);
1232 if (isDerivedMember()) {
1233 Path.push_back(Base);
1234 return true;
1235 }
1236 return castBack(Base);
1237 }
1238 };
Richard Smith357362d2011-12-13 06:39:58 +00001239
Richard Smith7bb00672012-02-01 01:42:44 +00001240 /// Compare two member pointers, which are assumed to be of the same type.
1241 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1242 if (!LHS.getDecl() || !RHS.getDecl())
1243 return !LHS.getDecl() && !RHS.getDecl();
1244 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1245 return false;
1246 return LHS.Path == RHS.Path;
1247 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001248}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001249
Richard Smith2e312c82012-03-03 22:46:17 +00001250static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001251static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1252 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001253 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001254static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1255static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001256static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1257 EvalInfo &Info);
1258static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001259static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001260static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001261 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001262static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001263static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001264static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001265static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001266
1267//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001268// Misc utilities
1269//===----------------------------------------------------------------------===//
1270
Richard Smith84401042013-06-03 05:03:02 +00001271/// Produce a string describing the given constexpr call.
1272static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1273 unsigned ArgIndex = 0;
1274 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1275 !isa<CXXConstructorDecl>(Frame->Callee) &&
1276 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1277
1278 if (!IsMemberCall)
1279 Out << *Frame->Callee << '(';
1280
1281 if (Frame->This && IsMemberCall) {
1282 APValue Val;
1283 Frame->This->moveInto(Val);
1284 Val.printPretty(Out, Frame->Info.Ctx,
1285 Frame->This->Designator.MostDerivedType);
1286 // FIXME: Add parens around Val if needed.
1287 Out << "->" << *Frame->Callee << '(';
1288 IsMemberCall = false;
1289 }
1290
1291 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1292 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1293 if (ArgIndex > (unsigned)IsMemberCall)
1294 Out << ", ";
1295
1296 const ParmVarDecl *Param = *I;
1297 const APValue &Arg = Frame->Arguments[ArgIndex];
1298 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1299
1300 if (ArgIndex == 0 && IsMemberCall)
1301 Out << "->" << *Frame->Callee << '(';
1302 }
1303
1304 Out << ')';
1305}
1306
Richard Smithd9f663b2013-04-22 15:31:51 +00001307/// Evaluate an expression to see if it had side-effects, and discard its
1308/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001309/// \return \c true if the caller should keep evaluating.
1310static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001311 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001312 if (!Evaluate(Scratch, Info, E))
1313 // We don't need the value, but we might have skipped a side effect here.
1314 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001315 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001316}
1317
Richard Smith861b5b52013-05-07 23:34:45 +00001318/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1319/// return its existing value.
1320static int64_t getExtValue(const APSInt &Value) {
1321 return Value.isSigned() ? Value.getSExtValue()
1322 : static_cast<int64_t>(Value.getZExtValue());
1323}
1324
Richard Smithd62306a2011-11-10 06:34:14 +00001325/// Should this call expression be treated as a string literal?
1326static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001327 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001328 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1329 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1330}
1331
Richard Smithce40ad62011-11-12 22:28:03 +00001332static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001333 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1334 // constant expression of pointer type that evaluates to...
1335
1336 // ... a null pointer value, or a prvalue core constant expression of type
1337 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001338 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001339
Richard Smithce40ad62011-11-12 22:28:03 +00001340 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1341 // ... the address of an object with static storage duration,
1342 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1343 return VD->hasGlobalStorage();
1344 // ... the address of a function,
1345 return isa<FunctionDecl>(D);
1346 }
1347
1348 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001349 switch (E->getStmtClass()) {
1350 default:
1351 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001352 case Expr::CompoundLiteralExprClass: {
1353 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1354 return CLE->isFileScope() && CLE->isLValue();
1355 }
Richard Smithe6c01442013-06-05 00:46:14 +00001356 case Expr::MaterializeTemporaryExprClass:
1357 // A materialized temporary might have been lifetime-extended to static
1358 // storage duration.
1359 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001360 // A string literal has static storage duration.
1361 case Expr::StringLiteralClass:
1362 case Expr::PredefinedExprClass:
1363 case Expr::ObjCStringLiteralClass:
1364 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001365 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001366 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001367 return true;
1368 case Expr::CallExprClass:
1369 return IsStringLiteralCall(cast<CallExpr>(E));
1370 // For GCC compatibility, &&label has static storage duration.
1371 case Expr::AddrLabelExprClass:
1372 return true;
1373 // A Block literal expression may be used as the initialization value for
1374 // Block variables at global or local static scope.
1375 case Expr::BlockExprClass:
1376 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001377 case Expr::ImplicitValueInitExprClass:
1378 // FIXME:
1379 // We can never form an lvalue with an implicit value initialization as its
1380 // base through expression evaluation, so these only appear in one case: the
1381 // implicit variable declaration we invent when checking whether a constexpr
1382 // constructor can produce a constant expression. We must assume that such
1383 // an expression might be a global lvalue.
1384 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001385 }
John McCall95007602010-05-10 23:27:23 +00001386}
1387
Richard Smithb228a862012-02-15 02:18:13 +00001388static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1389 assert(Base && "no location for a null lvalue");
1390 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1391 if (VD)
1392 Info.Note(VD->getLocation(), diag::note_declared_at);
1393 else
Ted Kremenek28831752012-08-23 20:46:57 +00001394 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001395 diag::note_constexpr_temporary_here);
1396}
1397
Richard Smith80815602011-11-07 05:07:52 +00001398/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001399/// value for an address or reference constant expression. Return true if we
1400/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001401static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1402 QualType Type, const LValue &LVal) {
1403 bool IsReferenceType = Type->isReferenceType();
1404
Richard Smith357362d2011-12-13 06:39:58 +00001405 APValue::LValueBase Base = LVal.getLValueBase();
1406 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1407
Richard Smith0dea49e2012-02-18 04:58:18 +00001408 // Check that the object is a global. Note that the fake 'this' object we
1409 // manufacture when checking potential constant expressions is conservatively
1410 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001411 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001412 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001413 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001414 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001415 << IsReferenceType << !Designator.Entries.empty()
1416 << !!VD << VD;
1417 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001418 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001419 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001420 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001421 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001422 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001423 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001424 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001425 LVal.getLValueCallIndex() == 0) &&
1426 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001427
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001428 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1429 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001430 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001431 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001432 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001433
Hans Wennborg82dd8772014-06-25 22:19:48 +00001434 // A dllimport variable never acts like a constant.
1435 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001436 return false;
1437 }
1438 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1439 // __declspec(dllimport) must be handled very carefully:
1440 // We must never initialize an expression with the thunk in C++.
1441 // Doing otherwise would allow the same id-expression to yield
1442 // different addresses for the same function in different translation
1443 // units. However, this means that we must dynamically initialize the
1444 // expression with the contents of the import address table at runtime.
1445 //
1446 // The C language has no notion of ODR; furthermore, it has no notion of
1447 // dynamic initialization. This means that we are permitted to
1448 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001449 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001450 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001451 }
1452 }
1453
Richard Smitha8105bc2012-01-06 16:39:00 +00001454 // Allow address constant expressions to be past-the-end pointers. This is
1455 // an extension: the standard requires them to point to an object.
1456 if (!IsReferenceType)
1457 return true;
1458
1459 // A reference constant expression must refer to an object.
1460 if (!Base) {
1461 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001462 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001463 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001464 }
1465
Richard Smith357362d2011-12-13 06:39:58 +00001466 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001467 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001468 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001469 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001470 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001471 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001472 }
1473
Richard Smith80815602011-11-07 05:07:52 +00001474 return true;
1475}
1476
Richard Smithfddd3842011-12-30 21:15:51 +00001477/// Check that this core constant expression is of literal type, and if not,
1478/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001479static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001480 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001481 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001482 return true;
1483
Richard Smith7525ff62013-05-09 07:14:00 +00001484 // C++1y: A constant initializer for an object o [...] may also invoke
1485 // constexpr constructors for o and its subobjects even if those objects
1486 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001487 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001488 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001489 return true;
1490
Richard Smithfddd3842011-12-30 21:15:51 +00001491 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001492 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001493 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001494 << E->getType();
1495 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001496 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001497 return false;
1498}
1499
Richard Smith0b0a0b62011-10-29 20:57:55 +00001500/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001501/// constant expression. If not, report an appropriate diagnostic. Does not
1502/// check that the expression is of literal type.
1503static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1504 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001505 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001506 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001507 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001508 return false;
1509 }
1510
Richard Smith77be48a2014-07-31 06:31:19 +00001511 // We allow _Atomic(T) to be initialized from anything that T can be
1512 // initialized from.
1513 if (const AtomicType *AT = Type->getAs<AtomicType>())
1514 Type = AT->getValueType();
1515
Richard Smithb228a862012-02-15 02:18:13 +00001516 // Core issue 1454: For a literal constant expression of array or class type,
1517 // each subobject of its value shall have been initialized by a constant
1518 // expression.
1519 if (Value.isArray()) {
1520 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1521 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1522 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1523 Value.getArrayInitializedElt(I)))
1524 return false;
1525 }
1526 if (!Value.hasArrayFiller())
1527 return true;
1528 return CheckConstantExpression(Info, DiagLoc, EltTy,
1529 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001530 }
Richard Smithb228a862012-02-15 02:18:13 +00001531 if (Value.isUnion() && Value.getUnionField()) {
1532 return CheckConstantExpression(Info, DiagLoc,
1533 Value.getUnionField()->getType(),
1534 Value.getUnionValue());
1535 }
1536 if (Value.isStruct()) {
1537 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1538 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1539 unsigned BaseIndex = 0;
1540 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1541 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1542 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1543 Value.getStructBase(BaseIndex)))
1544 return false;
1545 }
1546 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001547 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001548 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1549 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001550 return false;
1551 }
1552 }
1553
1554 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001555 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001556 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001557 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1558 }
1559
1560 // Everything else is fine.
1561 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001562}
1563
Benjamin Kramer8407df72015-03-09 16:47:52 +00001564static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001565 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001566}
1567
1568static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001569 if (Value.CallIndex)
1570 return false;
1571 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1572 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001573}
1574
Richard Smithcecf1842011-11-01 21:06:14 +00001575static bool IsWeakLValue(const LValue &Value) {
1576 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001577 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001578}
1579
David Majnemerb5116032014-12-09 23:32:34 +00001580static bool isZeroSized(const LValue &Value) {
1581 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001582 if (Decl && isa<VarDecl>(Decl)) {
1583 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001584 if (Ty->isArrayType())
1585 return Ty->isIncompleteType() ||
1586 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001587 }
1588 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001589}
1590
Richard Smith2e312c82012-03-03 22:46:17 +00001591static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001592 // A null base expression indicates a null pointer. These are always
1593 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001594 if (!Value.getLValueBase()) {
1595 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001596 return true;
1597 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001598
Richard Smith027bf112011-11-17 22:56:20 +00001599 // We have a non-null base. These are generally known to be true, but if it's
1600 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001601 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001602 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001603 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001604}
1605
Richard Smith2e312c82012-03-03 22:46:17 +00001606static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001607 switch (Val.getKind()) {
1608 case APValue::Uninitialized:
1609 return false;
1610 case APValue::Int:
1611 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001612 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001613 case APValue::Float:
1614 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001615 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001616 case APValue::ComplexInt:
1617 Result = Val.getComplexIntReal().getBoolValue() ||
1618 Val.getComplexIntImag().getBoolValue();
1619 return true;
1620 case APValue::ComplexFloat:
1621 Result = !Val.getComplexFloatReal().isZero() ||
1622 !Val.getComplexFloatImag().isZero();
1623 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001624 case APValue::LValue:
1625 return EvalPointerValueAsBool(Val, Result);
1626 case APValue::MemberPointer:
1627 Result = Val.getMemberPointerDecl();
1628 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001629 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001630 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001631 case APValue::Struct:
1632 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001633 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001634 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001635 }
1636
Richard Smith11562c52011-10-28 17:51:58 +00001637 llvm_unreachable("unknown APValue kind");
1638}
1639
1640static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1641 EvalInfo &Info) {
1642 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001643 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001644 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001645 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001646 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001647}
1648
Richard Smith357362d2011-12-13 06:39:58 +00001649template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001650static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001651 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001652 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001653 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001654 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001655}
1656
1657static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1658 QualType SrcType, const APFloat &Value,
1659 QualType DestType, APSInt &Result) {
1660 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001661 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001662 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001663
Richard Smith357362d2011-12-13 06:39:58 +00001664 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001665 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001666 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1667 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001668 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001669 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001670}
1671
Richard Smith357362d2011-12-13 06:39:58 +00001672static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1673 QualType SrcType, QualType DestType,
1674 APFloat &Result) {
1675 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001676 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001677 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1678 APFloat::rmNearestTiesToEven, &ignored)
1679 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001680 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001681 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001682}
1683
Richard Smith911e1422012-01-30 22:27:01 +00001684static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1685 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001686 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001687 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001688 APSInt Result = Value;
1689 // Figure out if this is a truncate, extend or noop cast.
1690 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001691 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001692 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001693 return Result;
1694}
1695
Richard Smith357362d2011-12-13 06:39:58 +00001696static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1697 QualType SrcType, const APSInt &Value,
1698 QualType DestType, APFloat &Result) {
1699 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1700 if (Result.convertFromAPInt(Value, Value.isSigned(),
1701 APFloat::rmNearestTiesToEven)
1702 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001703 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001704 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001705}
1706
Richard Smith49ca8aa2013-08-06 07:09:20 +00001707static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1708 APValue &Value, const FieldDecl *FD) {
1709 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1710
1711 if (!Value.isInt()) {
1712 // Trying to store a pointer-cast-to-integer into a bitfield.
1713 // FIXME: In this case, we should provide the diagnostic for casting
1714 // a pointer to an integer.
1715 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001716 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001717 return false;
1718 }
1719
1720 APSInt &Int = Value.getInt();
1721 unsigned OldBitWidth = Int.getBitWidth();
1722 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1723 if (NewBitWidth < OldBitWidth)
1724 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1725 return true;
1726}
1727
Eli Friedman803acb32011-12-22 03:51:45 +00001728static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1729 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001730 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001731 if (!Evaluate(SVal, Info, E))
1732 return false;
1733 if (SVal.isInt()) {
1734 Res = SVal.getInt();
1735 return true;
1736 }
1737 if (SVal.isFloat()) {
1738 Res = SVal.getFloat().bitcastToAPInt();
1739 return true;
1740 }
1741 if (SVal.isVector()) {
1742 QualType VecTy = E->getType();
1743 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1744 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1745 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1746 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1747 Res = llvm::APInt::getNullValue(VecSize);
1748 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1749 APValue &Elt = SVal.getVectorElt(i);
1750 llvm::APInt EltAsInt;
1751 if (Elt.isInt()) {
1752 EltAsInt = Elt.getInt();
1753 } else if (Elt.isFloat()) {
1754 EltAsInt = Elt.getFloat().bitcastToAPInt();
1755 } else {
1756 // Don't try to handle vectors of anything other than int or float
1757 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001758 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001759 return false;
1760 }
1761 unsigned BaseEltSize = EltAsInt.getBitWidth();
1762 if (BigEndian)
1763 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1764 else
1765 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1766 }
1767 return true;
1768 }
1769 // Give up if the input isn't an int, float, or vector. For example, we
1770 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001771 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001772 return false;
1773}
1774
Richard Smith43e77732013-05-07 04:50:00 +00001775/// Perform the given integer operation, which is known to need at most BitWidth
1776/// bits, and check for overflow in the original type (if that type was not an
1777/// unsigned type).
1778template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001779static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1780 const APSInt &LHS, const APSInt &RHS,
1781 unsigned BitWidth, Operation Op,
1782 APSInt &Result) {
1783 if (LHS.isUnsigned()) {
1784 Result = Op(LHS, RHS);
1785 return true;
1786 }
Richard Smith43e77732013-05-07 04:50:00 +00001787
1788 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001789 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001790 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001791 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001792 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001793 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001794 << Result.toString(10) << E->getType();
1795 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001796 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001797 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001798 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001799}
1800
1801/// Perform the given binary integer operation.
1802static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1803 BinaryOperatorKind Opcode, APSInt RHS,
1804 APSInt &Result) {
1805 switch (Opcode) {
1806 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001807 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001808 return false;
1809 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001810 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1811 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001812 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001813 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1814 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001815 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001816 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1817 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001818 case BO_And: Result = LHS & RHS; return true;
1819 case BO_Xor: Result = LHS ^ RHS; return true;
1820 case BO_Or: Result = LHS | RHS; return true;
1821 case BO_Div:
1822 case BO_Rem:
1823 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001824 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001825 return false;
1826 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001827 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1828 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1829 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001830 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1831 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001832 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1833 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001834 return true;
1835 case BO_Shl: {
1836 if (Info.getLangOpts().OpenCL)
1837 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1838 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1839 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1840 RHS.isUnsigned());
1841 else if (RHS.isSigned() && RHS.isNegative()) {
1842 // During constant-folding, a negative shift is an opposite shift. Such
1843 // a shift is not a constant expression.
1844 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1845 RHS = -RHS;
1846 goto shift_right;
1847 }
1848 shift_left:
1849 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1850 // the shifted type.
1851 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1852 if (SA != RHS) {
1853 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1854 << RHS << E->getType() << LHS.getBitWidth();
1855 } else if (LHS.isSigned()) {
1856 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1857 // operand, and must not overflow the corresponding unsigned type.
1858 if (LHS.isNegative())
1859 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1860 else if (LHS.countLeadingZeros() < SA)
1861 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1862 }
1863 Result = LHS << SA;
1864 return true;
1865 }
1866 case BO_Shr: {
1867 if (Info.getLangOpts().OpenCL)
1868 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1869 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1870 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1871 RHS.isUnsigned());
1872 else if (RHS.isSigned() && RHS.isNegative()) {
1873 // During constant-folding, a negative shift is an opposite shift. Such a
1874 // shift is not a constant expression.
1875 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1876 RHS = -RHS;
1877 goto shift_left;
1878 }
1879 shift_right:
1880 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1881 // shifted type.
1882 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1883 if (SA != RHS)
1884 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1885 << RHS << E->getType() << LHS.getBitWidth();
1886 Result = LHS >> SA;
1887 return true;
1888 }
1889
1890 case BO_LT: Result = LHS < RHS; return true;
1891 case BO_GT: Result = LHS > RHS; return true;
1892 case BO_LE: Result = LHS <= RHS; return true;
1893 case BO_GE: Result = LHS >= RHS; return true;
1894 case BO_EQ: Result = LHS == RHS; return true;
1895 case BO_NE: Result = LHS != RHS; return true;
1896 }
1897}
1898
Richard Smith861b5b52013-05-07 23:34:45 +00001899/// Perform the given binary floating-point operation, in-place, on LHS.
1900static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1901 APFloat &LHS, BinaryOperatorKind Opcode,
1902 const APFloat &RHS) {
1903 switch (Opcode) {
1904 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001905 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00001906 return false;
1907 case BO_Mul:
1908 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1909 break;
1910 case BO_Add:
1911 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1912 break;
1913 case BO_Sub:
1914 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1915 break;
1916 case BO_Div:
1917 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1918 break;
1919 }
1920
Richard Smith0c6124b2015-12-03 01:36:22 +00001921 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001922 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001923 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001924 }
Richard Smith861b5b52013-05-07 23:34:45 +00001925 return true;
1926}
1927
Richard Smitha8105bc2012-01-06 16:39:00 +00001928/// Cast an lvalue referring to a base subobject to a derived class, by
1929/// truncating the lvalue's path to the given length.
1930static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1931 const RecordDecl *TruncatedType,
1932 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001933 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001934
1935 // Check we actually point to a derived class object.
1936 if (TruncatedElements == D.Entries.size())
1937 return true;
1938 assert(TruncatedElements >= D.MostDerivedPathLength &&
1939 "not casting to a derived class");
1940 if (!Result.checkSubobject(Info, E, CSK_Derived))
1941 return false;
1942
1943 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001944 const RecordDecl *RD = TruncatedType;
1945 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001946 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001947 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1948 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001949 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001950 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001951 else
Richard Smithd62306a2011-11-10 06:34:14 +00001952 Result.Offset -= Layout.getBaseClassOffset(Base);
1953 RD = Base;
1954 }
Richard Smith027bf112011-11-17 22:56:20 +00001955 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001956 return true;
1957}
1958
John McCalld7bca762012-05-01 00:38:49 +00001959static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001960 const CXXRecordDecl *Derived,
1961 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001962 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001963 if (!RL) {
1964 if (Derived->isInvalidDecl()) return false;
1965 RL = &Info.Ctx.getASTRecordLayout(Derived);
1966 }
1967
Richard Smithd62306a2011-11-10 06:34:14 +00001968 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001969 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001970 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001971}
1972
Richard Smitha8105bc2012-01-06 16:39:00 +00001973static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001974 const CXXRecordDecl *DerivedDecl,
1975 const CXXBaseSpecifier *Base) {
1976 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1977
John McCalld7bca762012-05-01 00:38:49 +00001978 if (!Base->isVirtual())
1979 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001980
Richard Smitha8105bc2012-01-06 16:39:00 +00001981 SubobjectDesignator &D = Obj.Designator;
1982 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001983 return false;
1984
Richard Smitha8105bc2012-01-06 16:39:00 +00001985 // Extract most-derived object and corresponding type.
1986 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1987 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1988 return false;
1989
1990 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001991 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001992 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1993 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001994 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001995 return true;
1996}
1997
Richard Smith84401042013-06-03 05:03:02 +00001998static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1999 QualType Type, LValue &Result) {
2000 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2001 PathE = E->path_end();
2002 PathI != PathE; ++PathI) {
2003 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2004 *PathI))
2005 return false;
2006 Type = (*PathI)->getType();
2007 }
2008 return true;
2009}
2010
Richard Smithd62306a2011-11-10 06:34:14 +00002011/// Update LVal to refer to the given field, which must be a member of the type
2012/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002013static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002014 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002015 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002016 if (!RL) {
2017 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002018 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002019 }
Richard Smithd62306a2011-11-10 06:34:14 +00002020
2021 unsigned I = FD->getFieldIndex();
2022 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00002023 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002024 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002025}
2026
Richard Smith1b78b3d2012-01-25 22:15:11 +00002027/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002028static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002029 LValue &LVal,
2030 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002031 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002032 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002033 return false;
2034 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002035}
2036
Richard Smithd62306a2011-11-10 06:34:14 +00002037/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002038static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2039 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002040 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2041 // extension.
2042 if (Type->isVoidType() || Type->isFunctionType()) {
2043 Size = CharUnits::One();
2044 return true;
2045 }
2046
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002047 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002048 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002049 return false;
2050 }
2051
Richard Smithd62306a2011-11-10 06:34:14 +00002052 if (!Type->isConstantSizeType()) {
2053 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002054 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002055 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002056 return false;
2057 }
2058
2059 Size = Info.Ctx.getTypeSizeInChars(Type);
2060 return true;
2061}
2062
2063/// Update a pointer value to model pointer arithmetic.
2064/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002065/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002066/// \param LVal - The pointer value to be updated.
2067/// \param EltTy - The pointee type represented by LVal.
2068/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002069static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2070 LValue &LVal, QualType EltTy,
2071 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002072 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002073 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002074 return false;
2075
2076 // Compute the new offset in the appropriate width.
2077 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00002078 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00002079 return true;
2080}
2081
Richard Smith66c96992012-02-18 22:04:06 +00002082/// Update an lvalue to refer to a component of a complex number.
2083/// \param Info - Information about the ongoing evaluation.
2084/// \param LVal - The lvalue to be updated.
2085/// \param EltTy - The complex number's component type.
2086/// \param Imag - False for the real component, true for the imaginary.
2087static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2088 LValue &LVal, QualType EltTy,
2089 bool Imag) {
2090 if (Imag) {
2091 CharUnits SizeOfComponent;
2092 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2093 return false;
2094 LVal.Offset += SizeOfComponent;
2095 }
2096 LVal.addComplex(Info, E, EltTy, Imag);
2097 return true;
2098}
2099
Richard Smith27908702011-10-24 17:54:18 +00002100/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002101///
2102/// \param Info Information about the ongoing evaluation.
2103/// \param E An expression to be used when printing diagnostics.
2104/// \param VD The variable whose initializer should be obtained.
2105/// \param Frame The frame in which the variable was created. Must be null
2106/// if this variable is not local to the evaluation.
2107/// \param Result Filled in with a pointer to the value of the variable.
2108static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2109 const VarDecl *VD, CallStackFrame *Frame,
2110 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002111 // If this is a parameter to an active constexpr function call, perform
2112 // argument substitution.
2113 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002114 // Assume arguments of a potential constant expression are unknown
2115 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002116 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002117 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002118 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002119 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002120 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002121 }
Richard Smith3229b742013-05-05 21:17:10 +00002122 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002123 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002124 }
Richard Smith27908702011-10-24 17:54:18 +00002125
Richard Smithd9f663b2013-04-22 15:31:51 +00002126 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002127 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002128 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002129 if (!Result) {
2130 // Assume variables referenced within a lambda's call operator that were
2131 // not declared within the call operator are captures and during checking
2132 // of a potential constant expression, assume they are unknown constant
2133 // expressions.
2134 assert(isLambdaCallOperator(Frame->Callee) &&
2135 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2136 "missing value for local variable");
2137 if (Info.checkingPotentialConstantExpression())
2138 return false;
2139 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002140 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002141 diag::note_unimplemented_constexpr_lambda_feature_ast)
2142 << "captures not currently allowed";
2143 return false;
2144 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002145 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002146 }
2147
Richard Smithd0b4dd62011-12-19 06:19:21 +00002148 // Dig out the initializer, and use the declaration which it's attached to.
2149 const Expr *Init = VD->getAnyInitializer(VD);
2150 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002151 // If we're checking a potential constant expression, the variable could be
2152 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002153 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002154 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002155 return false;
2156 }
2157
Richard Smithd62306a2011-11-10 06:34:14 +00002158 // If we're currently evaluating the initializer of this declaration, use that
2159 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002160 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002161 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002162 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002163 }
2164
Richard Smithcecf1842011-11-01 21:06:14 +00002165 // Never evaluate the initializer of a weak variable. We can't be sure that
2166 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002167 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002168 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002169 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002170 }
Richard Smithcecf1842011-11-01 21:06:14 +00002171
Richard Smithd0b4dd62011-12-19 06:19:21 +00002172 // Check that we can fold the initializer. In C++, we will have already done
2173 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002174 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002175 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002176 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002177 Notes.size() + 1) << VD;
2178 Info.Note(VD->getLocation(), diag::note_declared_at);
2179 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002180 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002181 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002182 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002183 Notes.size() + 1) << VD;
2184 Info.Note(VD->getLocation(), diag::note_declared_at);
2185 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002186 }
Richard Smith27908702011-10-24 17:54:18 +00002187
Richard Smith3229b742013-05-05 21:17:10 +00002188 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002189 return true;
Richard Smith27908702011-10-24 17:54:18 +00002190}
2191
Richard Smith11562c52011-10-28 17:51:58 +00002192static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002193 Qualifiers Quals = T.getQualifiers();
2194 return Quals.hasConst() && !Quals.hasVolatile();
2195}
2196
Richard Smithe97cbd72011-11-11 04:05:33 +00002197/// Get the base index of the given base class within an APValue representing
2198/// the given derived class.
2199static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2200 const CXXRecordDecl *Base) {
2201 Base = Base->getCanonicalDecl();
2202 unsigned Index = 0;
2203 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2204 E = Derived->bases_end(); I != E; ++I, ++Index) {
2205 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2206 return Index;
2207 }
2208
2209 llvm_unreachable("base class missing from derived class's bases list");
2210}
2211
Richard Smith3da88fa2013-04-26 14:36:30 +00002212/// Extract the value of a character from a string literal.
2213static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2214 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002215 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2216 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2217 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002218 const StringLiteral *S = cast<StringLiteral>(Lit);
2219 const ConstantArrayType *CAT =
2220 Info.Ctx.getAsConstantArrayType(S->getType());
2221 assert(CAT && "string literal isn't an array");
2222 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002223 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002224
2225 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002226 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002227 if (Index < S->getLength())
2228 Value = S->getCodeUnit(Index);
2229 return Value;
2230}
2231
Richard Smith3da88fa2013-04-26 14:36:30 +00002232// Expand a string literal into an array of characters.
2233static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2234 APValue &Result) {
2235 const StringLiteral *S = cast<StringLiteral>(Lit);
2236 const ConstantArrayType *CAT =
2237 Info.Ctx.getAsConstantArrayType(S->getType());
2238 assert(CAT && "string literal isn't an array");
2239 QualType CharType = CAT->getElementType();
2240 assert(CharType->isIntegerType() && "unexpected character type");
2241
2242 unsigned Elts = CAT->getSize().getZExtValue();
2243 Result = APValue(APValue::UninitArray(),
2244 std::min(S->getLength(), Elts), Elts);
2245 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2246 CharType->isUnsignedIntegerType());
2247 if (Result.hasArrayFiller())
2248 Result.getArrayFiller() = APValue(Value);
2249 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2250 Value = S->getCodeUnit(I);
2251 Result.getArrayInitializedElt(I) = APValue(Value);
2252 }
2253}
2254
2255// Expand an array so that it has more than Index filled elements.
2256static void expandArray(APValue &Array, unsigned Index) {
2257 unsigned Size = Array.getArraySize();
2258 assert(Index < Size);
2259
2260 // Always at least double the number of elements for which we store a value.
2261 unsigned OldElts = Array.getArrayInitializedElts();
2262 unsigned NewElts = std::max(Index+1, OldElts * 2);
2263 NewElts = std::min(Size, std::max(NewElts, 8u));
2264
2265 // Copy the data across.
2266 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2267 for (unsigned I = 0; I != OldElts; ++I)
2268 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2269 for (unsigned I = OldElts; I != NewElts; ++I)
2270 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2271 if (NewValue.hasArrayFiller())
2272 NewValue.getArrayFiller() = Array.getArrayFiller();
2273 Array.swap(NewValue);
2274}
2275
Richard Smithb01fe402014-09-16 01:24:02 +00002276/// Determine whether a type would actually be read by an lvalue-to-rvalue
2277/// conversion. If it's of class type, we may assume that the copy operation
2278/// is trivial. Note that this is never true for a union type with fields
2279/// (because the copy always "reads" the active member) and always true for
2280/// a non-class type.
2281static bool isReadByLvalueToRvalueConversion(QualType T) {
2282 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2283 if (!RD || (RD->isUnion() && !RD->field_empty()))
2284 return true;
2285 if (RD->isEmpty())
2286 return false;
2287
2288 for (auto *Field : RD->fields())
2289 if (isReadByLvalueToRvalueConversion(Field->getType()))
2290 return true;
2291
2292 for (auto &BaseSpec : RD->bases())
2293 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2294 return true;
2295
2296 return false;
2297}
2298
2299/// Diagnose an attempt to read from any unreadable field within the specified
2300/// type, which might be a class type.
2301static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2302 QualType T) {
2303 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2304 if (!RD)
2305 return false;
2306
2307 if (!RD->hasMutableFields())
2308 return false;
2309
2310 for (auto *Field : RD->fields()) {
2311 // If we're actually going to read this field in some way, then it can't
2312 // be mutable. If we're in a union, then assigning to a mutable field
2313 // (even an empty one) can change the active member, so that's not OK.
2314 // FIXME: Add core issue number for the union case.
2315 if (Field->isMutable() &&
2316 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002317 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002318 Info.Note(Field->getLocation(), diag::note_declared_at);
2319 return true;
2320 }
2321
2322 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2323 return true;
2324 }
2325
2326 for (auto &BaseSpec : RD->bases())
2327 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2328 return true;
2329
2330 // All mutable fields were empty, and thus not actually read.
2331 return false;
2332}
2333
Richard Smith861b5b52013-05-07 23:34:45 +00002334/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002335enum AccessKinds {
2336 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002337 AK_Assign,
2338 AK_Increment,
2339 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002340};
2341
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002342namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002343/// A handle to a complete object (an object that is not a subobject of
2344/// another object).
2345struct CompleteObject {
2346 /// The value of the complete object.
2347 APValue *Value;
2348 /// The type of the complete object.
2349 QualType Type;
2350
Craig Topper36250ad2014-05-12 05:36:57 +00002351 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002352 CompleteObject(APValue *Value, QualType Type)
2353 : Value(Value), Type(Type) {
2354 assert(Value && "missing value for complete object");
2355 }
2356
Aaron Ballman67347662015-02-15 22:00:28 +00002357 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002358};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002359} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002360
Richard Smith3da88fa2013-04-26 14:36:30 +00002361/// Find the designated sub-object of an rvalue.
2362template<typename SubobjectHandler>
2363typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002364findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002365 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002366 if (Sub.Invalid)
2367 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002368 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002369 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002370 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002371 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002372 << handler.AccessKind;
2373 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002374 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002375 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002376 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002377
Richard Smith3229b742013-05-05 21:17:10 +00002378 APValue *O = Obj.Value;
2379 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002380 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002381
Richard Smithd62306a2011-11-10 06:34:14 +00002382 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002383 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2384 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002385 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002386 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002387 return handler.failed();
2388 }
2389
Richard Smith49ca8aa2013-08-06 07:09:20 +00002390 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002391 // If we are reading an object of class type, there may still be more
2392 // things we need to check: if there are any mutable subobjects, we
2393 // cannot perform this read. (This only happens when performing a trivial
2394 // copy or assignment.)
2395 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2396 diagnoseUnreadableFields(Info, E, ObjType))
2397 return handler.failed();
2398
Richard Smith49ca8aa2013-08-06 07:09:20 +00002399 if (!handler.found(*O, ObjType))
2400 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002401
Richard Smith49ca8aa2013-08-06 07:09:20 +00002402 // If we modified a bit-field, truncate it to the right width.
2403 if (handler.AccessKind != AK_Read &&
2404 LastField && LastField->isBitField() &&
2405 !truncateBitfieldValue(Info, E, *O, LastField))
2406 return false;
2407
2408 return true;
2409 }
2410
Craig Topper36250ad2014-05-12 05:36:57 +00002411 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002412 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002413 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002414 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002415 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002416 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002417 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002418 // Note, it should not be possible to form a pointer with a valid
2419 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002420 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002421 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002422 << handler.AccessKind;
2423 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002424 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002425 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002426 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002427
2428 ObjType = CAT->getElementType();
2429
Richard Smith14a94132012-02-17 03:35:37 +00002430 // An array object is represented as either an Array APValue or as an
2431 // LValue which refers to a string literal.
2432 if (O->isLValue()) {
2433 assert(I == N - 1 && "extracting subobject of character?");
2434 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002435 if (handler.AccessKind != AK_Read)
2436 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2437 *O);
2438 else
2439 return handler.foundString(*O, ObjType, Index);
2440 }
2441
2442 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002443 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002444 else if (handler.AccessKind != AK_Read) {
2445 expandArray(*O, Index);
2446 O = &O->getArrayInitializedElt(Index);
2447 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002448 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002449 } else if (ObjType->isAnyComplexType()) {
2450 // Next subobject is a complex number.
2451 uint64_t Index = Sub.Entries[I].ArrayIndex;
2452 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002453 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002454 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002455 << handler.AccessKind;
2456 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002457 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002458 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002459 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002460
2461 bool WasConstQualified = ObjType.isConstQualified();
2462 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2463 if (WasConstQualified)
2464 ObjType.addConst();
2465
Richard Smith66c96992012-02-18 22:04:06 +00002466 assert(I == N - 1 && "extracting subobject of scalar?");
2467 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002468 return handler.found(Index ? O->getComplexIntImag()
2469 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002470 } else {
2471 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002472 return handler.found(Index ? O->getComplexFloatImag()
2473 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002474 }
Richard Smithd62306a2011-11-10 06:34:14 +00002475 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002476 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002477 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002478 << Field;
2479 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002480 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002481 }
2482
Richard Smithd62306a2011-11-10 06:34:14 +00002483 // Next subobject is a class, struct or union field.
2484 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2485 if (RD->isUnion()) {
2486 const FieldDecl *UnionField = O->getUnionField();
2487 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002488 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002489 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002490 << handler.AccessKind << Field << !UnionField << UnionField;
2491 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002492 }
Richard Smithd62306a2011-11-10 06:34:14 +00002493 O = &O->getUnionValue();
2494 } else
2495 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002496
2497 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002498 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002499 if (WasConstQualified && !Field->isMutable())
2500 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002501
2502 if (ObjType.isVolatileQualified()) {
2503 if (Info.getLangOpts().CPlusPlus) {
2504 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002505 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002506 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002507 Info.Note(Field->getLocation(), diag::note_declared_at);
2508 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002509 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002510 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002511 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002512 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002513
2514 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002515 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002516 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002517 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2518 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2519 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002520
2521 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002522 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002523 if (WasConstQualified)
2524 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002525 }
2526 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002527}
2528
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002529namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002530struct ExtractSubobjectHandler {
2531 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002532 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002533
2534 static const AccessKinds AccessKind = AK_Read;
2535
2536 typedef bool result_type;
2537 bool failed() { return false; }
2538 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002539 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002540 return true;
2541 }
2542 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002543 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002544 return true;
2545 }
2546 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002547 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002548 return true;
2549 }
2550 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002551 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002552 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2553 return true;
2554 }
2555};
Richard Smith3229b742013-05-05 21:17:10 +00002556} // end anonymous namespace
2557
Richard Smith3da88fa2013-04-26 14:36:30 +00002558const AccessKinds ExtractSubobjectHandler::AccessKind;
2559
2560/// Extract the designated sub-object of an rvalue.
2561static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002562 const CompleteObject &Obj,
2563 const SubobjectDesignator &Sub,
2564 APValue &Result) {
2565 ExtractSubobjectHandler Handler = { Info, Result };
2566 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002567}
2568
Richard Smith3229b742013-05-05 21:17:10 +00002569namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002570struct ModifySubobjectHandler {
2571 EvalInfo &Info;
2572 APValue &NewVal;
2573 const Expr *E;
2574
2575 typedef bool result_type;
2576 static const AccessKinds AccessKind = AK_Assign;
2577
2578 bool checkConst(QualType QT) {
2579 // Assigning to a const object has undefined behavior.
2580 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002581 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002582 return false;
2583 }
2584 return true;
2585 }
2586
2587 bool failed() { return false; }
2588 bool found(APValue &Subobj, QualType SubobjType) {
2589 if (!checkConst(SubobjType))
2590 return false;
2591 // We've been given ownership of NewVal, so just swap it in.
2592 Subobj.swap(NewVal);
2593 return true;
2594 }
2595 bool found(APSInt &Value, QualType SubobjType) {
2596 if (!checkConst(SubobjType))
2597 return false;
2598 if (!NewVal.isInt()) {
2599 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002600 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002601 return false;
2602 }
2603 Value = NewVal.getInt();
2604 return true;
2605 }
2606 bool found(APFloat &Value, QualType SubobjType) {
2607 if (!checkConst(SubobjType))
2608 return false;
2609 Value = NewVal.getFloat();
2610 return true;
2611 }
2612 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2613 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2614 }
2615};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002616} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002617
Richard Smith3229b742013-05-05 21:17:10 +00002618const AccessKinds ModifySubobjectHandler::AccessKind;
2619
Richard Smith3da88fa2013-04-26 14:36:30 +00002620/// Update the designated sub-object of an rvalue to the given value.
2621static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002622 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002623 const SubobjectDesignator &Sub,
2624 APValue &NewVal) {
2625 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002626 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002627}
2628
Richard Smith84f6dcf2012-02-02 01:16:57 +00002629/// Find the position where two subobject designators diverge, or equivalently
2630/// the length of the common initial subsequence.
2631static unsigned FindDesignatorMismatch(QualType ObjType,
2632 const SubobjectDesignator &A,
2633 const SubobjectDesignator &B,
2634 bool &WasArrayIndex) {
2635 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2636 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002637 if (!ObjType.isNull() &&
2638 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002639 // Next subobject is an array element.
2640 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2641 WasArrayIndex = true;
2642 return I;
2643 }
Richard Smith66c96992012-02-18 22:04:06 +00002644 if (ObjType->isAnyComplexType())
2645 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2646 else
2647 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002648 } else {
2649 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2650 WasArrayIndex = false;
2651 return I;
2652 }
2653 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2654 // Next subobject is a field.
2655 ObjType = FD->getType();
2656 else
2657 // Next subobject is a base class.
2658 ObjType = QualType();
2659 }
2660 }
2661 WasArrayIndex = false;
2662 return I;
2663}
2664
2665/// Determine whether the given subobject designators refer to elements of the
2666/// same array object.
2667static bool AreElementsOfSameArray(QualType ObjType,
2668 const SubobjectDesignator &A,
2669 const SubobjectDesignator &B) {
2670 if (A.Entries.size() != B.Entries.size())
2671 return false;
2672
George Burgess IVa51c4072015-10-16 01:49:01 +00002673 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002674 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2675 // A is a subobject of the array element.
2676 return false;
2677
2678 // If A (and B) designates an array element, the last entry will be the array
2679 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2680 // of length 1' case, and the entire path must match.
2681 bool WasArrayIndex;
2682 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2683 return CommonLength >= A.Entries.size() - IsArray;
2684}
2685
Richard Smith3229b742013-05-05 21:17:10 +00002686/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002687static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2688 AccessKinds AK, const LValue &LVal,
2689 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002690 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002691 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002692 return CompleteObject();
2693 }
2694
Craig Topper36250ad2014-05-12 05:36:57 +00002695 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002696 if (LVal.CallIndex) {
2697 Frame = Info.getCallFrame(LVal.CallIndex);
2698 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002699 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002700 << AK << LVal.Base.is<const ValueDecl*>();
2701 NoteLValueLocation(Info, LVal.Base);
2702 return CompleteObject();
2703 }
Richard Smith3229b742013-05-05 21:17:10 +00002704 }
2705
2706 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2707 // is not a constant expression (even if the object is non-volatile). We also
2708 // apply this rule to C++98, in order to conform to the expected 'volatile'
2709 // semantics.
2710 if (LValType.isVolatileQualified()) {
2711 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002712 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002713 << AK << LValType;
2714 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002715 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002716 return CompleteObject();
2717 }
2718
2719 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002720 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002721 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002722
2723 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2724 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2725 // In C++11, constexpr, non-volatile variables initialized with constant
2726 // expressions are constant expressions too. Inside constexpr functions,
2727 // parameters are constant expressions even if they're non-const.
2728 // In C++1y, objects local to a constant expression (those with a Frame) are
2729 // both readable and writable inside constant expressions.
2730 // In C, such things can also be folded, although they are not ICEs.
2731 const VarDecl *VD = dyn_cast<VarDecl>(D);
2732 if (VD) {
2733 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2734 VD = VDef;
2735 }
2736 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002737 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002738 return CompleteObject();
2739 }
2740
2741 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002742 if (BaseType.isVolatileQualified()) {
2743 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002744 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002745 << AK << 1 << VD;
2746 Info.Note(VD->getLocation(), diag::note_declared_at);
2747 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002748 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002749 }
2750 return CompleteObject();
2751 }
2752
2753 // Unless we're looking at a local variable or argument in a constexpr call,
2754 // the variable we're reading must be const.
2755 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002756 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002757 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2758 // OK, we can read and modify an object if we're in the process of
2759 // evaluating its initializer, because its lifetime began in this
2760 // evaluation.
2761 } else if (AK != AK_Read) {
2762 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002763 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002764 return CompleteObject();
2765 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002766 // OK, we can read this variable.
2767 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002768 // In OpenCL if a variable is in constant address space it is a const value.
2769 if (!(BaseType.isConstQualified() ||
2770 (Info.getLangOpts().OpenCL &&
2771 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002772 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002773 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002774 Info.Note(VD->getLocation(), diag::note_declared_at);
2775 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002776 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002777 }
2778 return CompleteObject();
2779 }
2780 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2781 // We support folding of const floating-point types, in order to make
2782 // static const data members of such types (supported as an extension)
2783 // more useful.
2784 if (Info.getLangOpts().CPlusPlus11) {
2785 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2786 Info.Note(VD->getLocation(), diag::note_declared_at);
2787 } else {
2788 Info.CCEDiag(E);
2789 }
2790 } else {
2791 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002792 if (Info.checkingPotentialConstantExpression() &&
2793 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2794 // The definition of this variable could be constexpr. We can't
2795 // access it right now, but may be able to in future.
2796 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002797 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002798 Info.Note(VD->getLocation(), diag::note_declared_at);
2799 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002800 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002801 }
2802 return CompleteObject();
2803 }
2804 }
2805
2806 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2807 return CompleteObject();
2808 } else {
2809 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2810
2811 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002812 if (const MaterializeTemporaryExpr *MTE =
2813 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2814 assert(MTE->getStorageDuration() == SD_Static &&
2815 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002816
Richard Smithe6c01442013-06-05 00:46:14 +00002817 // Per C++1y [expr.const]p2:
2818 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2819 // - a [...] glvalue of integral or enumeration type that refers to
2820 // a non-volatile const object [...]
2821 // [...]
2822 // - a [...] glvalue of literal type that refers to a non-volatile
2823 // object whose lifetime began within the evaluation of e.
2824 //
2825 // C++11 misses the 'began within the evaluation of e' check and
2826 // instead allows all temporaries, including things like:
2827 // int &&r = 1;
2828 // int x = ++r;
2829 // constexpr int k = r;
2830 // Therefore we use the C++1y rules in C++11 too.
2831 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2832 const ValueDecl *ED = MTE->getExtendingDecl();
2833 if (!(BaseType.isConstQualified() &&
2834 BaseType->isIntegralOrEnumerationType()) &&
2835 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002836 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002837 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2838 return CompleteObject();
2839 }
2840
2841 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2842 assert(BaseVal && "got reference to unevaluated temporary");
2843 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002844 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00002845 return CompleteObject();
2846 }
2847 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002848 BaseVal = Frame->getTemporary(Base);
2849 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002850 }
Richard Smith3229b742013-05-05 21:17:10 +00002851
2852 // Volatile temporary objects cannot be accessed in constant expressions.
2853 if (BaseType.isVolatileQualified()) {
2854 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002855 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002856 << AK << 0;
2857 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2858 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002859 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002860 }
2861 return CompleteObject();
2862 }
2863 }
2864
Richard Smith7525ff62013-05-09 07:14:00 +00002865 // During the construction of an object, it is not yet 'const'.
2866 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2867 // and this doesn't do quite the right thing for const subobjects of the
2868 // object under construction.
2869 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2870 BaseType = Info.Ctx.getCanonicalType(BaseType);
2871 BaseType.removeLocalConst();
2872 }
2873
Richard Smith6d4c6582013-11-05 22:18:15 +00002874 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002875 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002876 //
2877 // FIXME: Not all local state is mutable. Allow local constant subobjects
2878 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002879 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2880 Info.EvalStatus.HasSideEffects) ||
2881 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002882 return CompleteObject();
2883
2884 return CompleteObject(BaseVal, BaseType);
2885}
2886
Richard Smith243ef902013-05-05 23:31:59 +00002887/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2888/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2889/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002890///
2891/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002892/// \param Conv - The expression for which we are performing the conversion.
2893/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002894/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2895/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002896/// \param LVal - The glvalue on which we are attempting to perform this action.
2897/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002898static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002899 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002900 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002901 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002902 return false;
2903
Richard Smith3229b742013-05-05 21:17:10 +00002904 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002905 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002906 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002907 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2908 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2909 // initializer until now for such expressions. Such an expression can't be
2910 // an ICE in C, so this only matters for fold.
2911 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2912 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002913 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002914 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002915 }
Richard Smith3229b742013-05-05 21:17:10 +00002916 APValue Lit;
2917 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2918 return false;
2919 CompleteObject LitObj(&Lit, Base->getType());
2920 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002921 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002922 // We represent a string literal array as an lvalue pointing at the
2923 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002924 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002925 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2926 CompleteObject StrObj(&Str, Base->getType());
2927 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002928 }
Richard Smith11562c52011-10-28 17:51:58 +00002929 }
2930
Richard Smith3229b742013-05-05 21:17:10 +00002931 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2932 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002933}
2934
2935/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002936static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002937 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002938 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002939 return false;
2940
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002941 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002942 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002943 return false;
2944 }
2945
Richard Smith3229b742013-05-05 21:17:10 +00002946 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2947 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002948}
2949
Richard Smith243ef902013-05-05 23:31:59 +00002950static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2951 return T->isSignedIntegerType() &&
2952 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2953}
2954
2955namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002956struct CompoundAssignSubobjectHandler {
2957 EvalInfo &Info;
2958 const Expr *E;
2959 QualType PromotedLHSType;
2960 BinaryOperatorKind Opcode;
2961 const APValue &RHS;
2962
2963 static const AccessKinds AccessKind = AK_Assign;
2964
2965 typedef bool result_type;
2966
2967 bool checkConst(QualType QT) {
2968 // Assigning to a const object has undefined behavior.
2969 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002970 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00002971 return false;
2972 }
2973 return true;
2974 }
2975
2976 bool failed() { return false; }
2977 bool found(APValue &Subobj, QualType SubobjType) {
2978 switch (Subobj.getKind()) {
2979 case APValue::Int:
2980 return found(Subobj.getInt(), SubobjType);
2981 case APValue::Float:
2982 return found(Subobj.getFloat(), SubobjType);
2983 case APValue::ComplexInt:
2984 case APValue::ComplexFloat:
2985 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00002986 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002987 return false;
2988 case APValue::LValue:
2989 return foundPointer(Subobj, SubobjType);
2990 default:
2991 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00002992 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002993 return false;
2994 }
2995 }
2996 bool found(APSInt &Value, QualType SubobjType) {
2997 if (!checkConst(SubobjType))
2998 return false;
2999
3000 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3001 // We don't support compound assignment on integer-cast-to-pointer
3002 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003003 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003004 return false;
3005 }
3006
3007 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3008 SubobjType, Value);
3009 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3010 return false;
3011 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3012 return true;
3013 }
3014 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003015 return checkConst(SubobjType) &&
3016 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3017 Value) &&
3018 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3019 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003020 }
3021 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3022 if (!checkConst(SubobjType))
3023 return false;
3024
3025 QualType PointeeType;
3026 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3027 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003028
3029 if (PointeeType.isNull() || !RHS.isInt() ||
3030 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003031 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003032 return false;
3033 }
3034
Richard Smith861b5b52013-05-07 23:34:45 +00003035 int64_t Offset = getExtValue(RHS.getInt());
3036 if (Opcode == BO_Sub)
3037 Offset = -Offset;
3038
3039 LValue LVal;
3040 LVal.setFrom(Info.Ctx, Subobj);
3041 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3042 return false;
3043 LVal.moveInto(Subobj);
3044 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003045 }
3046 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3047 llvm_unreachable("shouldn't encounter string elements here");
3048 }
3049};
3050} // end anonymous namespace
3051
3052const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3053
3054/// Perform a compound assignment of LVal <op>= RVal.
3055static bool handleCompoundAssignment(
3056 EvalInfo &Info, const Expr *E,
3057 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3058 BinaryOperatorKind Opcode, const APValue &RVal) {
3059 if (LVal.Designator.Invalid)
3060 return false;
3061
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003062 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003063 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003064 return false;
3065 }
3066
3067 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3068 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3069 RVal };
3070 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3071}
3072
3073namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003074struct IncDecSubobjectHandler {
3075 EvalInfo &Info;
3076 const Expr *E;
3077 AccessKinds AccessKind;
3078 APValue *Old;
3079
3080 typedef bool result_type;
3081
3082 bool checkConst(QualType QT) {
3083 // Assigning to a const object has undefined behavior.
3084 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003085 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003086 return false;
3087 }
3088 return true;
3089 }
3090
3091 bool failed() { return false; }
3092 bool found(APValue &Subobj, QualType SubobjType) {
3093 // Stash the old value. Also clear Old, so we don't clobber it later
3094 // if we're post-incrementing a complex.
3095 if (Old) {
3096 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003097 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003098 }
3099
3100 switch (Subobj.getKind()) {
3101 case APValue::Int:
3102 return found(Subobj.getInt(), SubobjType);
3103 case APValue::Float:
3104 return found(Subobj.getFloat(), SubobjType);
3105 case APValue::ComplexInt:
3106 return found(Subobj.getComplexIntReal(),
3107 SubobjType->castAs<ComplexType>()->getElementType()
3108 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3109 case APValue::ComplexFloat:
3110 return found(Subobj.getComplexFloatReal(),
3111 SubobjType->castAs<ComplexType>()->getElementType()
3112 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3113 case APValue::LValue:
3114 return foundPointer(Subobj, SubobjType);
3115 default:
3116 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003117 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003118 return false;
3119 }
3120 }
3121 bool found(APSInt &Value, QualType SubobjType) {
3122 if (!checkConst(SubobjType))
3123 return false;
3124
3125 if (!SubobjType->isIntegerType()) {
3126 // We don't support increment / decrement on integer-cast-to-pointer
3127 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003128 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003129 return false;
3130 }
3131
3132 if (Old) *Old = APValue(Value);
3133
3134 // bool arithmetic promotes to int, and the conversion back to bool
3135 // doesn't reduce mod 2^n, so special-case it.
3136 if (SubobjType->isBooleanType()) {
3137 if (AccessKind == AK_Increment)
3138 Value = 1;
3139 else
3140 Value = !Value;
3141 return true;
3142 }
3143
3144 bool WasNegative = Value.isNegative();
3145 if (AccessKind == AK_Increment) {
3146 ++Value;
3147
3148 if (!WasNegative && Value.isNegative() &&
3149 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3150 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003151 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003152 }
3153 } else {
3154 --Value;
3155
3156 if (WasNegative && !Value.isNegative() &&
3157 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3158 unsigned BitWidth = Value.getBitWidth();
3159 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3160 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003161 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003162 }
3163 }
3164 return true;
3165 }
3166 bool found(APFloat &Value, QualType SubobjType) {
3167 if (!checkConst(SubobjType))
3168 return false;
3169
3170 if (Old) *Old = APValue(Value);
3171
3172 APFloat One(Value.getSemantics(), 1);
3173 if (AccessKind == AK_Increment)
3174 Value.add(One, APFloat::rmNearestTiesToEven);
3175 else
3176 Value.subtract(One, APFloat::rmNearestTiesToEven);
3177 return true;
3178 }
3179 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3180 if (!checkConst(SubobjType))
3181 return false;
3182
3183 QualType PointeeType;
3184 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3185 PointeeType = PT->getPointeeType();
3186 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003187 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003188 return false;
3189 }
3190
3191 LValue LVal;
3192 LVal.setFrom(Info.Ctx, Subobj);
3193 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3194 AccessKind == AK_Increment ? 1 : -1))
3195 return false;
3196 LVal.moveInto(Subobj);
3197 return true;
3198 }
3199 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3200 llvm_unreachable("shouldn't encounter string elements here");
3201 }
3202};
3203} // end anonymous namespace
3204
3205/// Perform an increment or decrement on LVal.
3206static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3207 QualType LValType, bool IsIncrement, APValue *Old) {
3208 if (LVal.Designator.Invalid)
3209 return false;
3210
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003211 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003212 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003213 return false;
3214 }
3215
3216 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3217 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3218 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3219 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3220}
3221
Richard Smithe97cbd72011-11-11 04:05:33 +00003222/// Build an lvalue for the object argument of a member function call.
3223static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3224 LValue &This) {
3225 if (Object->getType()->isPointerType())
3226 return EvaluatePointer(Object, This, Info);
3227
3228 if (Object->isGLValue())
3229 return EvaluateLValue(Object, This, Info);
3230
Richard Smithd9f663b2013-04-22 15:31:51 +00003231 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003232 return EvaluateTemporary(Object, This, Info);
3233
Faisal Valie690b7a2016-07-02 22:34:24 +00003234 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003235 return false;
3236}
3237
3238/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3239/// lvalue referring to the result.
3240///
3241/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003242/// \param LV - An lvalue referring to the base of the member pointer.
3243/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003244/// \param IncludeMember - Specifies whether the member itself is included in
3245/// the resulting LValue subobject designator. This is not possible when
3246/// creating a bound member function.
3247/// \return The field or method declaration to which the member pointer refers,
3248/// or 0 if evaluation fails.
3249static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003250 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003251 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003252 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003253 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003254 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003255 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003256 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003257
3258 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3259 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003260 if (!MemPtr.getDecl()) {
3261 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003262 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003263 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003264 }
Richard Smith253c2a32012-01-27 01:14:48 +00003265
Richard Smith027bf112011-11-17 22:56:20 +00003266 if (MemPtr.isDerivedMember()) {
3267 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003268 // The end of the derived-to-base path for the base object must match the
3269 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003270 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003271 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003272 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003273 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003274 }
Richard Smith027bf112011-11-17 22:56:20 +00003275 unsigned PathLengthToMember =
3276 LV.Designator.Entries.size() - MemPtr.Path.size();
3277 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3278 const CXXRecordDecl *LVDecl = getAsBaseClass(
3279 LV.Designator.Entries[PathLengthToMember + I]);
3280 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003281 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003282 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003283 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003284 }
Richard Smith027bf112011-11-17 22:56:20 +00003285 }
3286
3287 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003288 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003289 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003290 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003291 } else if (!MemPtr.Path.empty()) {
3292 // Extend the LValue path with the member pointer's path.
3293 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3294 MemPtr.Path.size() + IncludeMember);
3295
3296 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003297 if (const PointerType *PT = LVType->getAs<PointerType>())
3298 LVType = PT->getPointeeType();
3299 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3300 assert(RD && "member pointer access on non-class-type expression");
3301 // The first class in the path is that of the lvalue.
3302 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3303 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003304 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003305 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003306 RD = Base;
3307 }
3308 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003309 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3310 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003311 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003312 }
3313
3314 // Add the member. Note that we cannot build bound member functions here.
3315 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003316 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003317 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003318 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003319 } else if (const IndirectFieldDecl *IFD =
3320 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003321 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003322 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003323 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003324 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003325 }
Richard Smith027bf112011-11-17 22:56:20 +00003326 }
3327
3328 return MemPtr.getDecl();
3329}
3330
Richard Smith84401042013-06-03 05:03:02 +00003331static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3332 const BinaryOperator *BO,
3333 LValue &LV,
3334 bool IncludeMember = true) {
3335 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3336
3337 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003338 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003339 MemberPtr MemPtr;
3340 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3341 }
Craig Topper36250ad2014-05-12 05:36:57 +00003342 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003343 }
3344
3345 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3346 BO->getRHS(), IncludeMember);
3347}
3348
Richard Smith027bf112011-11-17 22:56:20 +00003349/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3350/// the provided lvalue, which currently refers to the base object.
3351static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3352 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003353 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003354 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003355 return false;
3356
Richard Smitha8105bc2012-01-06 16:39:00 +00003357 QualType TargetQT = E->getType();
3358 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3359 TargetQT = PT->getPointeeType();
3360
3361 // Check this cast lands within the final derived-to-base subobject path.
3362 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003363 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003364 << D.MostDerivedType << TargetQT;
3365 return false;
3366 }
3367
Richard Smith027bf112011-11-17 22:56:20 +00003368 // Check the type of the final cast. We don't need to check the path,
3369 // since a cast can only be formed if the path is unique.
3370 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003371 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3372 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003373 if (NewEntriesSize == D.MostDerivedPathLength)
3374 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3375 else
Richard Smith027bf112011-11-17 22:56:20 +00003376 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003377 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003378 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003379 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003380 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003381 }
Richard Smith027bf112011-11-17 22:56:20 +00003382
3383 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003384 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003385}
3386
Mike Stump876387b2009-10-27 22:09:17 +00003387namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003388enum EvalStmtResult {
3389 /// Evaluation failed.
3390 ESR_Failed,
3391 /// Hit a 'return' statement.
3392 ESR_Returned,
3393 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003394 ESR_Succeeded,
3395 /// Hit a 'continue' statement.
3396 ESR_Continue,
3397 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003398 ESR_Break,
3399 /// Still scanning for 'case' or 'default' statement.
3400 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003401};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003402}
Richard Smith254a73d2011-10-28 22:34:42 +00003403
Richard Smithd9f663b2013-04-22 15:31:51 +00003404static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3405 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3406 // We don't need to evaluate the initializer for a static local.
3407 if (!VD->hasLocalStorage())
3408 return true;
3409
3410 LValue Result;
3411 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003412 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003413
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003414 const Expr *InitE = VD->getInit();
3415 if (!InitE) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003416 Info.FFDiag(D->getLocStart(), diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00003417 << false << VD->getType();
3418 Val = APValue();
3419 return false;
3420 }
3421
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003422 if (InitE->isValueDependent())
3423 return false;
3424
3425 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003426 // Wipe out any partially-computed value, to allow tracking that this
3427 // evaluation failed.
3428 Val = APValue();
3429 return false;
3430 }
3431 }
3432
3433 return true;
3434}
3435
Richard Smith4e18ca52013-05-06 05:56:11 +00003436/// Evaluate a condition (either a variable declaration or an expression).
3437static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3438 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003439 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003440 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3441 return false;
3442 return EvaluateAsBooleanCondition(Cond, Result, Info);
3443}
3444
Richard Smith89210072016-04-04 23:29:43 +00003445namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003446/// \brief A location where the result (returned value) of evaluating a
3447/// statement should be stored.
3448struct StmtResult {
3449 /// The APValue that should be filled in with the returned value.
3450 APValue &Value;
3451 /// The location containing the result, if any (used to support RVO).
3452 const LValue *Slot;
3453};
Richard Smith89210072016-04-04 23:29:43 +00003454}
Richard Smith52a980a2015-08-28 02:43:42 +00003455
3456static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003457 const Stmt *S,
3458 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003459
3460/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003461static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003462 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003463 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003464 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003465 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003466 case ESR_Break:
3467 return ESR_Succeeded;
3468 case ESR_Succeeded:
3469 case ESR_Continue:
3470 return ESR_Continue;
3471 case ESR_Failed:
3472 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003473 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003474 return ESR;
3475 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003476 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003477}
3478
Richard Smith496ddcf2013-05-12 17:32:42 +00003479/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003480static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003481 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003482 BlockScopeRAII Scope(Info);
3483
Richard Smith496ddcf2013-05-12 17:32:42 +00003484 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003485 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003486 {
3487 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003488 if (const Stmt *Init = SS->getInit()) {
3489 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3490 if (ESR != ESR_Succeeded)
3491 return ESR;
3492 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003493 if (SS->getConditionVariable() &&
3494 !EvaluateDecl(Info, SS->getConditionVariable()))
3495 return ESR_Failed;
3496 if (!EvaluateInteger(SS->getCond(), Value, Info))
3497 return ESR_Failed;
3498 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003499
3500 // Find the switch case corresponding to the value of the condition.
3501 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003502 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003503 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3504 SC = SC->getNextSwitchCase()) {
3505 if (isa<DefaultStmt>(SC)) {
3506 Found = SC;
3507 continue;
3508 }
3509
3510 const CaseStmt *CS = cast<CaseStmt>(SC);
3511 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3512 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3513 : LHS;
3514 if (LHS <= Value && Value <= RHS) {
3515 Found = SC;
3516 break;
3517 }
3518 }
3519
3520 if (!Found)
3521 return ESR_Succeeded;
3522
3523 // Search the switch body for the switch case and evaluate it from there.
3524 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3525 case ESR_Break:
3526 return ESR_Succeeded;
3527 case ESR_Succeeded:
3528 case ESR_Continue:
3529 case ESR_Failed:
3530 case ESR_Returned:
3531 return ESR;
3532 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003533 // This can only happen if the switch case is nested within a statement
3534 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003535 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003536 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003537 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003538 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003539}
3540
Richard Smith254a73d2011-10-28 22:34:42 +00003541// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003542static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003543 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003544 if (!Info.nextStep(S))
3545 return ESR_Failed;
3546
Richard Smith496ddcf2013-05-12 17:32:42 +00003547 // If we're hunting down a 'case' or 'default' label, recurse through
3548 // substatements until we hit the label.
3549 if (Case) {
3550 // FIXME: We don't start the lifetime of objects whose initialization we
3551 // jump over. However, such objects must be of class type with a trivial
3552 // default constructor that initialize all subobjects, so must be empty,
3553 // so this almost never matters.
3554 switch (S->getStmtClass()) {
3555 case Stmt::CompoundStmtClass:
3556 // FIXME: Precompute which substatement of a compound statement we
3557 // would jump to, and go straight there rather than performing a
3558 // linear scan each time.
3559 case Stmt::LabelStmtClass:
3560 case Stmt::AttributedStmtClass:
3561 case Stmt::DoStmtClass:
3562 break;
3563
3564 case Stmt::CaseStmtClass:
3565 case Stmt::DefaultStmtClass:
3566 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003567 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003568 break;
3569
3570 case Stmt::IfStmtClass: {
3571 // FIXME: Precompute which side of an 'if' we would jump to, and go
3572 // straight there rather than scanning both sides.
3573 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003574
3575 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3576 // preceded by our switch label.
3577 BlockScopeRAII Scope(Info);
3578
Richard Smith496ddcf2013-05-12 17:32:42 +00003579 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3580 if (ESR != ESR_CaseNotFound || !IS->getElse())
3581 return ESR;
3582 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3583 }
3584
3585 case Stmt::WhileStmtClass: {
3586 EvalStmtResult ESR =
3587 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3588 if (ESR != ESR_Continue)
3589 return ESR;
3590 break;
3591 }
3592
3593 case Stmt::ForStmtClass: {
3594 const ForStmt *FS = cast<ForStmt>(S);
3595 EvalStmtResult ESR =
3596 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3597 if (ESR != ESR_Continue)
3598 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003599 if (FS->getInc()) {
3600 FullExpressionRAII IncScope(Info);
3601 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3602 return ESR_Failed;
3603 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003604 break;
3605 }
3606
3607 case Stmt::DeclStmtClass:
3608 // FIXME: If the variable has initialization that can't be jumped over,
3609 // bail out of any immediately-surrounding compound-statement too.
3610 default:
3611 return ESR_CaseNotFound;
3612 }
3613 }
3614
Richard Smith254a73d2011-10-28 22:34:42 +00003615 switch (S->getStmtClass()) {
3616 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003617 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003618 // Don't bother evaluating beyond an expression-statement which couldn't
3619 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003620 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003621 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003622 return ESR_Failed;
3623 return ESR_Succeeded;
3624 }
3625
Faisal Valie690b7a2016-07-02 22:34:24 +00003626 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003627 return ESR_Failed;
3628
3629 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003630 return ESR_Succeeded;
3631
Richard Smithd9f663b2013-04-22 15:31:51 +00003632 case Stmt::DeclStmtClass: {
3633 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003634 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003635 // Each declaration initialization is its own full-expression.
3636 // FIXME: This isn't quite right; if we're performing aggregate
3637 // initialization, each braced subexpression is its own full-expression.
3638 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003639 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003640 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003641 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003642 return ESR_Succeeded;
3643 }
3644
Richard Smith357362d2011-12-13 06:39:58 +00003645 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003646 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003647 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003648 if (RetExpr &&
3649 !(Result.Slot
3650 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3651 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003652 return ESR_Failed;
3653 return ESR_Returned;
3654 }
Richard Smith254a73d2011-10-28 22:34:42 +00003655
3656 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003657 BlockScopeRAII Scope(Info);
3658
Richard Smith254a73d2011-10-28 22:34:42 +00003659 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003660 for (const auto *BI : CS->body()) {
3661 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003662 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003663 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003664 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003665 return ESR;
3666 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003667 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003668 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003669
3670 case Stmt::IfStmtClass: {
3671 const IfStmt *IS = cast<IfStmt>(S);
3672
3673 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003674 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003675 if (const Stmt *Init = IS->getInit()) {
3676 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3677 if (ESR != ESR_Succeeded)
3678 return ESR;
3679 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003680 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003681 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003682 return ESR_Failed;
3683
3684 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3685 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3686 if (ESR != ESR_Succeeded)
3687 return ESR;
3688 }
3689 return ESR_Succeeded;
3690 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003691
3692 case Stmt::WhileStmtClass: {
3693 const WhileStmt *WS = cast<WhileStmt>(S);
3694 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003695 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003696 bool Continue;
3697 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3698 Continue))
3699 return ESR_Failed;
3700 if (!Continue)
3701 break;
3702
3703 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3704 if (ESR != ESR_Continue)
3705 return ESR;
3706 }
3707 return ESR_Succeeded;
3708 }
3709
3710 case Stmt::DoStmtClass: {
3711 const DoStmt *DS = cast<DoStmt>(S);
3712 bool Continue;
3713 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003714 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003715 if (ESR != ESR_Continue)
3716 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003717 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003718
Richard Smith08d6a2c2013-07-24 07:11:57 +00003719 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003720 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3721 return ESR_Failed;
3722 } while (Continue);
3723 return ESR_Succeeded;
3724 }
3725
3726 case Stmt::ForStmtClass: {
3727 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003728 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003729 if (FS->getInit()) {
3730 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3731 if (ESR != ESR_Succeeded)
3732 return ESR;
3733 }
3734 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003735 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003736 bool Continue = true;
3737 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3738 FS->getCond(), Continue))
3739 return ESR_Failed;
3740 if (!Continue)
3741 break;
3742
3743 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3744 if (ESR != ESR_Continue)
3745 return ESR;
3746
Richard Smith08d6a2c2013-07-24 07:11:57 +00003747 if (FS->getInc()) {
3748 FullExpressionRAII IncScope(Info);
3749 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3750 return ESR_Failed;
3751 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003752 }
3753 return ESR_Succeeded;
3754 }
3755
Richard Smith896e0d72013-05-06 06:51:17 +00003756 case Stmt::CXXForRangeStmtClass: {
3757 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003758 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003759
3760 // Initialize the __range variable.
3761 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3762 if (ESR != ESR_Succeeded)
3763 return ESR;
3764
3765 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003766 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3767 if (ESR != ESR_Succeeded)
3768 return ESR;
3769 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003770 if (ESR != ESR_Succeeded)
3771 return ESR;
3772
3773 while (true) {
3774 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003775 {
3776 bool Continue = true;
3777 FullExpressionRAII CondExpr(Info);
3778 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3779 return ESR_Failed;
3780 if (!Continue)
3781 break;
3782 }
Richard Smith896e0d72013-05-06 06:51:17 +00003783
3784 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003785 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003786 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3787 if (ESR != ESR_Succeeded)
3788 return ESR;
3789
3790 // Loop body.
3791 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3792 if (ESR != ESR_Continue)
3793 return ESR;
3794
3795 // Increment: ++__begin
3796 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3797 return ESR_Failed;
3798 }
3799
3800 return ESR_Succeeded;
3801 }
3802
Richard Smith496ddcf2013-05-12 17:32:42 +00003803 case Stmt::SwitchStmtClass:
3804 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3805
Richard Smith4e18ca52013-05-06 05:56:11 +00003806 case Stmt::ContinueStmtClass:
3807 return ESR_Continue;
3808
3809 case Stmt::BreakStmtClass:
3810 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003811
3812 case Stmt::LabelStmtClass:
3813 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3814
3815 case Stmt::AttributedStmtClass:
3816 // As a general principle, C++11 attributes can be ignored without
3817 // any semantic impact.
3818 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3819 Case);
3820
3821 case Stmt::CaseStmtClass:
3822 case Stmt::DefaultStmtClass:
3823 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003824 }
3825}
3826
Richard Smithcc36f692011-12-22 02:22:31 +00003827/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3828/// default constructor. If so, we'll fold it whether or not it's marked as
3829/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3830/// so we need special handling.
3831static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003832 const CXXConstructorDecl *CD,
3833 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003834 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3835 return false;
3836
Richard Smith66e05fe2012-01-18 05:21:49 +00003837 // Value-initialization does not call a trivial default constructor, so such a
3838 // call is a core constant expression whether or not the constructor is
3839 // constexpr.
3840 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003841 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003842 // FIXME: If DiagDecl is an implicitly-declared special member function,
3843 // we should be much more explicit about why it's not constexpr.
3844 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3845 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3846 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003847 } else {
3848 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3849 }
3850 }
3851 return true;
3852}
3853
Richard Smith357362d2011-12-13 06:39:58 +00003854/// CheckConstexprFunction - Check that a function can be called in a constant
3855/// expression.
3856static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3857 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003858 const FunctionDecl *Definition,
3859 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003860 // Potential constant expressions can contain calls to declared, but not yet
3861 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003862 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003863 Declaration->isConstexpr())
3864 return false;
3865
Richard Smith0838f3a2013-05-14 05:18:44 +00003866 // Bail out with no diagnostic if the function declaration itself is invalid.
3867 // We will have produced a relevant diagnostic while parsing it.
3868 if (Declaration->isInvalidDecl())
3869 return false;
3870
Richard Smith357362d2011-12-13 06:39:58 +00003871 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003872 if (Definition && Definition->isConstexpr() &&
3873 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003874 return true;
3875
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003876 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003877 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00003878
Richard Smith5179eb72016-06-28 19:03:57 +00003879 // If this function is not constexpr because it is an inherited
3880 // non-constexpr constructor, diagnose that directly.
3881 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
3882 if (CD && CD->isInheritingConstructor()) {
3883 auto *Inherited = CD->getInheritedConstructor().getConstructor();
3884 if (!Inherited->isConstexpr())
3885 DiagDecl = CD = Inherited;
3886 }
3887
3888 // FIXME: If DiagDecl is an implicitly-declared special member function
3889 // or an inheriting constructor, we should be much more explicit about why
3890 // it's not constexpr.
3891 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00003892 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003893 << CD->getInheritedConstructor().getConstructor()->getParent();
3894 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003895 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003896 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00003897 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3898 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003899 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00003900 }
3901 return false;
3902}
3903
Richard Smithbe6dd812014-11-19 21:27:17 +00003904/// Determine if a class has any fields that might need to be copied by a
3905/// trivial copy or move operation.
3906static bool hasFields(const CXXRecordDecl *RD) {
3907 if (!RD || RD->isEmpty())
3908 return false;
3909 for (auto *FD : RD->fields()) {
3910 if (FD->isUnnamedBitfield())
3911 continue;
3912 return true;
3913 }
3914 for (auto &Base : RD->bases())
3915 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3916 return true;
3917 return false;
3918}
3919
Richard Smithd62306a2011-11-10 06:34:14 +00003920namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003921typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003922}
3923
3924/// EvaluateArgs - Evaluate the arguments to a function call.
3925static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3926 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003927 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003928 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003929 I != E; ++I) {
3930 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3931 // If we're checking for a potential constant expression, evaluate all
3932 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00003933 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00003934 return false;
3935 Success = false;
3936 }
3937 }
3938 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003939}
3940
Richard Smith254a73d2011-10-28 22:34:42 +00003941/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003942static bool HandleFunctionCall(SourceLocation CallLoc,
3943 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003944 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003945 EvalInfo &Info, APValue &Result,
3946 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003947 ArgVector ArgValues(Args.size());
3948 if (!EvaluateArgs(Args, ArgValues, Info))
3949 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003950
Richard Smith253c2a32012-01-27 01:14:48 +00003951 if (!Info.CheckCallLimit(CallLoc))
3952 return false;
3953
3954 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003955
3956 // For a trivial copy or move assignment, perform an APValue copy. This is
3957 // essential for unions, where the operations performed by the assignment
3958 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003959 //
3960 // Skip this for non-union classes with no fields; in that case, the defaulted
3961 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003962 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003963 if (MD && MD->isDefaulted() &&
3964 (MD->getParent()->isUnion() ||
3965 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003966 assert(This &&
3967 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3968 LValue RHS;
3969 RHS.setFrom(Info.Ctx, ArgValues[0]);
3970 APValue RHSValue;
3971 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3972 RHS, RHSValue))
3973 return false;
3974 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3975 RHSValue))
3976 return false;
3977 This->moveInto(Result);
3978 return true;
3979 }
3980
Richard Smith52a980a2015-08-28 02:43:42 +00003981 StmtResult Ret = {Result, ResultSlot};
3982 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003983 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003984 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003985 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00003986 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003987 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003988 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003989}
3990
Richard Smithd62306a2011-11-10 06:34:14 +00003991/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00003992static bool HandleConstructorCall(const Expr *E, const LValue &This,
3993 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00003994 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003995 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00003996 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00003997 if (!Info.CheckCallLimit(CallLoc))
3998 return false;
3999
Richard Smith3607ffe2012-02-13 03:54:03 +00004000 const CXXRecordDecl *RD = Definition->getParent();
4001 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004002 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004003 return false;
4004 }
4005
Richard Smith5179eb72016-06-28 19:03:57 +00004006 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004007
Richard Smith52a980a2015-08-28 02:43:42 +00004008 // FIXME: Creating an APValue just to hold a nonexistent return value is
4009 // wasteful.
4010 APValue RetVal;
4011 StmtResult Ret = {RetVal, nullptr};
4012
Richard Smith5179eb72016-06-28 19:03:57 +00004013 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004014 if (Definition->isDelegatingConstructor()) {
4015 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004016 {
4017 FullExpressionRAII InitScope(Info);
4018 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4019 return false;
4020 }
Richard Smith52a980a2015-08-28 02:43:42 +00004021 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004022 }
4023
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004024 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004025 // essential for unions (or classes with anonymous union members), where the
4026 // operations performed by the constructor cannot be represented by
4027 // ctor-initializers.
4028 //
4029 // Skip this for empty non-union classes; we should not perform an
4030 // lvalue-to-rvalue conversion on them because their copy constructor does not
4031 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004032 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004033 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004034 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004035 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004036 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004037 return handleLValueToRValueConversion(
4038 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4039 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004040 }
4041
4042 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004043 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004044 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004045 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004046
John McCalld7bca762012-05-01 00:38:49 +00004047 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004048 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4049
Richard Smith08d6a2c2013-07-24 07:11:57 +00004050 // A scope for temporaries lifetime-extended by reference members.
4051 BlockScopeRAII LifetimeExtendedScope(Info);
4052
Richard Smith253c2a32012-01-27 01:14:48 +00004053 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004054 unsigned BasesSeen = 0;
4055#ifndef NDEBUG
4056 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4057#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004058 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004059 LValue Subobject = This;
4060 APValue *Value = &Result;
4061
4062 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004063 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004064 if (I->isBaseInitializer()) {
4065 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004066#ifndef NDEBUG
4067 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004068 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004069 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4070 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4071 "base class initializers not in expected order");
4072 ++BaseIt;
4073#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004074 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004075 BaseType->getAsCXXRecordDecl(), &Layout))
4076 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004077 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004078 } else if ((FD = I->getMember())) {
4079 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004080 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004081 if (RD->isUnion()) {
4082 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004083 Value = &Result.getUnionValue();
4084 } else {
4085 Value = &Result.getStructField(FD->getFieldIndex());
4086 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004087 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004088 // Walk the indirect field decl's chain to find the object to initialize,
4089 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004090 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004091 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004092 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4093 // Switch the union field if it differs. This happens if we had
4094 // preceding zero-initialization, and we're now initializing a union
4095 // subobject other than the first.
4096 // FIXME: In this case, the values of the other subobjects are
4097 // specified, since zero-initialization sets all padding bits to zero.
4098 if (Value->isUninit() ||
4099 (Value->isUnion() && Value->getUnionField() != FD)) {
4100 if (CD->isUnion())
4101 *Value = APValue(FD);
4102 else
4103 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004104 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004105 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004106 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004107 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004108 if (CD->isUnion())
4109 Value = &Value->getUnionValue();
4110 else
4111 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004112 }
Richard Smithd62306a2011-11-10 06:34:14 +00004113 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004114 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004115 }
Richard Smith253c2a32012-01-27 01:14:48 +00004116
Richard Smith08d6a2c2013-07-24 07:11:57 +00004117 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004118 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4119 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004120 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004121 // If we're checking for a potential constant expression, evaluate all
4122 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004123 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004124 return false;
4125 Success = false;
4126 }
Richard Smithd62306a2011-11-10 06:34:14 +00004127 }
4128
Richard Smithd9f663b2013-04-22 15:31:51 +00004129 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004130 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004131}
4132
Richard Smith5179eb72016-06-28 19:03:57 +00004133static bool HandleConstructorCall(const Expr *E, const LValue &This,
4134 ArrayRef<const Expr*> Args,
4135 const CXXConstructorDecl *Definition,
4136 EvalInfo &Info, APValue &Result) {
4137 ArgVector ArgValues(Args.size());
4138 if (!EvaluateArgs(Args, ArgValues, Info))
4139 return false;
4140
4141 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4142 Info, Result);
4143}
4144
Eli Friedman9a156e52008-11-12 09:44:48 +00004145//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004146// Generic Evaluation
4147//===----------------------------------------------------------------------===//
4148namespace {
4149
Aaron Ballman68af21c2014-01-03 19:26:43 +00004150template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004151class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004152 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004153private:
Richard Smith52a980a2015-08-28 02:43:42 +00004154 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004155 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004156 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004157 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004158 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004159 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004160 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004161
Richard Smith17100ba2012-02-16 02:46:34 +00004162 // Check whether a conditional operator with a non-constant condition is a
4163 // potential constant expression. If neither arm is a potential constant
4164 // expression, then the conditional operator is not either.
4165 template<typename ConditionalOperator>
4166 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004167 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004168
4169 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004170 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004171 {
Richard Smith17100ba2012-02-16 02:46:34 +00004172 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004173 StmtVisitorTy::Visit(E->getFalseExpr());
4174 if (Diag.empty())
4175 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004176 }
Richard Smith17100ba2012-02-16 02:46:34 +00004177
George Burgess IV8c892b52016-05-25 22:31:54 +00004178 {
4179 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004180 Diag.clear();
4181 StmtVisitorTy::Visit(E->getTrueExpr());
4182 if (Diag.empty())
4183 return;
4184 }
4185
4186 Error(E, diag::note_constexpr_conditional_never_const);
4187 }
4188
4189
4190 template<typename ConditionalOperator>
4191 bool HandleConditionalOperator(const ConditionalOperator *E) {
4192 bool BoolResult;
4193 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004194 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004195 CheckPotentialConstantConditional(E);
4196 return false;
4197 }
4198
4199 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4200 return StmtVisitorTy::Visit(EvalExpr);
4201 }
4202
Peter Collingbournee9200682011-05-13 03:29:01 +00004203protected:
4204 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004205 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004206 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4207
Richard Smith92b1ce02011-12-12 09:28:41 +00004208 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004209 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004210 }
4211
Aaron Ballman68af21c2014-01-03 19:26:43 +00004212 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004213
4214public:
4215 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4216
4217 EvalInfo &getEvalInfo() { return Info; }
4218
Richard Smithf57d8cb2011-12-09 22:58:01 +00004219 /// Report an evaluation error. This should only be called when an error is
4220 /// first discovered. When propagating an error, just return false.
4221 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004222 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004223 return false;
4224 }
4225 bool Error(const Expr *E) {
4226 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4227 }
4228
Aaron Ballman68af21c2014-01-03 19:26:43 +00004229 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004230 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004231 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004232 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004233 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004234 }
4235
Aaron Ballman68af21c2014-01-03 19:26:43 +00004236 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004237 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004238 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004239 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004240 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004241 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004242 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004243 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004244 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004245 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004246 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004247 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004248 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004249 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004250 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004251 // The initializer may not have been parsed yet, or might be erroneous.
4252 if (!E->getExpr())
4253 return Error(E);
4254 return StmtVisitorTy::Visit(E->getExpr());
4255 }
Richard Smith5894a912011-12-19 22:12:41 +00004256 // We cannot create any objects for which cleanups are required, so there is
4257 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004258 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004259 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004260
Aaron Ballman68af21c2014-01-03 19:26:43 +00004261 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004262 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4263 return static_cast<Derived*>(this)->VisitCastExpr(E);
4264 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004265 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004266 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4267 return static_cast<Derived*>(this)->VisitCastExpr(E);
4268 }
4269
Aaron Ballman68af21c2014-01-03 19:26:43 +00004270 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004271 switch (E->getOpcode()) {
4272 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004273 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004274
4275 case BO_Comma:
4276 VisitIgnoredValue(E->getLHS());
4277 return StmtVisitorTy::Visit(E->getRHS());
4278
4279 case BO_PtrMemD:
4280 case BO_PtrMemI: {
4281 LValue Obj;
4282 if (!HandleMemberPointerAccess(Info, E, Obj))
4283 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004284 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004285 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004286 return false;
4287 return DerivedSuccess(Result, E);
4288 }
4289 }
4290 }
4291
Aaron Ballman68af21c2014-01-03 19:26:43 +00004292 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004293 // Evaluate and cache the common expression. We treat it as a temporary,
4294 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004295 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004296 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004297 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004298
Richard Smith17100ba2012-02-16 02:46:34 +00004299 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004300 }
4301
Aaron Ballman68af21c2014-01-03 19:26:43 +00004302 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004303 bool IsBcpCall = false;
4304 // If the condition (ignoring parens) is a __builtin_constant_p call,
4305 // the result is a constant expression if it can be folded without
4306 // side-effects. This is an important GNU extension. See GCC PR38377
4307 // for discussion.
4308 if (const CallExpr *CallCE =
4309 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004310 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004311 IsBcpCall = true;
4312
4313 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4314 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004315 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004316 return false;
4317
Richard Smith6d4c6582013-11-05 22:18:15 +00004318 FoldConstant Fold(Info, IsBcpCall);
4319 if (!HandleConditionalOperator(E)) {
4320 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004321 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004322 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004323
4324 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004325 }
4326
Aaron Ballman68af21c2014-01-03 19:26:43 +00004327 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004328 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4329 return DerivedSuccess(*Value, E);
4330
4331 const Expr *Source = E->getSourceExpr();
4332 if (!Source)
4333 return Error(E);
4334 if (Source == E) { // sanity checking.
4335 assert(0 && "OpaqueValueExpr recursively refers to itself");
4336 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004337 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004338 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004339 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004340
Aaron Ballman68af21c2014-01-03 19:26:43 +00004341 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004342 APValue Result;
4343 if (!handleCallExpr(E, Result, nullptr))
4344 return false;
4345 return DerivedSuccess(Result, E);
4346 }
4347
4348 bool handleCallExpr(const CallExpr *E, APValue &Result,
4349 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004350 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004351 QualType CalleeType = Callee->getType();
4352
Craig Topper36250ad2014-05-12 05:36:57 +00004353 const FunctionDecl *FD = nullptr;
4354 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004355 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004356 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004357
Richard Smithe97cbd72011-11-11 04:05:33 +00004358 // Extract function decl and 'this' pointer from the callee.
4359 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004360 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004361 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4362 // Explicit bound member calls, such as x.f() or p->g();
4363 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004364 return false;
4365 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004366 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004367 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004368 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4369 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004370 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4371 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004372 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004373 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004374 return Error(Callee);
4375
4376 FD = dyn_cast<FunctionDecl>(Member);
4377 if (!FD)
4378 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004379 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004380 LValue Call;
4381 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004382 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004383
Richard Smitha8105bc2012-01-06 16:39:00 +00004384 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004385 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004386 FD = dyn_cast_or_null<FunctionDecl>(
4387 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004388 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004389 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004390
4391 // Overloaded operator calls to member functions are represented as normal
4392 // calls with '*this' as the first argument.
4393 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4394 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004395 // FIXME: When selecting an implicit conversion for an overloaded
4396 // operator delete, we sometimes try to evaluate calls to conversion
4397 // operators without a 'this' parameter!
4398 if (Args.empty())
4399 return Error(E);
4400
Richard Smithe97cbd72011-11-11 04:05:33 +00004401 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4402 return false;
4403 This = &ThisVal;
4404 Args = Args.slice(1);
4405 }
4406
4407 // Don't call function pointers which have been cast to some other type.
4408 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004409 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004410 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004411 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004412
Richard Smith47b34932012-02-01 02:39:43 +00004413 if (This && !This->checkSubobject(Info, E, CSK_This))
4414 return false;
4415
Richard Smith3607ffe2012-02-13 03:54:03 +00004416 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4417 // calls to such functions in constant expressions.
4418 if (This && !HasQualifier &&
4419 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4420 return Error(E, diag::note_constexpr_virtual_call);
4421
Craig Topper36250ad2014-05-12 05:36:57 +00004422 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004423 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004424
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004425 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004426 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4427 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004428 return false;
4429
Richard Smith52a980a2015-08-28 02:43:42 +00004430 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004431 }
4432
Aaron Ballman68af21c2014-01-03 19:26:43 +00004433 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004434 return StmtVisitorTy::Visit(E->getInitializer());
4435 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004436 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004437 if (E->getNumInits() == 0)
4438 return DerivedZeroInitialization(E);
4439 if (E->getNumInits() == 1)
4440 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004441 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004442 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004443 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004444 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004445 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004446 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004447 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004448 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004449 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004450 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004451 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004452
Richard Smithd62306a2011-11-10 06:34:14 +00004453 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004454 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004455 assert(!E->isArrow() && "missing call to bound member function?");
4456
Richard Smith2e312c82012-03-03 22:46:17 +00004457 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004458 if (!Evaluate(Val, Info, E->getBase()))
4459 return false;
4460
4461 QualType BaseTy = E->getBase()->getType();
4462
4463 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004464 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004465 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004466 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004467 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4468
Richard Smith3229b742013-05-05 21:17:10 +00004469 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004470 SubobjectDesignator Designator(BaseTy);
4471 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004472
Richard Smith3229b742013-05-05 21:17:10 +00004473 APValue Result;
4474 return extractSubobject(Info, E, Obj, Designator, Result) &&
4475 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004476 }
4477
Aaron Ballman68af21c2014-01-03 19:26:43 +00004478 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004479 switch (E->getCastKind()) {
4480 default:
4481 break;
4482
Richard Smitha23ab512013-05-23 00:30:41 +00004483 case CK_AtomicToNonAtomic: {
4484 APValue AtomicVal;
4485 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4486 return false;
4487 return DerivedSuccess(AtomicVal, E);
4488 }
4489
Richard Smith11562c52011-10-28 17:51:58 +00004490 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004491 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004492 return StmtVisitorTy::Visit(E->getSubExpr());
4493
4494 case CK_LValueToRValue: {
4495 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004496 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4497 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004498 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004499 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004500 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004501 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004502 return false;
4503 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004504 }
4505 }
4506
Richard Smithf57d8cb2011-12-09 22:58:01 +00004507 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004508 }
4509
Aaron Ballman68af21c2014-01-03 19:26:43 +00004510 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004511 return VisitUnaryPostIncDec(UO);
4512 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004513 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004514 return VisitUnaryPostIncDec(UO);
4515 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004516 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004517 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004518 return Error(UO);
4519
4520 LValue LVal;
4521 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4522 return false;
4523 APValue RVal;
4524 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4525 UO->isIncrementOp(), &RVal))
4526 return false;
4527 return DerivedSuccess(RVal, UO);
4528 }
4529
Aaron Ballman68af21c2014-01-03 19:26:43 +00004530 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004531 // We will have checked the full-expressions inside the statement expression
4532 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004533 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004534 return Error(E);
4535
Richard Smith08d6a2c2013-07-24 07:11:57 +00004536 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004537 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004538 if (CS->body_empty())
4539 return true;
4540
Richard Smith51f03172013-06-20 03:00:05 +00004541 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4542 BE = CS->body_end();
4543 /**/; ++BI) {
4544 if (BI + 1 == BE) {
4545 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4546 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004547 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004548 diag::note_constexpr_stmt_expr_unsupported);
4549 return false;
4550 }
4551 return this->Visit(FinalExpr);
4552 }
4553
4554 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004555 StmtResult Result = { ReturnValue, nullptr };
4556 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004557 if (ESR != ESR_Succeeded) {
4558 // FIXME: If the statement-expression terminated due to 'return',
4559 // 'break', or 'continue', it would be nice to propagate that to
4560 // the outer statement evaluation rather than bailing out.
4561 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004562 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004563 diag::note_constexpr_stmt_expr_unsupported);
4564 return false;
4565 }
4566 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004567
4568 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004569 }
4570
Richard Smith4a678122011-10-24 18:44:57 +00004571 /// Visit a value which is evaluated, but whose value is ignored.
4572 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004573 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004574 }
David Majnemere9807b22016-02-26 04:23:19 +00004575
4576 /// Potentially visit a MemberExpr's base expression.
4577 void VisitIgnoredBaseExpression(const Expr *E) {
4578 // While MSVC doesn't evaluate the base expression, it does diagnose the
4579 // presence of side-effecting behavior.
4580 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4581 return;
4582 VisitIgnoredValue(E);
4583 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004584};
4585
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004586}
Peter Collingbournee9200682011-05-13 03:29:01 +00004587
4588//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004589// Common base class for lvalue and temporary evaluation.
4590//===----------------------------------------------------------------------===//
4591namespace {
4592template<class Derived>
4593class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004594 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004595protected:
4596 LValue &Result;
4597 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004598 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004599
4600 bool Success(APValue::LValueBase B) {
4601 Result.set(B);
4602 return true;
4603 }
4604
4605public:
4606 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4607 ExprEvaluatorBaseTy(Info), Result(Result) {}
4608
Richard Smith2e312c82012-03-03 22:46:17 +00004609 bool Success(const APValue &V, const Expr *E) {
4610 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004611 return true;
4612 }
Richard Smith027bf112011-11-17 22:56:20 +00004613
Richard Smith027bf112011-11-17 22:56:20 +00004614 bool VisitMemberExpr(const MemberExpr *E) {
4615 // Handle non-static data members.
4616 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004617 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004618 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004619 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004620 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004621 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004622 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004623 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004624 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004625 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004626 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004627 BaseTy = E->getBase()->getType();
4628 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004629 if (!EvalOK) {
4630 if (!this->Info.allowInvalidBaseExpr())
4631 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004632 Result.setInvalid(E);
4633 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004634 }
Richard Smith027bf112011-11-17 22:56:20 +00004635
Richard Smith1b78b3d2012-01-25 22:15:11 +00004636 const ValueDecl *MD = E->getMemberDecl();
4637 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4638 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4639 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4640 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004641 if (!HandleLValueMember(this->Info, E, Result, FD))
4642 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004643 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004644 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4645 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004646 } else
4647 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004648
Richard Smith1b78b3d2012-01-25 22:15:11 +00004649 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004650 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004651 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004652 RefValue))
4653 return false;
4654 return Success(RefValue, E);
4655 }
4656 return true;
4657 }
4658
4659 bool VisitBinaryOperator(const BinaryOperator *E) {
4660 switch (E->getOpcode()) {
4661 default:
4662 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4663
4664 case BO_PtrMemD:
4665 case BO_PtrMemI:
4666 return HandleMemberPointerAccess(this->Info, E, Result);
4667 }
4668 }
4669
4670 bool VisitCastExpr(const CastExpr *E) {
4671 switch (E->getCastKind()) {
4672 default:
4673 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4674
4675 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004676 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004677 if (!this->Visit(E->getSubExpr()))
4678 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004679
4680 // Now figure out the necessary offset to add to the base LV to get from
4681 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004682 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4683 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004684 }
4685 }
4686};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004687}
Richard Smith027bf112011-11-17 22:56:20 +00004688
4689//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004690// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004691//
4692// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4693// function designators (in C), decl references to void objects (in C), and
4694// temporaries (if building with -Wno-address-of-temporary).
4695//
4696// LValue evaluation produces values comprising a base expression of one of the
4697// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004698// - Declarations
4699// * VarDecl
4700// * FunctionDecl
4701// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004702// * CompoundLiteralExpr in C
4703// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004704// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004705// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004706// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004707// * ObjCEncodeExpr
4708// * AddrLabelExpr
4709// * BlockExpr
4710// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004711// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004712// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004713// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004714// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4715// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004716// * A MaterializeTemporaryExpr that has static storage duration, with no
4717// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004718// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004719//===----------------------------------------------------------------------===//
4720namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004721class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004722 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004723public:
Richard Smith027bf112011-11-17 22:56:20 +00004724 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4725 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004726
Richard Smith11562c52011-10-28 17:51:58 +00004727 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004728 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004729
Peter Collingbournee9200682011-05-13 03:29:01 +00004730 bool VisitDeclRefExpr(const DeclRefExpr *E);
4731 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004732 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004733 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4734 bool VisitMemberExpr(const MemberExpr *E);
4735 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4736 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004737 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004738 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004739 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4740 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004741 bool VisitUnaryReal(const UnaryOperator *E);
4742 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004743 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4744 return VisitUnaryPreIncDec(UO);
4745 }
4746 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4747 return VisitUnaryPreIncDec(UO);
4748 }
Richard Smith3229b742013-05-05 21:17:10 +00004749 bool VisitBinAssign(const BinaryOperator *BO);
4750 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004751
Peter Collingbournee9200682011-05-13 03:29:01 +00004752 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004753 switch (E->getCastKind()) {
4754 default:
Richard Smith027bf112011-11-17 22:56:20 +00004755 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004756
Eli Friedmance3e02a2011-10-11 00:13:24 +00004757 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004758 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004759 if (!Visit(E->getSubExpr()))
4760 return false;
4761 Result.Designator.setInvalid();
4762 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004763
Richard Smith027bf112011-11-17 22:56:20 +00004764 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004765 if (!Visit(E->getSubExpr()))
4766 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004767 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004768 }
4769 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004770};
4771} // end anonymous namespace
4772
Richard Smith11562c52011-10-28 17:51:58 +00004773/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004774/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004775/// * function designators in C, and
4776/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004777/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004778static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4779 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004780 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004781 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004782}
4783
Peter Collingbournee9200682011-05-13 03:29:01 +00004784bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004785 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004786 return Success(FD);
4787 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004788 return VisitVarDecl(E, VD);
4789 return Error(E);
4790}
Richard Smith733237d2011-10-24 23:14:33 +00004791
Richard Smith11562c52011-10-28 17:51:58 +00004792bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004793 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004794 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4795 Frame = Info.CurrentCall;
4796
Richard Smithfec09922011-11-01 16:57:24 +00004797 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004798 if (Frame) {
4799 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004800 return true;
4801 }
Richard Smithce40ad62011-11-12 22:28:03 +00004802 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004803 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004804
Richard Smith3229b742013-05-05 21:17:10 +00004805 APValue *V;
4806 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004807 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004808 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004809 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00004810 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004811 return false;
4812 }
Richard Smith3229b742013-05-05 21:17:10 +00004813 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004814}
4815
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004816bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4817 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004818 // Walk through the expression to find the materialized temporary itself.
4819 SmallVector<const Expr *, 2> CommaLHSs;
4820 SmallVector<SubobjectAdjustment, 2> Adjustments;
4821 const Expr *Inner = E->GetTemporaryExpr()->
4822 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004823
Richard Smith84401042013-06-03 05:03:02 +00004824 // If we passed any comma operators, evaluate their LHSs.
4825 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4826 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4827 return false;
4828
Richard Smithe6c01442013-06-05 00:46:14 +00004829 // A materialized temporary with static storage duration can appear within the
4830 // result of a constant expression evaluation, so we need to preserve its
4831 // value for use outside this evaluation.
4832 APValue *Value;
4833 if (E->getStorageDuration() == SD_Static) {
4834 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004835 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004836 Result.set(E);
4837 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004838 Value = &Info.CurrentCall->
4839 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004840 Result.set(E, Info.CurrentCall->Index);
4841 }
4842
Richard Smithea4ad5d2013-06-06 08:19:16 +00004843 QualType Type = Inner->getType();
4844
Richard Smith84401042013-06-03 05:03:02 +00004845 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004846 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4847 (E->getStorageDuration() == SD_Static &&
4848 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4849 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004850 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004851 }
Richard Smith84401042013-06-03 05:03:02 +00004852
4853 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004854 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4855 --I;
4856 switch (Adjustments[I].Kind) {
4857 case SubobjectAdjustment::DerivedToBaseAdjustment:
4858 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4859 Type, Result))
4860 return false;
4861 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4862 break;
4863
4864 case SubobjectAdjustment::FieldAdjustment:
4865 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4866 return false;
4867 Type = Adjustments[I].Field->getType();
4868 break;
4869
4870 case SubobjectAdjustment::MemberPointerAdjustment:
4871 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4872 Adjustments[I].Ptr.RHS))
4873 return false;
4874 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4875 break;
4876 }
4877 }
4878
4879 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004880}
4881
Peter Collingbournee9200682011-05-13 03:29:01 +00004882bool
4883LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004884 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4885 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4886 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004887 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004888}
4889
Richard Smith6e525142011-12-27 12:18:28 +00004890bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004891 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004892 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004893
Faisal Valie690b7a2016-07-02 22:34:24 +00004894 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00004895 << E->getExprOperand()->getType()
4896 << E->getExprOperand()->getSourceRange();
4897 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004898}
4899
Francois Pichet0066db92012-04-16 04:08:35 +00004900bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4901 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004902}
Francois Pichet0066db92012-04-16 04:08:35 +00004903
Peter Collingbournee9200682011-05-13 03:29:01 +00004904bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004905 // Handle static data members.
4906 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004907 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004908 return VisitVarDecl(E, VD);
4909 }
4910
Richard Smith254a73d2011-10-28 22:34:42 +00004911 // Handle static member functions.
4912 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4913 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004914 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004915 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004916 }
4917 }
4918
Richard Smithd62306a2011-11-10 06:34:14 +00004919 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004920 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004921}
4922
Peter Collingbournee9200682011-05-13 03:29:01 +00004923bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004924 // FIXME: Deal with vectors as array subscript bases.
4925 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004926 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004927
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004928 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004929 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004930
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004931 APSInt Index;
4932 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004933 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004934
Richard Smith861b5b52013-05-07 23:34:45 +00004935 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4936 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004937}
Eli Friedman9a156e52008-11-12 09:44:48 +00004938
Peter Collingbournee9200682011-05-13 03:29:01 +00004939bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004940 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004941}
4942
Richard Smith66c96992012-02-18 22:04:06 +00004943bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4944 if (!Visit(E->getSubExpr()))
4945 return false;
4946 // __real is a no-op on scalar lvalues.
4947 if (E->getSubExpr()->getType()->isAnyComplexType())
4948 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4949 return true;
4950}
4951
4952bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4953 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4954 "lvalue __imag__ on scalar?");
4955 if (!Visit(E->getSubExpr()))
4956 return false;
4957 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4958 return true;
4959}
4960
Richard Smith243ef902013-05-05 23:31:59 +00004961bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004962 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004963 return Error(UO);
4964
4965 if (!this->Visit(UO->getSubExpr()))
4966 return false;
4967
Richard Smith243ef902013-05-05 23:31:59 +00004968 return handleIncDec(
4969 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004970 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004971}
4972
4973bool LValueExprEvaluator::VisitCompoundAssignOperator(
4974 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004975 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004976 return Error(CAO);
4977
Richard Smith3229b742013-05-05 21:17:10 +00004978 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004979
4980 // The overall lvalue result is the result of evaluating the LHS.
4981 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00004982 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004983 Evaluate(RHS, this->Info, CAO->getRHS());
4984 return false;
4985 }
4986
Richard Smith3229b742013-05-05 21:17:10 +00004987 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4988 return false;
4989
Richard Smith43e77732013-05-07 04:50:00 +00004990 return handleCompoundAssignment(
4991 this->Info, CAO,
4992 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4993 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004994}
4995
4996bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004997 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004998 return Error(E);
4999
Richard Smith3229b742013-05-05 21:17:10 +00005000 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005001
5002 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005003 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005004 Evaluate(NewVal, this->Info, E->getRHS());
5005 return false;
5006 }
5007
Richard Smith3229b742013-05-05 21:17:10 +00005008 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5009 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005010
5011 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005012 NewVal);
5013}
5014
Eli Friedman9a156e52008-11-12 09:44:48 +00005015//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005016// Pointer Evaluation
5017//===----------------------------------------------------------------------===//
5018
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005019namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005020class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005021 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005022 LValue &Result;
5023
Peter Collingbournee9200682011-05-13 03:29:01 +00005024 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005025 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005026 return true;
5027 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005028public:
Mike Stump11289f42009-09-09 15:08:12 +00005029
John McCall45d55e42010-05-07 21:00:08 +00005030 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005031 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005032
Richard Smith2e312c82012-03-03 22:46:17 +00005033 bool Success(const APValue &V, const Expr *E) {
5034 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005035 return true;
5036 }
Richard Smithfddd3842011-12-30 21:15:51 +00005037 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005038 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00005039 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005040
John McCall45d55e42010-05-07 21:00:08 +00005041 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005042 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005043 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005044 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005045 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005046 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005047 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005048 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005049 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005050 bool VisitCallExpr(const CallExpr *E);
5051 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005052 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005053 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005054 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005055 }
Richard Smithd62306a2011-11-10 06:34:14 +00005056 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005057 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005058 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005059 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005060 if (!Info.CurrentCall->This) {
5061 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005062 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005063 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005064 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005065 return false;
5066 }
Richard Smithd62306a2011-11-10 06:34:14 +00005067 Result = *Info.CurrentCall->This;
5068 return true;
5069 }
John McCallc07a0c72011-02-17 10:25:35 +00005070
Eli Friedman449fe542009-03-23 04:56:01 +00005071 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005072};
Chris Lattner05706e882008-07-11 18:11:29 +00005073} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005074
John McCall45d55e42010-05-07 21:00:08 +00005075static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005076 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005077 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005078}
5079
John McCall45d55e42010-05-07 21:00:08 +00005080bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005081 if (E->getOpcode() != BO_Add &&
5082 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005083 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005084
Chris Lattner05706e882008-07-11 18:11:29 +00005085 const Expr *PExp = E->getLHS();
5086 const Expr *IExp = E->getRHS();
5087 if (IExp->getType()->isPointerType())
5088 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005089
Richard Smith253c2a32012-01-27 01:14:48 +00005090 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005091 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005092 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005093
John McCall45d55e42010-05-07 21:00:08 +00005094 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005095 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005096 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005097
5098 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005099 if (E->getOpcode() == BO_Sub)
5100 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005101
Ted Kremenek28831752012-08-23 20:46:57 +00005102 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005103 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5104 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005105}
Eli Friedman9a156e52008-11-12 09:44:48 +00005106
John McCall45d55e42010-05-07 21:00:08 +00005107bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5108 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005109}
Mike Stump11289f42009-09-09 15:08:12 +00005110
Peter Collingbournee9200682011-05-13 03:29:01 +00005111bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5112 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005113
Eli Friedman847a2bc2009-12-27 05:43:15 +00005114 switch (E->getCastKind()) {
5115 default:
5116 break;
5117
John McCalle3027922010-08-25 11:45:40 +00005118 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005119 case CK_CPointerToObjCPointerCast:
5120 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005121 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005122 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005123 if (!Visit(SubExpr))
5124 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005125 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5126 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5127 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005128 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005129 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005130 if (SubExpr->getType()->isVoidPointerType())
5131 CCEDiag(E, diag::note_constexpr_invalid_cast)
5132 << 3 << SubExpr->getType();
5133 else
5134 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5135 }
Richard Smith96e0c102011-11-04 02:25:55 +00005136 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005137
Anders Carlsson18275092010-10-31 20:41:46 +00005138 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005139 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005140 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005141 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005142 if (!Result.Base && Result.Offset.isZero())
5143 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005144
Richard Smithd62306a2011-11-10 06:34:14 +00005145 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005146 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005147 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5148 castAs<PointerType>()->getPointeeType(),
5149 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005150
Richard Smith027bf112011-11-17 22:56:20 +00005151 case CK_BaseToDerived:
5152 if (!Visit(E->getSubExpr()))
5153 return false;
5154 if (!Result.Base && Result.Offset.isZero())
5155 return true;
5156 return HandleBaseToDerivedCast(Info, E, Result);
5157
Richard Smith0b0a0b62011-10-29 20:57:55 +00005158 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005159 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005160 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005161
John McCalle3027922010-08-25 11:45:40 +00005162 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005163 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5164
Richard Smith2e312c82012-03-03 22:46:17 +00005165 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005166 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005167 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005168
John McCall45d55e42010-05-07 21:00:08 +00005169 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005170 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5171 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005172 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005173 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005174 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005175 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005176 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005177 return true;
5178 } else {
5179 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005180 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005181 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005182 }
5183 }
John McCalle3027922010-08-25 11:45:40 +00005184 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005185 if (SubExpr->isGLValue()) {
5186 if (!EvaluateLValue(SubExpr, Result, Info))
5187 return false;
5188 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005189 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005190 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005191 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005192 return false;
5193 }
Richard Smith96e0c102011-11-04 02:25:55 +00005194 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005195 if (const ConstantArrayType *CAT
5196 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5197 Result.addArray(Info, E, CAT);
5198 else
5199 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005200 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005201
John McCalle3027922010-08-25 11:45:40 +00005202 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005203 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005204 }
5205
Richard Smith11562c52011-10-28 17:51:58 +00005206 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005207}
Chris Lattner05706e882008-07-11 18:11:29 +00005208
Hal Finkel0dd05d42014-10-03 17:18:37 +00005209static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5210 // C++ [expr.alignof]p3:
5211 // When alignof is applied to a reference type, the result is the
5212 // alignment of the referenced type.
5213 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5214 T = Ref->getPointeeType();
5215
5216 // __alignof is defined to return the preferred alignment.
5217 return Info.Ctx.toCharUnitsFromBits(
5218 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5219}
5220
5221static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5222 E = E->IgnoreParens();
5223
5224 // The kinds of expressions that we have special-case logic here for
5225 // should be kept up to date with the special checks for those
5226 // expressions in Sema.
5227
5228 // alignof decl is always accepted, even if it doesn't make sense: we default
5229 // to 1 in those cases.
5230 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5231 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5232 /*RefAsPointee*/true);
5233
5234 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5235 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5236 /*RefAsPointee*/true);
5237
5238 return GetAlignOfType(Info, E->getType());
5239}
5240
Peter Collingbournee9200682011-05-13 03:29:01 +00005241bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005242 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005243 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005244
Alp Tokera724cff2013-12-28 21:59:02 +00005245 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005246 case Builtin::BI__builtin_addressof:
5247 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005248 case Builtin::BI__builtin_assume_aligned: {
5249 // We need to be very careful here because: if the pointer does not have the
5250 // asserted alignment, then the behavior is undefined, and undefined
5251 // behavior is non-constant.
5252 if (!EvaluatePointer(E->getArg(0), Result, Info))
5253 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005254
Hal Finkel0dd05d42014-10-03 17:18:37 +00005255 LValue OffsetResult(Result);
5256 APSInt Alignment;
5257 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5258 return false;
5259 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5260
5261 if (E->getNumArgs() > 2) {
5262 APSInt Offset;
5263 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5264 return false;
5265
5266 int64_t AdditionalOffset = -getExtValue(Offset);
5267 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5268 }
5269
5270 // If there is a base object, then it must have the correct alignment.
5271 if (OffsetResult.Base) {
5272 CharUnits BaseAlignment;
5273 if (const ValueDecl *VD =
5274 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5275 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5276 } else {
5277 BaseAlignment =
5278 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5279 }
5280
5281 if (BaseAlignment < Align) {
5282 Result.Designator.setInvalid();
5283 // FIXME: Quantities here cast to integers because the plural modifier
5284 // does not work on APSInts yet.
5285 CCEDiag(E->getArg(0),
5286 diag::note_constexpr_baa_insufficient_alignment) << 0
5287 << (int) BaseAlignment.getQuantity()
5288 << (unsigned) getExtValue(Alignment);
5289 return false;
5290 }
5291 }
5292
5293 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005294 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005295 Result.Designator.setInvalid();
5296 APSInt Offset(64, false);
5297 Offset = OffsetResult.Offset.getQuantity();
5298
5299 if (OffsetResult.Base)
5300 CCEDiag(E->getArg(0),
5301 diag::note_constexpr_baa_insufficient_alignment) << 1
5302 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5303 else
5304 CCEDiag(E->getArg(0),
5305 diag::note_constexpr_baa_value_insufficient_alignment)
5306 << Offset << (unsigned) getExtValue(Alignment);
5307
5308 return false;
5309 }
5310
5311 return true;
5312 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005313 default:
5314 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5315 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005316}
Chris Lattner05706e882008-07-11 18:11:29 +00005317
5318//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005319// Member Pointer Evaluation
5320//===----------------------------------------------------------------------===//
5321
5322namespace {
5323class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005324 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005325 MemberPtr &Result;
5326
5327 bool Success(const ValueDecl *D) {
5328 Result = MemberPtr(D);
5329 return true;
5330 }
5331public:
5332
5333 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5334 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5335
Richard Smith2e312c82012-03-03 22:46:17 +00005336 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005337 Result.setFrom(V);
5338 return true;
5339 }
Richard Smithfddd3842011-12-30 21:15:51 +00005340 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005341 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005342 }
5343
5344 bool VisitCastExpr(const CastExpr *E);
5345 bool VisitUnaryAddrOf(const UnaryOperator *E);
5346};
5347} // end anonymous namespace
5348
5349static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5350 EvalInfo &Info) {
5351 assert(E->isRValue() && E->getType()->isMemberPointerType());
5352 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5353}
5354
5355bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5356 switch (E->getCastKind()) {
5357 default:
5358 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5359
5360 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005361 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005362 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005363
5364 case CK_BaseToDerivedMemberPointer: {
5365 if (!Visit(E->getSubExpr()))
5366 return false;
5367 if (E->path_empty())
5368 return true;
5369 // Base-to-derived member pointer casts store the path in derived-to-base
5370 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5371 // the wrong end of the derived->base arc, so stagger the path by one class.
5372 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5373 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5374 PathI != PathE; ++PathI) {
5375 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5376 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5377 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005378 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005379 }
5380 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5381 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005382 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005383 return true;
5384 }
5385
5386 case CK_DerivedToBaseMemberPointer:
5387 if (!Visit(E->getSubExpr()))
5388 return false;
5389 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5390 PathE = E->path_end(); PathI != PathE; ++PathI) {
5391 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5392 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5393 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005394 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005395 }
5396 return true;
5397 }
5398}
5399
5400bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5401 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5402 // member can be formed.
5403 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5404}
5405
5406//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005407// Record Evaluation
5408//===----------------------------------------------------------------------===//
5409
5410namespace {
5411 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005412 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005413 const LValue &This;
5414 APValue &Result;
5415 public:
5416
5417 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5418 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5419
Richard Smith2e312c82012-03-03 22:46:17 +00005420 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005421 Result = V;
5422 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005423 }
Richard Smithb8348f52016-05-12 22:16:28 +00005424 bool ZeroInitialization(const Expr *E) {
5425 return ZeroInitialization(E, E->getType());
5426 }
5427 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005428
Richard Smith52a980a2015-08-28 02:43:42 +00005429 bool VisitCallExpr(const CallExpr *E) {
5430 return handleCallExpr(E, Result, &This);
5431 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005432 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005433 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005434 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5435 return VisitCXXConstructExpr(E, E->getType());
5436 }
Richard Smith5179eb72016-06-28 19:03:57 +00005437 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005438 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005439 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005440 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005441}
Richard Smithd62306a2011-11-10 06:34:14 +00005442
Richard Smithfddd3842011-12-30 21:15:51 +00005443/// Perform zero-initialization on an object of non-union class type.
5444/// C++11 [dcl.init]p5:
5445/// To zero-initialize an object or reference of type T means:
5446/// [...]
5447/// -- if T is a (possibly cv-qualified) non-union class type,
5448/// each non-static data member and each base-class subobject is
5449/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005450static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5451 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005452 const LValue &This, APValue &Result) {
5453 assert(!RD->isUnion() && "Expected non-union class type");
5454 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5455 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005456 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005457
John McCalld7bca762012-05-01 00:38:49 +00005458 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005459 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5460
5461 if (CD) {
5462 unsigned Index = 0;
5463 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005464 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005465 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5466 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005467 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5468 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005469 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005470 Result.getStructBase(Index)))
5471 return false;
5472 }
5473 }
5474
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005475 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005476 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005477 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005478 continue;
5479
5480 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005481 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005482 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005483
David Blaikie2d7c57e2012-04-30 02:36:29 +00005484 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005485 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005486 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005487 return false;
5488 }
5489
5490 return true;
5491}
5492
Richard Smithb8348f52016-05-12 22:16:28 +00005493bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5494 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005495 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005496 if (RD->isUnion()) {
5497 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5498 // object's first non-static named data member is zero-initialized
5499 RecordDecl::field_iterator I = RD->field_begin();
5500 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005501 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005502 return true;
5503 }
5504
5505 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005506 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005507 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005508 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005509 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005510 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005511 }
5512
Richard Smith5d108602012-02-17 00:44:16 +00005513 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005514 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005515 return false;
5516 }
5517
Richard Smitha8105bc2012-01-06 16:39:00 +00005518 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005519}
5520
Richard Smithe97cbd72011-11-11 04:05:33 +00005521bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5522 switch (E->getCastKind()) {
5523 default:
5524 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5525
5526 case CK_ConstructorConversion:
5527 return Visit(E->getSubExpr());
5528
5529 case CK_DerivedToBase:
5530 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005531 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005532 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005533 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005534 if (!DerivedObject.isStruct())
5535 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005536
5537 // Derived-to-base rvalue conversion: just slice off the derived part.
5538 APValue *Value = &DerivedObject;
5539 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5540 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5541 PathE = E->path_end(); PathI != PathE; ++PathI) {
5542 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5543 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5544 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5545 RD = Base;
5546 }
5547 Result = *Value;
5548 return true;
5549 }
5550 }
5551}
5552
Richard Smithd62306a2011-11-10 06:34:14 +00005553bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5554 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005555 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005556 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5557
5558 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005559 const FieldDecl *Field = E->getInitializedFieldInUnion();
5560 Result = APValue(Field);
5561 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005562 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005563
5564 // If the initializer list for a union does not contain any elements, the
5565 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005566 // FIXME: The element should be initialized from an initializer list.
5567 // Is this difference ever observable for initializer lists which
5568 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005569 ImplicitValueInitExpr VIE(Field->getType());
5570 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5571
Richard Smithd62306a2011-11-10 06:34:14 +00005572 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005573 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5574 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005575
5576 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5577 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5578 isa<CXXDefaultInitExpr>(InitExpr));
5579
Richard Smithb228a862012-02-15 02:18:13 +00005580 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005581 }
5582
Richard Smith872307e2016-03-08 22:17:41 +00005583 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005584 if (Result.isUninit())
5585 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5586 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005587 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005588 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005589
5590 // Initialize base classes.
5591 if (CXXRD) {
5592 for (const auto &Base : CXXRD->bases()) {
5593 assert(ElementNo < E->getNumInits() && "missing init for base class");
5594 const Expr *Init = E->getInit(ElementNo);
5595
5596 LValue Subobject = This;
5597 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5598 return false;
5599
5600 APValue &FieldVal = Result.getStructBase(ElementNo);
5601 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00005602 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00005603 return false;
5604 Success = false;
5605 }
5606 ++ElementNo;
5607 }
5608 }
5609
5610 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005611 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005612 // Anonymous bit-fields are not considered members of the class for
5613 // purposes of aggregate initialization.
5614 if (Field->isUnnamedBitfield())
5615 continue;
5616
5617 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005618
Richard Smith253c2a32012-01-27 01:14:48 +00005619 bool HaveInit = ElementNo < E->getNumInits();
5620
5621 // FIXME: Diagnostics here should point to the end of the initializer
5622 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005623 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005624 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005625 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005626
5627 // Perform an implicit value-initialization for members beyond the end of
5628 // the initializer list.
5629 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005630 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005631
Richard Smith852c9db2013-04-20 22:23:05 +00005632 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5633 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5634 isa<CXXDefaultInitExpr>(Init));
5635
Richard Smith49ca8aa2013-08-06 07:09:20 +00005636 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5637 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5638 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005639 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00005640 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005641 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005642 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005643 }
5644 }
5645
Richard Smith253c2a32012-01-27 01:14:48 +00005646 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005647}
5648
Richard Smithb8348f52016-05-12 22:16:28 +00005649bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5650 QualType T) {
5651 // Note that E's type is not necessarily the type of our class here; we might
5652 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005653 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005654 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5655
Richard Smithfddd3842011-12-30 21:15:51 +00005656 bool ZeroInit = E->requiresZeroInitialization();
5657 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005658 // If we've already performed zero-initialization, we're already done.
5659 if (!Result.isUninit())
5660 return true;
5661
Richard Smithda3f4fd2014-03-05 23:32:50 +00005662 // We can get here in two different ways:
5663 // 1) We're performing value-initialization, and should zero-initialize
5664 // the object, or
5665 // 2) We're performing default-initialization of an object with a trivial
5666 // constexpr default constructor, in which case we should start the
5667 // lifetimes of all the base subobjects (there can be no data member
5668 // subobjects in this case) per [basic.life]p1.
5669 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005670 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005671 }
5672
Craig Topper36250ad2014-05-12 05:36:57 +00005673 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005674 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005675
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005676 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005677 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005678
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005679 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005680 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005681 if (const MaterializeTemporaryExpr *ME
5682 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5683 return Visit(ME->GetTemporaryExpr());
5684
Richard Smithb8348f52016-05-12 22:16:28 +00005685 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005686 return false;
5687
Craig Topper5fc8fc22014-08-27 06:28:36 +00005688 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00005689 return HandleConstructorCall(E, This, Args,
5690 cast<CXXConstructorDecl>(Definition), Info,
5691 Result);
5692}
5693
5694bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
5695 const CXXInheritedCtorInitExpr *E) {
5696 if (!Info.CurrentCall) {
5697 assert(Info.checkingPotentialConstantExpression());
5698 return false;
5699 }
5700
5701 const CXXConstructorDecl *FD = E->getConstructor();
5702 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
5703 return false;
5704
5705 const FunctionDecl *Definition = nullptr;
5706 auto Body = FD->getBody(Definition);
5707
5708 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5709 return false;
5710
5711 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005712 cast<CXXConstructorDecl>(Definition), Info,
5713 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005714}
5715
Richard Smithcc1b96d2013-06-12 22:31:48 +00005716bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5717 const CXXStdInitializerListExpr *E) {
5718 const ConstantArrayType *ArrayType =
5719 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5720
5721 LValue Array;
5722 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5723 return false;
5724
5725 // Get a pointer to the first element of the array.
5726 Array.addArray(Info, E, ArrayType);
5727
5728 // FIXME: Perform the checks on the field types in SemaInit.
5729 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5730 RecordDecl::field_iterator Field = Record->field_begin();
5731 if (Field == Record->field_end())
5732 return Error(E);
5733
5734 // Start pointer.
5735 if (!Field->getType()->isPointerType() ||
5736 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5737 ArrayType->getElementType()))
5738 return Error(E);
5739
5740 // FIXME: What if the initializer_list type has base classes, etc?
5741 Result = APValue(APValue::UninitStruct(), 0, 2);
5742 Array.moveInto(Result.getStructField(0));
5743
5744 if (++Field == Record->field_end())
5745 return Error(E);
5746
5747 if (Field->getType()->isPointerType() &&
5748 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5749 ArrayType->getElementType())) {
5750 // End pointer.
5751 if (!HandleLValueArrayAdjustment(Info, E, Array,
5752 ArrayType->getElementType(),
5753 ArrayType->getSize().getZExtValue()))
5754 return false;
5755 Array.moveInto(Result.getStructField(1));
5756 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5757 // Length.
5758 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5759 else
5760 return Error(E);
5761
5762 if (++Field != Record->field_end())
5763 return Error(E);
5764
5765 return true;
5766}
5767
Richard Smithd62306a2011-11-10 06:34:14 +00005768static bool EvaluateRecord(const Expr *E, const LValue &This,
5769 APValue &Result, EvalInfo &Info) {
5770 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005771 "can't evaluate expression as a record rvalue");
5772 return RecordExprEvaluator(Info, This, Result).Visit(E);
5773}
5774
5775//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005776// Temporary Evaluation
5777//
5778// Temporaries are represented in the AST as rvalues, but generally behave like
5779// lvalues. The full-object of which the temporary is a subobject is implicitly
5780// materialized so that a reference can bind to it.
5781//===----------------------------------------------------------------------===//
5782namespace {
5783class TemporaryExprEvaluator
5784 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5785public:
5786 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5787 LValueExprEvaluatorBaseTy(Info, Result) {}
5788
5789 /// Visit an expression which constructs the value of this temporary.
5790 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005791 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005792 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5793 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005794 }
5795
5796 bool VisitCastExpr(const CastExpr *E) {
5797 switch (E->getCastKind()) {
5798 default:
5799 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5800
5801 case CK_ConstructorConversion:
5802 return VisitConstructExpr(E->getSubExpr());
5803 }
5804 }
5805 bool VisitInitListExpr(const InitListExpr *E) {
5806 return VisitConstructExpr(E);
5807 }
5808 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5809 return VisitConstructExpr(E);
5810 }
5811 bool VisitCallExpr(const CallExpr *E) {
5812 return VisitConstructExpr(E);
5813 }
Richard Smith513955c2014-12-17 19:24:30 +00005814 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5815 return VisitConstructExpr(E);
5816 }
Richard Smith027bf112011-11-17 22:56:20 +00005817};
5818} // end anonymous namespace
5819
5820/// Evaluate an expression of record type as a temporary.
5821static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005822 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005823 return TemporaryExprEvaluator(Info, Result).Visit(E);
5824}
5825
5826//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005827// Vector Evaluation
5828//===----------------------------------------------------------------------===//
5829
5830namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005831 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005832 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005833 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005834 public:
Mike Stump11289f42009-09-09 15:08:12 +00005835
Richard Smith2d406342011-10-22 21:10:00 +00005836 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5837 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005838
Craig Topper9798b932015-09-29 04:30:05 +00005839 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005840 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5841 // FIXME: remove this APValue copy.
5842 Result = APValue(V.data(), V.size());
5843 return true;
5844 }
Richard Smith2e312c82012-03-03 22:46:17 +00005845 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005846 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005847 Result = V;
5848 return true;
5849 }
Richard Smithfddd3842011-12-30 21:15:51 +00005850 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005851
Richard Smith2d406342011-10-22 21:10:00 +00005852 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005853 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005854 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005855 bool VisitInitListExpr(const InitListExpr *E);
5856 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005857 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005858 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005859 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005860 };
5861} // end anonymous namespace
5862
5863static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005864 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005865 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005866}
5867
George Burgess IV533ff002015-12-11 00:23:35 +00005868bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005869 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005870 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005871
Richard Smith161f09a2011-12-06 22:44:34 +00005872 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005873 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005874
Eli Friedmanc757de22011-03-25 00:43:55 +00005875 switch (E->getCastKind()) {
5876 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005877 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005878 if (SETy->isIntegerType()) {
5879 APSInt IntResult;
5880 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00005881 return false;
5882 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005883 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00005884 APFloat FloatResult(0.0);
5885 if (!EvaluateFloat(SE, FloatResult, Info))
5886 return false;
5887 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005888 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005889 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005890 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005891
5892 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005893 SmallVector<APValue, 4> Elts(NElts, Val);
5894 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005895 }
Eli Friedman803acb32011-12-22 03:51:45 +00005896 case CK_BitCast: {
5897 // Evaluate the operand into an APInt we can extract from.
5898 llvm::APInt SValInt;
5899 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5900 return false;
5901 // Extract the elements
5902 QualType EltTy = VTy->getElementType();
5903 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5904 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5905 SmallVector<APValue, 4> Elts;
5906 if (EltTy->isRealFloatingType()) {
5907 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005908 unsigned FloatEltSize = EltSize;
5909 if (&Sem == &APFloat::x87DoubleExtended)
5910 FloatEltSize = 80;
5911 for (unsigned i = 0; i < NElts; i++) {
5912 llvm::APInt Elt;
5913 if (BigEndian)
5914 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5915 else
5916 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005917 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005918 }
5919 } else if (EltTy->isIntegerType()) {
5920 for (unsigned i = 0; i < NElts; i++) {
5921 llvm::APInt Elt;
5922 if (BigEndian)
5923 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5924 else
5925 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5926 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5927 }
5928 } else {
5929 return Error(E);
5930 }
5931 return Success(Elts, E);
5932 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005933 default:
Richard Smith11562c52011-10-28 17:51:58 +00005934 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005935 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005936}
5937
Richard Smith2d406342011-10-22 21:10:00 +00005938bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005939VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005940 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005941 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005942 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005943
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005944 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005945 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005946
Eli Friedmanb9c71292012-01-03 23:24:20 +00005947 // The number of initializers can be less than the number of
5948 // vector elements. For OpenCL, this can be due to nested vector
5949 // initialization. For GCC compatibility, missing trailing elements
5950 // should be initialized with zeroes.
5951 unsigned CountInits = 0, CountElts = 0;
5952 while (CountElts < NumElements) {
5953 // Handle nested vector initialization.
5954 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005955 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005956 APValue v;
5957 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5958 return Error(E);
5959 unsigned vlen = v.getVectorLength();
5960 for (unsigned j = 0; j < vlen; j++)
5961 Elements.push_back(v.getVectorElt(j));
5962 CountElts += vlen;
5963 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005964 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005965 if (CountInits < NumInits) {
5966 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005967 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005968 } else // trailing integer zero.
5969 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5970 Elements.push_back(APValue(sInt));
5971 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005972 } else {
5973 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005974 if (CountInits < NumInits) {
5975 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005976 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005977 } else // trailing float zero.
5978 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5979 Elements.push_back(APValue(f));
5980 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005981 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005982 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005983 }
Richard Smith2d406342011-10-22 21:10:00 +00005984 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005985}
5986
Richard Smith2d406342011-10-22 21:10:00 +00005987bool
Richard Smithfddd3842011-12-30 21:15:51 +00005988VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005989 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005990 QualType EltTy = VT->getElementType();
5991 APValue ZeroElement;
5992 if (EltTy->isIntegerType())
5993 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5994 else
5995 ZeroElement =
5996 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5997
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005998 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005999 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006000}
6001
Richard Smith2d406342011-10-22 21:10:00 +00006002bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006003 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006004 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006005}
6006
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006007//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006008// Array Evaluation
6009//===----------------------------------------------------------------------===//
6010
6011namespace {
6012 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006013 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006014 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006015 APValue &Result;
6016 public:
6017
Richard Smithd62306a2011-11-10 06:34:14 +00006018 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6019 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006020
6021 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006022 assert((V.isArray() || V.isLValue()) &&
6023 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006024 Result = V;
6025 return true;
6026 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006027
Richard Smithfddd3842011-12-30 21:15:51 +00006028 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006029 const ConstantArrayType *CAT =
6030 Info.Ctx.getAsConstantArrayType(E->getType());
6031 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006032 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006033
6034 Result = APValue(APValue::UninitArray(), 0,
6035 CAT->getSize().getZExtValue());
6036 if (!Result.hasArrayFiller()) return true;
6037
Richard Smithfddd3842011-12-30 21:15:51 +00006038 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006039 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006040 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006041 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006042 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006043 }
6044
Richard Smith52a980a2015-08-28 02:43:42 +00006045 bool VisitCallExpr(const CallExpr *E) {
6046 return handleCallExpr(E, Result, &This);
6047 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006048 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006049 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006050 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6051 const LValue &Subobject,
6052 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006053 };
6054} // end anonymous namespace
6055
Richard Smithd62306a2011-11-10 06:34:14 +00006056static bool EvaluateArray(const Expr *E, const LValue &This,
6057 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006058 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006059 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006060}
6061
6062bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6063 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6064 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006065 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006066
Richard Smithca2cfbf2011-12-22 01:07:19 +00006067 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6068 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006069 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006070 LValue LV;
6071 if (!EvaluateLValue(E->getInit(0), LV, Info))
6072 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006073 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006074 LV.moveInto(Val);
6075 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006076 }
6077
Richard Smith253c2a32012-01-27 01:14:48 +00006078 bool Success = true;
6079
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006080 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6081 "zero-initialized array shouldn't have any initialized elts");
6082 APValue Filler;
6083 if (Result.isArray() && Result.hasArrayFiller())
6084 Filler = Result.getArrayFiller();
6085
Richard Smith9543c5e2013-04-22 14:44:29 +00006086 unsigned NumEltsToInit = E->getNumInits();
6087 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006088 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006089
6090 // If the initializer might depend on the array index, run it for each
6091 // array element. For now, just whitelist non-class value-initialization.
6092 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6093 NumEltsToInit = NumElts;
6094
6095 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006096
6097 // If the array was previously zero-initialized, preserve the
6098 // zero-initialized values.
6099 if (!Filler.isUninit()) {
6100 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6101 Result.getArrayInitializedElt(I) = Filler;
6102 if (Result.hasArrayFiller())
6103 Result.getArrayFiller() = Filler;
6104 }
6105
Richard Smithd62306a2011-11-10 06:34:14 +00006106 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006107 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006108 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6109 const Expr *Init =
6110 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006111 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006112 Info, Subobject, Init) ||
6113 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006114 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006115 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006116 return false;
6117 Success = false;
6118 }
Richard Smithd62306a2011-11-10 06:34:14 +00006119 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006120
Richard Smith9543c5e2013-04-22 14:44:29 +00006121 if (!Result.hasArrayFiller())
6122 return Success;
6123
6124 // If we get here, we have a trivial filler, which we can just evaluate
6125 // once and splat over the rest of the array elements.
6126 assert(FillerExpr && "no array filler for incomplete init list");
6127 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6128 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006129}
6130
Richard Smith027bf112011-11-17 22:56:20 +00006131bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006132 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6133}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006134
Richard Smith9543c5e2013-04-22 14:44:29 +00006135bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6136 const LValue &Subobject,
6137 APValue *Value,
6138 QualType Type) {
6139 bool HadZeroInit = !Value->isUninit();
6140
6141 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6142 unsigned N = CAT->getSize().getZExtValue();
6143
6144 // Preserve the array filler if we had prior zero-initialization.
6145 APValue Filler =
6146 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6147 : APValue();
6148
6149 *Value = APValue(APValue::UninitArray(), N, N);
6150
6151 if (HadZeroInit)
6152 for (unsigned I = 0; I != N; ++I)
6153 Value->getArrayInitializedElt(I) = Filler;
6154
6155 // Initialize the elements.
6156 LValue ArrayElt = Subobject;
6157 ArrayElt.addArray(Info, E, CAT);
6158 for (unsigned I = 0; I != N; ++I)
6159 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6160 CAT->getElementType()) ||
6161 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6162 CAT->getElementType(), 1))
6163 return false;
6164
6165 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006166 }
Richard Smith027bf112011-11-17 22:56:20 +00006167
Richard Smith9543c5e2013-04-22 14:44:29 +00006168 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006169 return Error(E);
6170
Richard Smithb8348f52016-05-12 22:16:28 +00006171 return RecordExprEvaluator(Info, Subobject, *Value)
6172 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006173}
6174
Richard Smithf3e9e432011-11-07 09:22:26 +00006175//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006176// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006177//
6178// As a GNU extension, we support casting pointers to sufficiently-wide integer
6179// types and back in constant folding. Integer values are thus represented
6180// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006181//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006182
6183namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006184class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006185 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006186 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006187public:
Richard Smith2e312c82012-03-03 22:46:17 +00006188 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006189 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006190
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006191 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006192 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006193 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006194 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006195 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006196 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006197 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006198 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006199 return true;
6200 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006201 bool Success(const llvm::APSInt &SI, const Expr *E) {
6202 return Success(SI, E, Result);
6203 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006204
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006205 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006206 assert(E->getType()->isIntegralOrEnumerationType() &&
6207 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006208 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006209 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006210 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006211 Result.getInt().setIsUnsigned(
6212 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006213 return true;
6214 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006215 bool Success(const llvm::APInt &I, const Expr *E) {
6216 return Success(I, E, Result);
6217 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006218
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006219 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006220 assert(E->getType()->isIntegralOrEnumerationType() &&
6221 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006222 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006223 return true;
6224 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006225 bool Success(uint64_t Value, const Expr *E) {
6226 return Success(Value, E, Result);
6227 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006228
Ken Dyckdbc01912011-03-11 02:13:43 +00006229 bool Success(CharUnits Size, const Expr *E) {
6230 return Success(Size.getQuantity(), E);
6231 }
6232
Richard Smith2e312c82012-03-03 22:46:17 +00006233 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006234 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006235 Result = V;
6236 return true;
6237 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006238 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006239 }
Mike Stump11289f42009-09-09 15:08:12 +00006240
Richard Smithfddd3842011-12-30 21:15:51 +00006241 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006242
Peter Collingbournee9200682011-05-13 03:29:01 +00006243 //===--------------------------------------------------------------------===//
6244 // Visitor Methods
6245 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006246
Chris Lattner7174bf32008-07-12 00:38:25 +00006247 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006248 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006249 }
6250 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006251 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006252 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006253
6254 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6255 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006256 if (CheckReferencedDecl(E, E->getDecl()))
6257 return true;
6258
6259 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006260 }
6261 bool VisitMemberExpr(const MemberExpr *E) {
6262 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006263 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006264 return true;
6265 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006266
6267 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006268 }
6269
Peter Collingbournee9200682011-05-13 03:29:01 +00006270 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006271 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006272 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006273 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006274
Peter Collingbournee9200682011-05-13 03:29:01 +00006275 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006276 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006277
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006278 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006279 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006280 }
Mike Stump11289f42009-09-09 15:08:12 +00006281
Ted Kremeneke65b0862012-03-06 20:05:56 +00006282 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6283 return Success(E->getValue(), E);
6284 }
6285
Richard Smith4ce706a2011-10-11 21:43:33 +00006286 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006287 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006288 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006289 }
6290
Douglas Gregor29c42f22012-02-24 07:38:34 +00006291 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6292 return Success(E->getValue(), E);
6293 }
6294
John Wiegley6242b6a2011-04-28 00:16:57 +00006295 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6296 return Success(E->getValue(), E);
6297 }
6298
John Wiegleyf9f65842011-04-25 06:54:41 +00006299 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6300 return Success(E->getValue(), E);
6301 }
6302
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006303 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006304 bool VisitUnaryImag(const UnaryOperator *E);
6305
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006306 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006307 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006308
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006309private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006310 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006311 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006312};
Chris Lattner05706e882008-07-11 18:11:29 +00006313} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006314
Richard Smith11562c52011-10-28 17:51:58 +00006315/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6316/// produce either the integer value or a pointer.
6317///
6318/// GCC has a heinous extension which folds casts between pointer types and
6319/// pointer-sized integral types. We support this by allowing the evaluation of
6320/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6321/// Some simple arithmetic on such values is supported (they are treated much
6322/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006323static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006324 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006325 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006326 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006327}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006328
Richard Smithf57d8cb2011-12-09 22:58:01 +00006329static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006330 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006331 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006332 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006333 if (!Val.isInt()) {
6334 // FIXME: It would be better to produce the diagnostic for casting
6335 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006336 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006337 return false;
6338 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006339 Result = Val.getInt();
6340 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006341}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006342
Richard Smithf57d8cb2011-12-09 22:58:01 +00006343/// Check whether the given declaration can be directly converted to an integral
6344/// rvalue. If not, no diagnostic is produced; there are other things we can
6345/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006346bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006347 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006348 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006349 // Check for signedness/width mismatches between E type and ECD value.
6350 bool SameSign = (ECD->getInitVal().isSigned()
6351 == E->getType()->isSignedIntegerOrEnumerationType());
6352 bool SameWidth = (ECD->getInitVal().getBitWidth()
6353 == Info.Ctx.getIntWidth(E->getType()));
6354 if (SameSign && SameWidth)
6355 return Success(ECD->getInitVal(), E);
6356 else {
6357 // Get rid of mismatch (otherwise Success assertions will fail)
6358 // by computing a new value matching the type of E.
6359 llvm::APSInt Val = ECD->getInitVal();
6360 if (!SameSign)
6361 Val.setIsSigned(!ECD->getInitVal().isSigned());
6362 if (!SameWidth)
6363 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6364 return Success(Val, E);
6365 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006366 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006367 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006368}
6369
Chris Lattner86ee2862008-10-06 06:40:35 +00006370/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6371/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006372static int EvaluateBuiltinClassifyType(const CallExpr *E,
6373 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006374 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006375 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006376 enum gcc_type_class {
6377 no_type_class = -1,
6378 void_type_class, integer_type_class, char_type_class,
6379 enumeral_type_class, boolean_type_class,
6380 pointer_type_class, reference_type_class, offset_type_class,
6381 real_type_class, complex_type_class,
6382 function_type_class, method_type_class,
6383 record_type_class, union_type_class,
6384 array_type_class, string_type_class,
6385 lang_type_class
6386 };
Mike Stump11289f42009-09-09 15:08:12 +00006387
6388 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006389 // ideal, however it is what gcc does.
6390 if (E->getNumArgs() == 0)
6391 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006392
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006393 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6394 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6395
6396 switch (CanTy->getTypeClass()) {
6397#define TYPE(ID, BASE)
6398#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6399#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6400#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6401#include "clang/AST/TypeNodes.def"
6402 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6403
6404 case Type::Builtin:
6405 switch (BT->getKind()) {
6406#define BUILTIN_TYPE(ID, SINGLETON_ID)
6407#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6408#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6409#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6410#include "clang/AST/BuiltinTypes.def"
6411 case BuiltinType::Void:
6412 return void_type_class;
6413
6414 case BuiltinType::Bool:
6415 return boolean_type_class;
6416
6417 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6418 case BuiltinType::UChar:
6419 case BuiltinType::UShort:
6420 case BuiltinType::UInt:
6421 case BuiltinType::ULong:
6422 case BuiltinType::ULongLong:
6423 case BuiltinType::UInt128:
6424 return integer_type_class;
6425
6426 case BuiltinType::NullPtr:
6427 return pointer_type_class;
6428
6429 case BuiltinType::WChar_U:
6430 case BuiltinType::Char16:
6431 case BuiltinType::Char32:
6432 case BuiltinType::ObjCId:
6433 case BuiltinType::ObjCClass:
6434 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006435#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6436 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006437#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006438 case BuiltinType::OCLSampler:
6439 case BuiltinType::OCLEvent:
6440 case BuiltinType::OCLClkEvent:
6441 case BuiltinType::OCLQueue:
6442 case BuiltinType::OCLNDRange:
6443 case BuiltinType::OCLReserveID:
6444 case BuiltinType::Dependent:
6445 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6446 };
6447
6448 case Type::Enum:
6449 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6450 break;
6451
6452 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006453 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006454 break;
6455
6456 case Type::MemberPointer:
6457 if (CanTy->isMemberDataPointerType())
6458 return offset_type_class;
6459 else {
6460 // We expect member pointers to be either data or function pointers,
6461 // nothing else.
6462 assert(CanTy->isMemberFunctionPointerType());
6463 return method_type_class;
6464 }
6465
6466 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006467 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006468
6469 case Type::FunctionNoProto:
6470 case Type::FunctionProto:
6471 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6472
6473 case Type::Record:
6474 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6475 switch (RT->getDecl()->getTagKind()) {
6476 case TagTypeKind::TTK_Struct:
6477 case TagTypeKind::TTK_Class:
6478 case TagTypeKind::TTK_Interface:
6479 return record_type_class;
6480
6481 case TagTypeKind::TTK_Enum:
6482 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6483
6484 case TagTypeKind::TTK_Union:
6485 return union_type_class;
6486 }
6487 }
David Blaikie83d382b2011-09-23 05:06:16 +00006488 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006489
6490 case Type::ConstantArray:
6491 case Type::VariableArray:
6492 case Type::IncompleteArray:
6493 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6494
6495 case Type::BlockPointer:
6496 case Type::LValueReference:
6497 case Type::RValueReference:
6498 case Type::Vector:
6499 case Type::ExtVector:
6500 case Type::Auto:
6501 case Type::ObjCObject:
6502 case Type::ObjCInterface:
6503 case Type::ObjCObjectPointer:
6504 case Type::Pipe:
6505 case Type::Atomic:
6506 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6507 }
6508
6509 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006510}
6511
Richard Smith5fab0c92011-12-28 19:48:30 +00006512/// EvaluateBuiltinConstantPForLValue - Determine the result of
6513/// __builtin_constant_p when applied to the given lvalue.
6514///
6515/// An lvalue is only "constant" if it is a pointer or reference to the first
6516/// character of a string literal.
6517template<typename LValue>
6518static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006519 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006520 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6521}
6522
6523/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6524/// GCC as we can manage.
6525static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6526 QualType ArgType = Arg->getType();
6527
6528 // __builtin_constant_p always has one operand. The rules which gcc follows
6529 // are not precisely documented, but are as follows:
6530 //
6531 // - If the operand is of integral, floating, complex or enumeration type,
6532 // and can be folded to a known value of that type, it returns 1.
6533 // - If the operand and can be folded to a pointer to the first character
6534 // of a string literal (or such a pointer cast to an integral type), it
6535 // returns 1.
6536 //
6537 // Otherwise, it returns 0.
6538 //
6539 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6540 // its support for this does not currently work.
6541 if (ArgType->isIntegralOrEnumerationType()) {
6542 Expr::EvalResult Result;
6543 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6544 return false;
6545
6546 APValue &V = Result.Val;
6547 if (V.getKind() == APValue::Int)
6548 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006549 if (V.getKind() == APValue::LValue)
6550 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006551 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6552 return Arg->isEvaluatable(Ctx);
6553 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6554 LValue LV;
6555 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006556 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006557 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6558 : EvaluatePointer(Arg, LV, Info)) &&
6559 !Status.HasSideEffects)
6560 return EvaluateBuiltinConstantPForLValue(LV);
6561 }
6562
6563 // Anything else isn't considered to be sufficiently constant.
6564 return false;
6565}
6566
John McCall95007602010-05-10 23:27:23 +00006567/// Retrieves the "underlying object type" of the given expression,
6568/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006569static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006570 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6571 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006572 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006573 } else if (const Expr *E = B.get<const Expr*>()) {
6574 if (isa<CompoundLiteralExpr>(E))
6575 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006576 }
6577
6578 return QualType();
6579}
6580
George Burgess IV3a03fab2015-09-04 21:28:13 +00006581/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006582/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6583/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006584/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6585///
6586/// Always returns an RValue with a pointer representation.
6587static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6588 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6589
6590 auto *NoParens = E->IgnoreParens();
6591 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006592 if (Cast == nullptr)
6593 return NoParens;
6594
6595 // We only conservatively allow a few kinds of casts, because this code is
6596 // inherently a simple solution that seeks to support the common case.
6597 auto CastKind = Cast->getCastKind();
6598 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6599 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006600 return NoParens;
6601
6602 auto *SubExpr = Cast->getSubExpr();
6603 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6604 return NoParens;
6605 return ignorePointerCastsAndParens(SubExpr);
6606}
6607
George Burgess IVa51c4072015-10-16 01:49:01 +00006608/// Checks to see if the given LValue's Designator is at the end of the LValue's
6609/// record layout. e.g.
6610/// struct { struct { int a, b; } fst, snd; } obj;
6611/// obj.fst // no
6612/// obj.snd // yes
6613/// obj.fst.a // no
6614/// obj.fst.b // no
6615/// obj.snd.a // no
6616/// obj.snd.b // yes
6617///
6618/// Please note: this function is specialized for how __builtin_object_size
6619/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00006620///
6621/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00006622static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6623 assert(!LVal.Designator.Invalid);
6624
George Burgess IV4168d752016-06-27 19:40:41 +00006625 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6626 const RecordDecl *Parent = FD->getParent();
6627 Invalid = Parent->isInvalidDecl();
6628 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00006629 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00006630 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00006631 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6632 };
6633
6634 auto &Base = LVal.getLValueBase();
6635 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6636 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006637 bool Invalid;
6638 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6639 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006640 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006641 for (auto *FD : IFD->chain()) {
6642 bool Invalid;
6643 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6644 return Invalid;
6645 }
George Burgess IVa51c4072015-10-16 01:49:01 +00006646 }
6647 }
6648
6649 QualType BaseType = getType(Base);
6650 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6651 if (BaseType->isArrayType()) {
6652 // Because __builtin_object_size treats arrays as objects, we can ignore
6653 // the index iff this is the last array in the Designator.
6654 if (I + 1 == E)
6655 return true;
6656 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6657 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6658 if (Index + 1 != CAT->getSize())
6659 return false;
6660 BaseType = CAT->getElementType();
6661 } else if (BaseType->isAnyComplexType()) {
6662 auto *CT = BaseType->castAs<ComplexType>();
6663 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6664 if (Index != 1)
6665 return false;
6666 BaseType = CT->getElementType();
6667 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
George Burgess IV4168d752016-06-27 19:40:41 +00006668 bool Invalid;
6669 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6670 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006671 BaseType = FD->getType();
6672 } else {
6673 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6674 "Expecting cast to a base class");
6675 return false;
6676 }
6677 }
6678 return true;
6679}
6680
6681/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6682static bool refersToCompleteObject(const LValue &LVal) {
6683 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6684 return false;
6685
6686 if (!LVal.InvalidBase)
6687 return true;
6688
6689 auto *E = LVal.Base.dyn_cast<const Expr *>();
6690 (void)E;
6691 assert(E != nullptr && isa<MemberExpr>(E));
6692 return false;
6693}
6694
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006695/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6696/// true and stores the result in @p Size.
6697///
6698/// If @p WasError is non-null, this will report whether the failure to evaluate
6699/// is to be treated as an Error in IntExprEvaluator.
6700static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6701 EvalInfo &Info, uint64_t &Size,
6702 bool *WasError = nullptr) {
6703 if (WasError != nullptr)
6704 *WasError = false;
6705
6706 auto Error = [&](const Expr *E) {
6707 if (WasError != nullptr)
6708 *WasError = true;
6709 return false;
6710 };
6711
6712 auto Success = [&](uint64_t S, const Expr *E) {
6713 Size = S;
6714 return true;
6715 };
6716
George Burgess IVbdb5b262015-08-19 02:19:07 +00006717 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006718 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006719 {
6720 // The operand of __builtin_object_size is never evaluated for side-effects.
6721 // If there are any, but we can determine the pointed-to object anyway, then
6722 // ignore the side-effects.
6723 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006724 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006725
6726 if (E->isGLValue()) {
6727 // It's possible for us to be given GLValues if we're called via
6728 // Expr::tryEvaluateObjectSize.
6729 APValue RVal;
6730 if (!EvaluateAsRValue(Info, E, RVal))
6731 return false;
6732 Base.setFrom(Info.Ctx, RVal);
6733 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006734 return false;
6735 }
John McCall95007602010-05-10 23:27:23 +00006736
George Burgess IVbdb5b262015-08-19 02:19:07 +00006737 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006738 // If we point to before the start of the object, there are no accessible
6739 // bytes.
6740 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006741 return Success(0, E);
6742
George Burgess IV3a03fab2015-09-04 21:28:13 +00006743 // In the case where we're not dealing with a subobject, we discard the
6744 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006745 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006746
6747 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6748 // exist. If we can't verify the base, then we can't do that.
6749 //
6750 // As a special case, we produce a valid object size for an unknown object
6751 // with a known designator if Type & 1 is 1. For instance:
6752 //
6753 // extern struct X { char buff[32]; int a, b, c; } *p;
6754 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6755 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6756 //
6757 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006758 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006759 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006760
George Burgess IVa51c4072015-10-16 01:49:01 +00006761 // If we're not examining only the subobject, then we reset to a complete
6762 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006763 //
6764 // If Type is 1 and we've lost track of the subobject, just find the complete
6765 // object instead. (If Type is 3, that's not correct behavior and we should
6766 // return 0 instead.)
6767 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006768 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006769 QualType T = getObjectType(End.getLValueBase());
6770 if (T.isNull())
6771 End.Designator.setInvalid();
6772 else {
6773 End.Designator = SubobjectDesignator(T);
6774 End.Offset = CharUnits::Zero();
6775 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006776 }
John McCall95007602010-05-10 23:27:23 +00006777
George Burgess IVbdb5b262015-08-19 02:19:07 +00006778 // If it is not possible to determine which objects ptr points to at compile
6779 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6780 // and (size_t) 0 for type 2 or 3.
6781 if (End.Designator.Invalid)
6782 return false;
6783
6784 // According to the GCC documentation, we want the size of the subobject
6785 // denoted by the pointer. But that's not quite right -- what we actually
6786 // want is the size of the immediately-enclosing array, if there is one.
6787 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006788 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006789 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6790 // We got a pointer to an array. Step to its end.
6791 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006792 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006793 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006794 // We're already pointing at the end of the object.
6795 AmountToAdd = 0;
6796 }
6797
George Burgess IV3a03fab2015-09-04 21:28:13 +00006798 QualType PointeeType = End.Designator.MostDerivedType;
6799 assert(!PointeeType.isNull());
6800 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006801 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006802
George Burgess IVbdb5b262015-08-19 02:19:07 +00006803 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6804 AmountToAdd))
6805 return false;
John McCall95007602010-05-10 23:27:23 +00006806
George Burgess IVbdb5b262015-08-19 02:19:07 +00006807 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006808
6809 // The following is a moderately common idiom in C:
6810 //
6811 // struct Foo { int a; char c[1]; };
6812 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6813 // strcpy(&F->c[0], Bar);
6814 //
6815 // So, if we see that we're examining a 1-length (or 0-length) array at the
6816 // end of a struct with an unknown base, we give up instead of breaking code
6817 // that behaves this way. Note that we only do this when Type=1, because
6818 // Type=3 is a lower bound, so answering conservatively is fine.
6819 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6820 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6821 End.Designator.MostDerivedIsArrayElement &&
6822 End.Designator.MostDerivedArraySize < 2 &&
6823 isDesignatorAtObjectEnd(Info.Ctx, End))
6824 return false;
6825
George Burgess IVbdb5b262015-08-19 02:19:07 +00006826 if (BaseOffset > EndOffset)
6827 return Success(0, E);
6828
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006829 return Success((EndOffset - BaseOffset).getQuantity(), E);
6830}
6831
6832bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6833 unsigned Type) {
6834 uint64_t Size;
6835 bool WasError;
6836 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6837 return Success(Size, E);
6838 if (WasError)
6839 return Error(E);
6840 return false;
John McCall95007602010-05-10 23:27:23 +00006841}
6842
Peter Collingbournee9200682011-05-13 03:29:01 +00006843bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006844 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006845 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006846 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006847
6848 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006849 // The type was checked when we built the expression.
6850 unsigned Type =
6851 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6852 assert(Type <= 3 && "unexpected type");
6853
6854 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006855 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006856
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006857 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006858 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006859
Richard Smith01ade172012-05-23 04:13:20 +00006860 // Expression had no side effects, but we couldn't statically determine the
6861 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006862 switch (Info.EvalMode) {
6863 case EvalInfo::EM_ConstantExpression:
6864 case EvalInfo::EM_PotentialConstantExpression:
6865 case EvalInfo::EM_ConstantFold:
6866 case EvalInfo::EM_EvaluateForOverflow:
6867 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006868 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006869 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006870 return Error(E);
6871 case EvalInfo::EM_ConstantExpressionUnevaluated:
6872 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006873 // Reduce it to a constant now.
6874 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006875 }
Mike Stump722cedf2009-10-26 18:35:08 +00006876 }
6877
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006878 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006879 case Builtin::BI__builtin_bswap32:
6880 case Builtin::BI__builtin_bswap64: {
6881 APSInt Val;
6882 if (!EvaluateInteger(E->getArg(0), Val, Info))
6883 return false;
6884
6885 return Success(Val.byteSwap(), E);
6886 }
6887
Richard Smith8889a3d2013-06-13 06:26:32 +00006888 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006889 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00006890
6891 // FIXME: BI__builtin_clrsb
6892 // FIXME: BI__builtin_clrsbl
6893 // FIXME: BI__builtin_clrsbll
6894
Richard Smith80b3c8e2013-06-13 05:04:16 +00006895 case Builtin::BI__builtin_clz:
6896 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006897 case Builtin::BI__builtin_clzll:
6898 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006899 APSInt Val;
6900 if (!EvaluateInteger(E->getArg(0), Val, Info))
6901 return false;
6902 if (!Val)
6903 return Error(E);
6904
6905 return Success(Val.countLeadingZeros(), E);
6906 }
6907
Richard Smith8889a3d2013-06-13 06:26:32 +00006908 case Builtin::BI__builtin_constant_p:
6909 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6910
Richard Smith80b3c8e2013-06-13 05:04:16 +00006911 case Builtin::BI__builtin_ctz:
6912 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006913 case Builtin::BI__builtin_ctzll:
6914 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006915 APSInt Val;
6916 if (!EvaluateInteger(E->getArg(0), Val, Info))
6917 return false;
6918 if (!Val)
6919 return Error(E);
6920
6921 return Success(Val.countTrailingZeros(), E);
6922 }
6923
Richard Smith8889a3d2013-06-13 06:26:32 +00006924 case Builtin::BI__builtin_eh_return_data_regno: {
6925 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6926 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6927 return Success(Operand, E);
6928 }
6929
6930 case Builtin::BI__builtin_expect:
6931 return Visit(E->getArg(0));
6932
6933 case Builtin::BI__builtin_ffs:
6934 case Builtin::BI__builtin_ffsl:
6935 case Builtin::BI__builtin_ffsll: {
6936 APSInt Val;
6937 if (!EvaluateInteger(E->getArg(0), Val, Info))
6938 return false;
6939
6940 unsigned N = Val.countTrailingZeros();
6941 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6942 }
6943
6944 case Builtin::BI__builtin_fpclassify: {
6945 APFloat Val(0.0);
6946 if (!EvaluateFloat(E->getArg(5), Val, Info))
6947 return false;
6948 unsigned Arg;
6949 switch (Val.getCategory()) {
6950 case APFloat::fcNaN: Arg = 0; break;
6951 case APFloat::fcInfinity: Arg = 1; break;
6952 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6953 case APFloat::fcZero: Arg = 4; break;
6954 }
6955 return Visit(E->getArg(Arg));
6956 }
6957
6958 case Builtin::BI__builtin_isinf_sign: {
6959 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006960 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006961 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6962 }
6963
Richard Smithea3019d2013-10-15 19:07:14 +00006964 case Builtin::BI__builtin_isinf: {
6965 APFloat Val(0.0);
6966 return EvaluateFloat(E->getArg(0), Val, Info) &&
6967 Success(Val.isInfinity() ? 1 : 0, E);
6968 }
6969
6970 case Builtin::BI__builtin_isfinite: {
6971 APFloat Val(0.0);
6972 return EvaluateFloat(E->getArg(0), Val, Info) &&
6973 Success(Val.isFinite() ? 1 : 0, E);
6974 }
6975
6976 case Builtin::BI__builtin_isnan: {
6977 APFloat Val(0.0);
6978 return EvaluateFloat(E->getArg(0), Val, Info) &&
6979 Success(Val.isNaN() ? 1 : 0, E);
6980 }
6981
6982 case Builtin::BI__builtin_isnormal: {
6983 APFloat Val(0.0);
6984 return EvaluateFloat(E->getArg(0), Val, Info) &&
6985 Success(Val.isNormal() ? 1 : 0, E);
6986 }
6987
Richard Smith8889a3d2013-06-13 06:26:32 +00006988 case Builtin::BI__builtin_parity:
6989 case Builtin::BI__builtin_parityl:
6990 case Builtin::BI__builtin_parityll: {
6991 APSInt Val;
6992 if (!EvaluateInteger(E->getArg(0), Val, Info))
6993 return false;
6994
6995 return Success(Val.countPopulation() % 2, E);
6996 }
6997
Richard Smith80b3c8e2013-06-13 05:04:16 +00006998 case Builtin::BI__builtin_popcount:
6999 case Builtin::BI__builtin_popcountl:
7000 case Builtin::BI__builtin_popcountll: {
7001 APSInt Val;
7002 if (!EvaluateInteger(E->getArg(0), Val, Info))
7003 return false;
7004
7005 return Success(Val.countPopulation(), E);
7006 }
7007
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007008 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007009 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007010 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007011 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00007012 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
7013 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007014 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007015 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00007016 case Builtin::BI__builtin_strlen: {
7017 // As an extension, we support __builtin_strlen() as a constant expression,
7018 // and support folding strlen() to a constant.
7019 LValue String;
7020 if (!EvaluatePointer(E->getArg(0), String, Info))
7021 return false;
7022
7023 // Fast path: if it's a string literal, search the string value.
7024 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7025 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007026 // The string literal may have embedded null characters. Find the first
7027 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007028 StringRef Str = S->getBytes();
7029 int64_t Off = String.Offset.getQuantity();
7030 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7031 S->getCharByteWidth() == 1) {
7032 Str = Str.substr(Off);
7033
7034 StringRef::size_type Pos = Str.find(0);
7035 if (Pos != StringRef::npos)
7036 Str = Str.substr(0, Pos);
7037
7038 return Success(Str.size(), E);
7039 }
7040
7041 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007042 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007043
7044 // Slow path: scan the bytes of the string looking for the terminating 0.
7045 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7046 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7047 APValue Char;
7048 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7049 !Char.isInt())
7050 return false;
7051 if (!Char.getInt())
7052 return Success(Strlen, E);
7053 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7054 return false;
7055 }
7056 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007057
Richard Smith01ba47d2012-04-13 00:45:38 +00007058 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007059 case Builtin::BI__atomic_is_lock_free:
7060 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007061 APSInt SizeVal;
7062 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7063 return false;
7064
7065 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7066 // of two less than the maximum inline atomic width, we know it is
7067 // lock-free. If the size isn't a power of two, or greater than the
7068 // maximum alignment where we promote atomics, we know it is not lock-free
7069 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7070 // the answer can only be determined at runtime; for example, 16-byte
7071 // atomics have lock-free implementations on some, but not all,
7072 // x86-64 processors.
7073
7074 // Check power-of-two.
7075 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007076 if (Size.isPowerOfTwo()) {
7077 // Check against inlining width.
7078 unsigned InlineWidthBits =
7079 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7080 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7081 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7082 Size == CharUnits::One() ||
7083 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7084 Expr::NPC_NeverValueDependent))
7085 // OK, we will inline appropriately-aligned operations of this size,
7086 // and _Atomic(T) is appropriately-aligned.
7087 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007088
Richard Smith01ba47d2012-04-13 00:45:38 +00007089 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7090 castAs<PointerType>()->getPointeeType();
7091 if (!PointeeType->isIncompleteType() &&
7092 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7093 // OK, we will inline operations on this object.
7094 return Success(1, E);
7095 }
7096 }
7097 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007098
Richard Smith01ba47d2012-04-13 00:45:38 +00007099 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7100 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007101 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007102 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007103}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007104
Richard Smith8b3497e2011-10-31 01:37:14 +00007105static bool HasSameBase(const LValue &A, const LValue &B) {
7106 if (!A.getLValueBase())
7107 return !B.getLValueBase();
7108 if (!B.getLValueBase())
7109 return false;
7110
Richard Smithce40ad62011-11-12 22:28:03 +00007111 if (A.getLValueBase().getOpaqueValue() !=
7112 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007113 const Decl *ADecl = GetLValueBaseDecl(A);
7114 if (!ADecl)
7115 return false;
7116 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007117 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007118 return false;
7119 }
7120
7121 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007122 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007123}
7124
Richard Smithd20f1e62014-10-21 23:01:04 +00007125/// \brief Determine whether this is a pointer past the end of the complete
7126/// object referred to by the lvalue.
7127static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7128 const LValue &LV) {
7129 // A null pointer can be viewed as being "past the end" but we don't
7130 // choose to look at it that way here.
7131 if (!LV.getLValueBase())
7132 return false;
7133
7134 // If the designator is valid and refers to a subobject, we're not pointing
7135 // past the end.
7136 if (!LV.getLValueDesignator().Invalid &&
7137 !LV.getLValueDesignator().isOnePastTheEnd())
7138 return false;
7139
David Majnemerc378ca52015-08-29 08:32:55 +00007140 // A pointer to an incomplete type might be past-the-end if the type's size is
7141 // zero. We cannot tell because the type is incomplete.
7142 QualType Ty = getType(LV.getLValueBase());
7143 if (Ty->isIncompleteType())
7144 return true;
7145
Richard Smithd20f1e62014-10-21 23:01:04 +00007146 // We're a past-the-end pointer if we point to the byte after the object,
7147 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007148 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007149 return LV.getLValueOffset() == Size;
7150}
7151
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007152namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007153
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007154/// \brief Data recursive integer evaluator of certain binary operators.
7155///
7156/// We use a data recursive algorithm for binary operators so that we are able
7157/// to handle extreme cases of chained binary operators without causing stack
7158/// overflow.
7159class DataRecursiveIntBinOpEvaluator {
7160 struct EvalResult {
7161 APValue Val;
7162 bool Failed;
7163
7164 EvalResult() : Failed(false) { }
7165
7166 void swap(EvalResult &RHS) {
7167 Val.swap(RHS.Val);
7168 Failed = RHS.Failed;
7169 RHS.Failed = false;
7170 }
7171 };
7172
7173 struct Job {
7174 const Expr *E;
7175 EvalResult LHSResult; // meaningful only for binary operator expression.
7176 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007177
David Blaikie73726062015-08-12 23:09:24 +00007178 Job() = default;
7179 Job(Job &&J)
7180 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
George Burgess IV8c892b52016-05-25 22:31:54 +00007181 SpecEvalRAII(std::move(J.SpecEvalRAII)) {}
David Blaikie73726062015-08-12 23:09:24 +00007182
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007183 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007184 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007185 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007186
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007187 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007188 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007189 };
7190
7191 SmallVector<Job, 16> Queue;
7192
7193 IntExprEvaluator &IntEval;
7194 EvalInfo &Info;
7195 APValue &FinalResult;
7196
7197public:
7198 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7199 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7200
7201 /// \brief True if \param E is a binary operator that we are going to handle
7202 /// data recursively.
7203 /// We handle binary operators that are comma, logical, or that have operands
7204 /// with integral or enumeration type.
7205 static bool shouldEnqueue(const BinaryOperator *E) {
7206 return E->getOpcode() == BO_Comma ||
7207 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007208 (E->isRValue() &&
7209 E->getType()->isIntegralOrEnumerationType() &&
7210 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007211 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007212 }
7213
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007214 bool Traverse(const BinaryOperator *E) {
7215 enqueue(E);
7216 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007217 while (!Queue.empty())
7218 process(PrevResult);
7219
7220 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007221
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007222 FinalResult.swap(PrevResult.Val);
7223 return true;
7224 }
7225
7226private:
7227 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7228 return IntEval.Success(Value, E, Result);
7229 }
7230 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7231 return IntEval.Success(Value, E, Result);
7232 }
7233 bool Error(const Expr *E) {
7234 return IntEval.Error(E);
7235 }
7236 bool Error(const Expr *E, diag::kind D) {
7237 return IntEval.Error(E, D);
7238 }
7239
7240 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7241 return Info.CCEDiag(E, D);
7242 }
7243
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007244 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7245 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007246 bool &SuppressRHSDiags);
7247
7248 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7249 const BinaryOperator *E, APValue &Result);
7250
7251 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7252 Result.Failed = !Evaluate(Result.Val, Info, E);
7253 if (Result.Failed)
7254 Result.Val = APValue();
7255 }
7256
Richard Trieuba4d0872012-03-21 23:30:30 +00007257 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007258
7259 void enqueue(const Expr *E) {
7260 E = E->IgnoreParens();
7261 Queue.resize(Queue.size()+1);
7262 Queue.back().E = E;
7263 Queue.back().Kind = Job::AnyExprKind;
7264 }
7265};
7266
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007267}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007268
7269bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007270 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007271 bool &SuppressRHSDiags) {
7272 if (E->getOpcode() == BO_Comma) {
7273 // Ignore LHS but note if we could not evaluate it.
7274 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007275 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007276 return true;
7277 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007278
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007279 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007280 bool LHSAsBool;
7281 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007282 // We were able to evaluate the LHS, see if we can get away with not
7283 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007284 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7285 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007286 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007287 }
7288 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007289 LHSResult.Failed = true;
7290
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007291 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007292 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007293 if (!Info.noteSideEffect())
7294 return false;
7295
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007296 // We can't evaluate the LHS; however, sometimes the result
7297 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7298 // Don't ignore RHS and suppress diagnostics from this arm.
7299 SuppressRHSDiags = true;
7300 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007301
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007302 return true;
7303 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007304
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007305 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7306 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007307
George Burgess IVa145e252016-05-25 22:38:36 +00007308 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007309 return false; // Ignore RHS;
7310
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007311 return true;
7312}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007313
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007314bool DataRecursiveIntBinOpEvaluator::
7315 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7316 const BinaryOperator *E, APValue &Result) {
7317 if (E->getOpcode() == BO_Comma) {
7318 if (RHSResult.Failed)
7319 return false;
7320 Result = RHSResult.Val;
7321 return true;
7322 }
7323
7324 if (E->isLogicalOp()) {
7325 bool lhsResult, rhsResult;
7326 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7327 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7328
7329 if (LHSIsOK) {
7330 if (RHSIsOK) {
7331 if (E->getOpcode() == BO_LOr)
7332 return Success(lhsResult || rhsResult, E, Result);
7333 else
7334 return Success(lhsResult && rhsResult, E, Result);
7335 }
7336 } else {
7337 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007338 // We can't evaluate the LHS; however, sometimes the result
7339 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7340 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007341 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007342 }
7343 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007344
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007345 return false;
7346 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007347
7348 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7349 E->getRHS()->getType()->isIntegralOrEnumerationType());
7350
7351 if (LHSResult.Failed || RHSResult.Failed)
7352 return false;
7353
7354 const APValue &LHSVal = LHSResult.Val;
7355 const APValue &RHSVal = RHSResult.Val;
7356
7357 // Handle cases like (unsigned long)&a + 4.
7358 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7359 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007360 CharUnits AdditionalOffset =
7361 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007362 if (E->getOpcode() == BO_Add)
7363 Result.getLValueOffset() += AdditionalOffset;
7364 else
7365 Result.getLValueOffset() -= AdditionalOffset;
7366 return true;
7367 }
7368
7369 // Handle cases like 4 + (unsigned long)&a
7370 if (E->getOpcode() == BO_Add &&
7371 RHSVal.isLValue() && LHSVal.isInt()) {
7372 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007373 Result.getLValueOffset() +=
7374 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007375 return true;
7376 }
7377
7378 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7379 // Handle (intptr_t)&&A - (intptr_t)&&B.
7380 if (!LHSVal.getLValueOffset().isZero() ||
7381 !RHSVal.getLValueOffset().isZero())
7382 return false;
7383 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7384 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7385 if (!LHSExpr || !RHSExpr)
7386 return false;
7387 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7388 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7389 if (!LHSAddrExpr || !RHSAddrExpr)
7390 return false;
7391 // Make sure both labels come from the same function.
7392 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7393 RHSAddrExpr->getLabel()->getDeclContext())
7394 return false;
7395 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7396 return true;
7397 }
Richard Smith43e77732013-05-07 04:50:00 +00007398
7399 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007400 if (!LHSVal.isInt() || !RHSVal.isInt())
7401 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007402
7403 // Set up the width and signedness manually, in case it can't be deduced
7404 // from the operation we're performing.
7405 // FIXME: Don't do this in the cases where we can deduce it.
7406 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7407 E->getType()->isUnsignedIntegerOrEnumerationType());
7408 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7409 RHSVal.getInt(), Value))
7410 return false;
7411 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007412}
7413
Richard Trieuba4d0872012-03-21 23:30:30 +00007414void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007415 Job &job = Queue.back();
7416
7417 switch (job.Kind) {
7418 case Job::AnyExprKind: {
7419 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7420 if (shouldEnqueue(Bop)) {
7421 job.Kind = Job::BinOpKind;
7422 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007423 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007424 }
7425 }
7426
7427 EvaluateExpr(job.E, Result);
7428 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007429 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007430 }
7431
7432 case Job::BinOpKind: {
7433 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007434 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007435 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007436 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007437 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007438 }
7439 if (SuppressRHSDiags)
7440 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007441 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007442 job.Kind = Job::BinOpVisitedLHSKind;
7443 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007444 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007445 }
7446
7447 case Job::BinOpVisitedLHSKind: {
7448 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7449 EvalResult RHS;
7450 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007451 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007452 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007453 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007454 }
7455 }
7456
7457 llvm_unreachable("Invalid Job::Kind!");
7458}
7459
George Burgess IV8c892b52016-05-25 22:31:54 +00007460namespace {
7461/// Used when we determine that we should fail, but can keep evaluating prior to
7462/// noting that we had a failure.
7463class DelayedNoteFailureRAII {
7464 EvalInfo &Info;
7465 bool NoteFailure;
7466
7467public:
7468 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7469 : Info(Info), NoteFailure(NoteFailure) {}
7470 ~DelayedNoteFailureRAII() {
7471 if (NoteFailure) {
7472 bool ContinueAfterFailure = Info.noteFailure();
7473 (void)ContinueAfterFailure;
7474 assert(ContinueAfterFailure &&
7475 "Shouldn't have kept evaluating on failure.");
7476 }
7477 }
7478};
7479}
7480
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007481bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007482 // We don't call noteFailure immediately because the assignment happens after
7483 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007484 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007485 return Error(E);
7486
George Burgess IV8c892b52016-05-25 22:31:54 +00007487 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007488 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7489 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007490
Anders Carlssonacc79812008-11-16 07:17:21 +00007491 QualType LHSTy = E->getLHS()->getType();
7492 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007493
Chandler Carruthb29a7432014-10-11 11:03:30 +00007494 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007495 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007496 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007497 if (E->isAssignmentOp()) {
7498 LValue LV;
7499 EvaluateLValue(E->getLHS(), LV, Info);
7500 LHSOK = false;
7501 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007502 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7503 if (LHSOK) {
7504 LHS.makeComplexFloat();
7505 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7506 }
7507 } else {
7508 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7509 }
George Burgess IVa145e252016-05-25 22:38:36 +00007510 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007511 return false;
7512
Chandler Carruthb29a7432014-10-11 11:03:30 +00007513 if (E->getRHS()->getType()->isRealFloatingType()) {
7514 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7515 return false;
7516 RHS.makeComplexFloat();
7517 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7518 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007519 return false;
7520
7521 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007522 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007523 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007524 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007525 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7526
John McCalle3027922010-08-25 11:45:40 +00007527 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007528 return Success((CR_r == APFloat::cmpEqual &&
7529 CR_i == APFloat::cmpEqual), E);
7530 else {
John McCalle3027922010-08-25 11:45:40 +00007531 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007532 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007533 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007534 CR_r == APFloat::cmpLessThan ||
7535 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007536 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007537 CR_i == APFloat::cmpLessThan ||
7538 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007539 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007540 } else {
John McCalle3027922010-08-25 11:45:40 +00007541 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007542 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7543 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7544 else {
John McCalle3027922010-08-25 11:45:40 +00007545 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007546 "Invalid compex comparison.");
7547 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7548 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7549 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007550 }
7551 }
Mike Stump11289f42009-09-09 15:08:12 +00007552
Anders Carlssonacc79812008-11-16 07:17:21 +00007553 if (LHSTy->isRealFloatingType() &&
7554 RHSTy->isRealFloatingType()) {
7555 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007556
Richard Smith253c2a32012-01-27 01:14:48 +00007557 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007558 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007559 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007560
Richard Smith253c2a32012-01-27 01:14:48 +00007561 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007562 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007563
Anders Carlssonacc79812008-11-16 07:17:21 +00007564 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007565
Anders Carlssonacc79812008-11-16 07:17:21 +00007566 switch (E->getOpcode()) {
7567 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007568 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007569 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007570 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007571 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007572 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007573 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007574 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007575 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007576 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007577 E);
John McCalle3027922010-08-25 11:45:40 +00007578 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007579 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007580 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007581 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007582 || CR == APFloat::cmpLessThan
7583 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007584 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007585 }
Mike Stump11289f42009-09-09 15:08:12 +00007586
Eli Friedmana38da572009-04-28 19:17:36 +00007587 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007588 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007589 LValue LHSValue, RHSValue;
7590
7591 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007592 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007593 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007594
Richard Smith253c2a32012-01-27 01:14:48 +00007595 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007596 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007597
Richard Smith8b3497e2011-10-31 01:37:14 +00007598 // Reject differing bases from the normal codepath; we special-case
7599 // comparisons to null.
7600 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007601 if (E->getOpcode() == BO_Sub) {
7602 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007603 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007604 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007605 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007606 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007607 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007608 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007609 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7610 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7611 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007612 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007613 // Make sure both labels come from the same function.
7614 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7615 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007616 return Error(E);
7617 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007618 }
Richard Smith83c68212011-10-31 05:11:32 +00007619 // Inequalities and subtractions between unrelated pointers have
7620 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007621 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007622 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007623 // A constant address may compare equal to the address of a symbol.
7624 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007625 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007626 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7627 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007628 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007629 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007630 // distinct addresses. In clang, the result of such a comparison is
7631 // unspecified, so it is not a constant expression. However, we do know
7632 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007633 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7634 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007635 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007636 // We can't tell whether weak symbols will end up pointing to the same
7637 // object.
7638 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007639 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007640 // We can't compare the address of the start of one object with the
7641 // past-the-end address of another object, per C++ DR1652.
7642 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7643 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7644 (RHSValue.Base && RHSValue.Offset.isZero() &&
7645 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7646 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007647 // We can't tell whether an object is at the same address as another
7648 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007649 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7650 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007651 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007652 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007653 // (Note that clang defaults to -fmerge-all-constants, which can
7654 // lead to inconsistent results for comparisons involving the address
7655 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007656 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007657 }
Eli Friedman64004332009-03-23 04:38:34 +00007658
Richard Smith1b470412012-02-01 08:10:20 +00007659 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7660 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7661
Richard Smith84f6dcf2012-02-02 01:16:57 +00007662 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7663 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7664
John McCalle3027922010-08-25 11:45:40 +00007665 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007666 // C++11 [expr.add]p6:
7667 // Unless both pointers point to elements of the same array object, or
7668 // one past the last element of the array object, the behavior is
7669 // undefined.
7670 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7671 !AreElementsOfSameArray(getType(LHSValue.Base),
7672 LHSDesignator, RHSDesignator))
7673 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7674
Chris Lattner882bdf22010-04-20 17:13:14 +00007675 QualType Type = E->getLHS()->getType();
7676 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007677
Richard Smithd62306a2011-11-10 06:34:14 +00007678 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007679 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007680 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007681
Richard Smith84c6b3d2013-09-10 21:34:14 +00007682 // As an extension, a type may have zero size (empty struct or union in
7683 // C, array of zero length). Pointer subtraction in such cases has
7684 // undefined behavior, so is not constant.
7685 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007686 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00007687 << ElementType;
7688 return false;
7689 }
7690
Richard Smith1b470412012-02-01 08:10:20 +00007691 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7692 // and produce incorrect results when it overflows. Such behavior
7693 // appears to be non-conforming, but is common, so perhaps we should
7694 // assume the standard intended for such cases to be undefined behavior
7695 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007696
Richard Smith1b470412012-02-01 08:10:20 +00007697 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7698 // overflow in the final conversion to ptrdiff_t.
7699 APSInt LHS(
7700 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7701 APSInt RHS(
7702 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7703 APSInt ElemSize(
7704 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7705 APSInt TrueResult = (LHS - RHS) / ElemSize;
7706 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7707
Richard Smith0c6124b2015-12-03 01:36:22 +00007708 if (Result.extend(65) != TrueResult &&
7709 !HandleOverflow(Info, E, TrueResult, E->getType()))
7710 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007711 return Success(Result, E);
7712 }
Richard Smithde21b242012-01-31 06:41:30 +00007713
7714 // C++11 [expr.rel]p3:
7715 // Pointers to void (after pointer conversions) can be compared, with a
7716 // result defined as follows: If both pointers represent the same
7717 // address or are both the null pointer value, the result is true if the
7718 // operator is <= or >= and false otherwise; otherwise the result is
7719 // unspecified.
7720 // We interpret this as applying to pointers to *cv* void.
7721 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007722 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007723 CCEDiag(E, diag::note_constexpr_void_comparison);
7724
Richard Smith84f6dcf2012-02-02 01:16:57 +00007725 // C++11 [expr.rel]p2:
7726 // - If two pointers point to non-static data members of the same object,
7727 // or to subobjects or array elements fo such members, recursively, the
7728 // pointer to the later declared member compares greater provided the
7729 // two members have the same access control and provided their class is
7730 // not a union.
7731 // [...]
7732 // - Otherwise pointer comparisons are unspecified.
7733 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7734 E->isRelationalOp()) {
7735 bool WasArrayIndex;
7736 unsigned Mismatch =
7737 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7738 RHSDesignator, WasArrayIndex);
7739 // At the point where the designators diverge, the comparison has a
7740 // specified value if:
7741 // - we are comparing array indices
7742 // - we are comparing fields of a union, or fields with the same access
7743 // Otherwise, the result is unspecified and thus the comparison is not a
7744 // constant expression.
7745 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7746 Mismatch < RHSDesignator.Entries.size()) {
7747 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7748 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7749 if (!LF && !RF)
7750 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7751 else if (!LF)
7752 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7753 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7754 << RF->getParent() << RF;
7755 else if (!RF)
7756 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7757 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7758 << LF->getParent() << LF;
7759 else if (!LF->getParent()->isUnion() &&
7760 LF->getAccess() != RF->getAccess())
7761 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7762 << LF << LF->getAccess() << RF << RF->getAccess()
7763 << LF->getParent();
7764 }
7765 }
7766
Eli Friedman6c31cb42012-04-16 04:30:08 +00007767 // The comparison here must be unsigned, and performed with the same
7768 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007769 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7770 uint64_t CompareLHS = LHSOffset.getQuantity();
7771 uint64_t CompareRHS = RHSOffset.getQuantity();
7772 assert(PtrSize <= 64 && "Unexpected pointer width");
7773 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7774 CompareLHS &= Mask;
7775 CompareRHS &= Mask;
7776
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007777 // If there is a base and this is a relational operator, we can only
7778 // compare pointers within the object in question; otherwise, the result
7779 // depends on where the object is located in memory.
7780 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7781 QualType BaseTy = getType(LHSValue.Base);
7782 if (BaseTy->isIncompleteType())
7783 return Error(E);
7784 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7785 uint64_t OffsetLimit = Size.getQuantity();
7786 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7787 return Error(E);
7788 }
7789
Richard Smith8b3497e2011-10-31 01:37:14 +00007790 switch (E->getOpcode()) {
7791 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007792 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7793 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7794 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7795 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7796 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7797 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007798 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007799 }
7800 }
Richard Smith7bb00672012-02-01 01:42:44 +00007801
7802 if (LHSTy->isMemberPointerType()) {
7803 assert(E->isEqualityOp() && "unexpected member pointer operation");
7804 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7805
7806 MemberPtr LHSValue, RHSValue;
7807
7808 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007809 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00007810 return false;
7811
7812 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7813 return false;
7814
7815 // C++11 [expr.eq]p2:
7816 // If both operands are null, they compare equal. Otherwise if only one is
7817 // null, they compare unequal.
7818 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7819 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7820 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7821 }
7822
7823 // Otherwise if either is a pointer to a virtual member function, the
7824 // result is unspecified.
7825 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7826 if (MD->isVirtual())
7827 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7828 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7829 if (MD->isVirtual())
7830 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7831
7832 // Otherwise they compare equal if and only if they would refer to the
7833 // same member of the same most derived object or the same subobject if
7834 // they were dereferenced with a hypothetical object of the associated
7835 // class type.
7836 bool Equal = LHSValue == RHSValue;
7837 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7838 }
7839
Richard Smithab44d9b2012-02-14 22:35:28 +00007840 if (LHSTy->isNullPtrType()) {
7841 assert(E->isComparisonOp() && "unexpected nullptr operation");
7842 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7843 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7844 // are compared, the result is true of the operator is <=, >= or ==, and
7845 // false otherwise.
7846 BinaryOperator::Opcode Opcode = E->getOpcode();
7847 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7848 }
7849
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007850 assert((!LHSTy->isIntegralOrEnumerationType() ||
7851 !RHSTy->isIntegralOrEnumerationType()) &&
7852 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7853 // We can't continue from here for non-integral types.
7854 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007855}
7856
Peter Collingbournee190dee2011-03-11 19:24:49 +00007857/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7858/// a result as the expression's type.
7859bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7860 const UnaryExprOrTypeTraitExpr *E) {
7861 switch(E->getKind()) {
7862 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007863 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007864 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007865 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007866 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007867 }
Eli Friedman64004332009-03-23 04:38:34 +00007868
Peter Collingbournee190dee2011-03-11 19:24:49 +00007869 case UETT_VecStep: {
7870 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007871
Peter Collingbournee190dee2011-03-11 19:24:49 +00007872 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007873 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007874
Peter Collingbournee190dee2011-03-11 19:24:49 +00007875 // The vec_step built-in functions that take a 3-component
7876 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7877 if (n == 3)
7878 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007879
Peter Collingbournee190dee2011-03-11 19:24:49 +00007880 return Success(n, E);
7881 } else
7882 return Success(1, E);
7883 }
7884
7885 case UETT_SizeOf: {
7886 QualType SrcTy = E->getTypeOfArgument();
7887 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7888 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007889 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7890 SrcTy = Ref->getPointeeType();
7891
Richard Smithd62306a2011-11-10 06:34:14 +00007892 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007893 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007894 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007895 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007896 }
Alexey Bataev00396512015-07-02 03:40:19 +00007897 case UETT_OpenMPRequiredSimdAlign:
7898 assert(E->isArgumentType());
7899 return Success(
7900 Info.Ctx.toCharUnitsFromBits(
7901 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7902 .getQuantity(),
7903 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007904 }
7905
7906 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007907}
7908
Peter Collingbournee9200682011-05-13 03:29:01 +00007909bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007910 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007911 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007912 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007913 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007914 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007915 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00007916 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00007917 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00007918 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007919 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007920 APSInt IdxResult;
7921 if (!EvaluateInteger(Idx, IdxResult, Info))
7922 return false;
7923 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7924 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007925 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007926 CurrentType = AT->getElementType();
7927 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7928 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007929 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007930 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007931
James Y Knight7281c352015-12-29 22:31:18 +00007932 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00007933 FieldDecl *MemberDecl = ON.getField();
7934 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007935 if (!RT)
7936 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007937 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007938 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007939 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007940 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007941 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007942 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007943 CurrentType = MemberDecl->getType().getNonReferenceType();
7944 break;
7945 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007946
James Y Knight7281c352015-12-29 22:31:18 +00007947 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00007948 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007949
James Y Knight7281c352015-12-29 22:31:18 +00007950 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00007951 CXXBaseSpecifier *BaseSpec = ON.getBase();
7952 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007953 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007954
7955 // Find the layout of the class whose base we are looking into.
7956 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007957 if (!RT)
7958 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007959 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007960 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007961 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7962
7963 // Find the base class itself.
7964 CurrentType = BaseSpec->getType();
7965 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7966 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007967 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007968
7969 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007970 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007971 break;
7972 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007973 }
7974 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007975 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007976}
7977
Chris Lattnere13042c2008-07-11 19:10:17 +00007978bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007979 switch (E->getOpcode()) {
7980 default:
7981 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7982 // See C99 6.6p3.
7983 return Error(E);
7984 case UO_Extension:
7985 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7986 // If so, we could clear the diagnostic ID.
7987 return Visit(E->getSubExpr());
7988 case UO_Plus:
7989 // The result is just the value.
7990 return Visit(E->getSubExpr());
7991 case UO_Minus: {
7992 if (!Visit(E->getSubExpr()))
7993 return false;
7994 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007995 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00007996 if (Value.isSigned() && Value.isMinSignedValue() &&
7997 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7998 E->getType()))
7999 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008000 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008001 }
8002 case UO_Not: {
8003 if (!Visit(E->getSubExpr()))
8004 return false;
8005 if (!Result.isInt()) return Error(E);
8006 return Success(~Result.getInt(), E);
8007 }
8008 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008009 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008010 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008011 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008012 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008013 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008014 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008015}
Mike Stump11289f42009-09-09 15:08:12 +00008016
Chris Lattner477c4be2008-07-12 01:15:53 +00008017/// HandleCast - This is used to evaluate implicit or explicit casts where the
8018/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008019bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8020 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008021 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008022 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008023
Eli Friedmanc757de22011-03-25 00:43:55 +00008024 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008025 case CK_BaseToDerived:
8026 case CK_DerivedToBase:
8027 case CK_UncheckedDerivedToBase:
8028 case CK_Dynamic:
8029 case CK_ToUnion:
8030 case CK_ArrayToPointerDecay:
8031 case CK_FunctionToPointerDecay:
8032 case CK_NullToPointer:
8033 case CK_NullToMemberPointer:
8034 case CK_BaseToDerivedMemberPointer:
8035 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008036 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008037 case CK_ConstructorConversion:
8038 case CK_IntegralToPointer:
8039 case CK_ToVoid:
8040 case CK_VectorSplat:
8041 case CK_IntegralToFloating:
8042 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008043 case CK_CPointerToObjCPointerCast:
8044 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008045 case CK_AnyPointerToBlockPointerCast:
8046 case CK_ObjCObjectLValueCast:
8047 case CK_FloatingRealToComplex:
8048 case CK_FloatingComplexToReal:
8049 case CK_FloatingComplexCast:
8050 case CK_FloatingComplexToIntegralComplex:
8051 case CK_IntegralRealToComplex:
8052 case CK_IntegralComplexCast:
8053 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008054 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008055 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008056 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008057 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008058 llvm_unreachable("invalid cast kind for integral value");
8059
Eli Friedman9faf2f92011-03-25 19:07:11 +00008060 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008061 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008062 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008063 case CK_ARCProduceObject:
8064 case CK_ARCConsumeObject:
8065 case CK_ARCReclaimReturnedObject:
8066 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008067 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008068 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008069
Richard Smith4ef685b2012-01-17 21:17:26 +00008070 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008071 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008072 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008073 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008074 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008075
8076 case CK_MemberPointerToBoolean:
8077 case CK_PointerToBoolean:
8078 case CK_IntegralToBoolean:
8079 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008080 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008081 case CK_FloatingComplexToBoolean:
8082 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008083 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008084 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008085 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008086 uint64_t IntResult = BoolResult;
8087 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8088 IntResult = (uint64_t)-1;
8089 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008090 }
8091
Eli Friedmanc757de22011-03-25 00:43:55 +00008092 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008093 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008094 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008095
Eli Friedman742421e2009-02-20 01:15:07 +00008096 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008097 // Allow casts of address-of-label differences if they are no-ops
8098 // or narrowing. (The narrowing case isn't actually guaranteed to
8099 // be constant-evaluatable except in some narrow cases which are hard
8100 // to detect here. We let it through on the assumption the user knows
8101 // what they are doing.)
8102 if (Result.isAddrLabelDiff())
8103 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008104 // Only allow casts of lvalues if they are lossless.
8105 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8106 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008107
Richard Smith911e1422012-01-30 22:27:01 +00008108 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8109 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008110 }
Mike Stump11289f42009-09-09 15:08:12 +00008111
Eli Friedmanc757de22011-03-25 00:43:55 +00008112 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008113 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8114
John McCall45d55e42010-05-07 21:00:08 +00008115 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008116 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008117 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008118
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008119 if (LV.getLValueBase()) {
8120 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008121 // FIXME: Allow a larger integer size than the pointer size, and allow
8122 // narrowing back down to pointer width in subsequent integral casts.
8123 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008124 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008125 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008126
Richard Smithcf74da72011-11-16 07:18:12 +00008127 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008128 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008129 return true;
8130 }
8131
Ken Dyck02990832010-01-15 12:37:54 +00008132 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8133 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008134 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008135 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008136
Eli Friedmanc757de22011-03-25 00:43:55 +00008137 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008138 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008139 if (!EvaluateComplex(SubExpr, C, Info))
8140 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008141 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008142 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008143
Eli Friedmanc757de22011-03-25 00:43:55 +00008144 case CK_FloatingToIntegral: {
8145 APFloat F(0.0);
8146 if (!EvaluateFloat(SubExpr, F, Info))
8147 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008148
Richard Smith357362d2011-12-13 06:39:58 +00008149 APSInt Value;
8150 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8151 return false;
8152 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008153 }
8154 }
Mike Stump11289f42009-09-09 15:08:12 +00008155
Eli Friedmanc757de22011-03-25 00:43:55 +00008156 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008157}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008158
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008159bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8160 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008161 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008162 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8163 return false;
8164 if (!LV.isComplexInt())
8165 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008166 return Success(LV.getComplexIntReal(), E);
8167 }
8168
8169 return Visit(E->getSubExpr());
8170}
8171
Eli Friedman4e7a2412009-02-27 04:45:43 +00008172bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008173 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008174 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008175 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8176 return false;
8177 if (!LV.isComplexInt())
8178 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008179 return Success(LV.getComplexIntImag(), E);
8180 }
8181
Richard Smith4a678122011-10-24 18:44:57 +00008182 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008183 return Success(0, E);
8184}
8185
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008186bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8187 return Success(E->getPackLength(), E);
8188}
8189
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008190bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8191 return Success(E->getValue(), E);
8192}
8193
Chris Lattner05706e882008-07-11 18:11:29 +00008194//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008195// Float Evaluation
8196//===----------------------------------------------------------------------===//
8197
8198namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008199class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008200 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008201 APFloat &Result;
8202public:
8203 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008204 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008205
Richard Smith2e312c82012-03-03 22:46:17 +00008206 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008207 Result = V.getFloat();
8208 return true;
8209 }
Eli Friedman24c01542008-08-22 00:06:13 +00008210
Richard Smithfddd3842011-12-30 21:15:51 +00008211 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008212 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8213 return true;
8214 }
8215
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008216 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008217
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008218 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008219 bool VisitBinaryOperator(const BinaryOperator *E);
8220 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008221 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008222
John McCallb1fb0d32010-05-07 22:08:54 +00008223 bool VisitUnaryReal(const UnaryOperator *E);
8224 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008225
Richard Smithfddd3842011-12-30 21:15:51 +00008226 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008227};
8228} // end anonymous namespace
8229
8230static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008231 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008232 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008233}
8234
Jay Foad39c79802011-01-12 09:06:06 +00008235static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008236 QualType ResultTy,
8237 const Expr *Arg,
8238 bool SNaN,
8239 llvm::APFloat &Result) {
8240 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8241 if (!S) return false;
8242
8243 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8244
8245 llvm::APInt fill;
8246
8247 // Treat empty strings as if they were zero.
8248 if (S->getString().empty())
8249 fill = llvm::APInt(32, 0);
8250 else if (S->getString().getAsInteger(0, fill))
8251 return false;
8252
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008253 if (Context.getTargetInfo().isNan2008()) {
8254 if (SNaN)
8255 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8256 else
8257 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8258 } else {
8259 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8260 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8261 // a different encoding to what became a standard in 2008, and for pre-
8262 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8263 // sNaN. This is now known as "legacy NaN" encoding.
8264 if (SNaN)
8265 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8266 else
8267 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8268 }
8269
John McCall16291492010-02-28 13:00:19 +00008270 return true;
8271}
8272
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008273bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008274 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008275 default:
8276 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8277
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008278 case Builtin::BI__builtin_huge_val:
8279 case Builtin::BI__builtin_huge_valf:
8280 case Builtin::BI__builtin_huge_vall:
8281 case Builtin::BI__builtin_inf:
8282 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008283 case Builtin::BI__builtin_infl: {
8284 const llvm::fltSemantics &Sem =
8285 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008286 Result = llvm::APFloat::getInf(Sem);
8287 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008288 }
Mike Stump11289f42009-09-09 15:08:12 +00008289
John McCall16291492010-02-28 13:00:19 +00008290 case Builtin::BI__builtin_nans:
8291 case Builtin::BI__builtin_nansf:
8292 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008293 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8294 true, Result))
8295 return Error(E);
8296 return true;
John McCall16291492010-02-28 13:00:19 +00008297
Chris Lattner0b7282e2008-10-06 06:31:58 +00008298 case Builtin::BI__builtin_nan:
8299 case Builtin::BI__builtin_nanf:
8300 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008301 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008302 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008303 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8304 false, Result))
8305 return Error(E);
8306 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008307
8308 case Builtin::BI__builtin_fabs:
8309 case Builtin::BI__builtin_fabsf:
8310 case Builtin::BI__builtin_fabsl:
8311 if (!EvaluateFloat(E->getArg(0), Result, Info))
8312 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008313
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008314 if (Result.isNegative())
8315 Result.changeSign();
8316 return true;
8317
Richard Smith8889a3d2013-06-13 06:26:32 +00008318 // FIXME: Builtin::BI__builtin_powi
8319 // FIXME: Builtin::BI__builtin_powif
8320 // FIXME: Builtin::BI__builtin_powil
8321
Mike Stump11289f42009-09-09 15:08:12 +00008322 case Builtin::BI__builtin_copysign:
8323 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008324 case Builtin::BI__builtin_copysignl: {
8325 APFloat RHS(0.);
8326 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8327 !EvaluateFloat(E->getArg(1), RHS, Info))
8328 return false;
8329 Result.copySign(RHS);
8330 return true;
8331 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008332 }
8333}
8334
John McCallb1fb0d32010-05-07 22:08:54 +00008335bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008336 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8337 ComplexValue CV;
8338 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8339 return false;
8340 Result = CV.FloatReal;
8341 return true;
8342 }
8343
8344 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008345}
8346
8347bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008348 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8349 ComplexValue CV;
8350 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8351 return false;
8352 Result = CV.FloatImag;
8353 return true;
8354 }
8355
Richard Smith4a678122011-10-24 18:44:57 +00008356 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008357 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8358 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008359 return true;
8360}
8361
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008362bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008363 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008364 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008365 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008366 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008367 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008368 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8369 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008370 Result.changeSign();
8371 return true;
8372 }
8373}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008374
Eli Friedman24c01542008-08-22 00:06:13 +00008375bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008376 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8377 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008378
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008379 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008380 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008381 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008382 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008383 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8384 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008385}
8386
8387bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8388 Result = E->getValue();
8389 return true;
8390}
8391
Peter Collingbournee9200682011-05-13 03:29:01 +00008392bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8393 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008394
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008395 switch (E->getCastKind()) {
8396 default:
Richard Smith11562c52011-10-28 17:51:58 +00008397 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008398
8399 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008400 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008401 return EvaluateInteger(SubExpr, IntResult, Info) &&
8402 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8403 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008404 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008405
8406 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008407 if (!Visit(SubExpr))
8408 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008409 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8410 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008411 }
John McCalld7646252010-11-14 08:17:51 +00008412
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008413 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008414 ComplexValue V;
8415 if (!EvaluateComplex(SubExpr, V, Info))
8416 return false;
8417 Result = V.getComplexFloatReal();
8418 return true;
8419 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008420 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008421}
8422
Eli Friedman24c01542008-08-22 00:06:13 +00008423//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008424// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008425//===----------------------------------------------------------------------===//
8426
8427namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008428class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008429 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008430 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008431
Anders Carlsson537969c2008-11-16 20:27:53 +00008432public:
John McCall93d91dc2010-05-07 17:22:02 +00008433 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008434 : ExprEvaluatorBaseTy(info), Result(Result) {}
8435
Richard Smith2e312c82012-03-03 22:46:17 +00008436 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008437 Result.setFrom(V);
8438 return true;
8439 }
Mike Stump11289f42009-09-09 15:08:12 +00008440
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008441 bool ZeroInitialization(const Expr *E);
8442
Anders Carlsson537969c2008-11-16 20:27:53 +00008443 //===--------------------------------------------------------------------===//
8444 // Visitor Methods
8445 //===--------------------------------------------------------------------===//
8446
Peter Collingbournee9200682011-05-13 03:29:01 +00008447 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008448 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008449 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008450 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008451 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008452};
8453} // end anonymous namespace
8454
John McCall93d91dc2010-05-07 17:22:02 +00008455static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8456 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008457 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008458 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008459}
8460
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008461bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008462 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008463 if (ElemTy->isRealFloatingType()) {
8464 Result.makeComplexFloat();
8465 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8466 Result.FloatReal = Zero;
8467 Result.FloatImag = Zero;
8468 } else {
8469 Result.makeComplexInt();
8470 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8471 Result.IntReal = Zero;
8472 Result.IntImag = Zero;
8473 }
8474 return true;
8475}
8476
Peter Collingbournee9200682011-05-13 03:29:01 +00008477bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8478 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008479
8480 if (SubExpr->getType()->isRealFloatingType()) {
8481 Result.makeComplexFloat();
8482 APFloat &Imag = Result.FloatImag;
8483 if (!EvaluateFloat(SubExpr, Imag, Info))
8484 return false;
8485
8486 Result.FloatReal = APFloat(Imag.getSemantics());
8487 return true;
8488 } else {
8489 assert(SubExpr->getType()->isIntegerType() &&
8490 "Unexpected imaginary literal.");
8491
8492 Result.makeComplexInt();
8493 APSInt &Imag = Result.IntImag;
8494 if (!EvaluateInteger(SubExpr, Imag, Info))
8495 return false;
8496
8497 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8498 return true;
8499 }
8500}
8501
Peter Collingbournee9200682011-05-13 03:29:01 +00008502bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008503
John McCallfcef3cf2010-12-14 17:51:41 +00008504 switch (E->getCastKind()) {
8505 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008506 case CK_BaseToDerived:
8507 case CK_DerivedToBase:
8508 case CK_UncheckedDerivedToBase:
8509 case CK_Dynamic:
8510 case CK_ToUnion:
8511 case CK_ArrayToPointerDecay:
8512 case CK_FunctionToPointerDecay:
8513 case CK_NullToPointer:
8514 case CK_NullToMemberPointer:
8515 case CK_BaseToDerivedMemberPointer:
8516 case CK_DerivedToBaseMemberPointer:
8517 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008518 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008519 case CK_ConstructorConversion:
8520 case CK_IntegralToPointer:
8521 case CK_PointerToIntegral:
8522 case CK_PointerToBoolean:
8523 case CK_ToVoid:
8524 case CK_VectorSplat:
8525 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008526 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008527 case CK_IntegralToBoolean:
8528 case CK_IntegralToFloating:
8529 case CK_FloatingToIntegral:
8530 case CK_FloatingToBoolean:
8531 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008532 case CK_CPointerToObjCPointerCast:
8533 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008534 case CK_AnyPointerToBlockPointerCast:
8535 case CK_ObjCObjectLValueCast:
8536 case CK_FloatingComplexToReal:
8537 case CK_FloatingComplexToBoolean:
8538 case CK_IntegralComplexToReal:
8539 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008540 case CK_ARCProduceObject:
8541 case CK_ARCConsumeObject:
8542 case CK_ARCReclaimReturnedObject:
8543 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008544 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008545 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008546 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008547 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008548 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008549 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008550
John McCallfcef3cf2010-12-14 17:51:41 +00008551 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008552 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008553 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008554 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008555
8556 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008557 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008558 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008559 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008560
8561 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008562 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008563 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008564 return false;
8565
John McCallfcef3cf2010-12-14 17:51:41 +00008566 Result.makeComplexFloat();
8567 Result.FloatImag = APFloat(Real.getSemantics());
8568 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008569 }
8570
John McCallfcef3cf2010-12-14 17:51:41 +00008571 case CK_FloatingComplexCast: {
8572 if (!Visit(E->getSubExpr()))
8573 return false;
8574
8575 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8576 QualType From
8577 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8578
Richard Smith357362d2011-12-13 06:39:58 +00008579 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8580 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008581 }
8582
8583 case CK_FloatingComplexToIntegralComplex: {
8584 if (!Visit(E->getSubExpr()))
8585 return false;
8586
8587 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8588 QualType From
8589 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8590 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008591 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8592 To, Result.IntReal) &&
8593 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8594 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008595 }
8596
8597 case CK_IntegralRealToComplex: {
8598 APSInt &Real = Result.IntReal;
8599 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8600 return false;
8601
8602 Result.makeComplexInt();
8603 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8604 return true;
8605 }
8606
8607 case CK_IntegralComplexCast: {
8608 if (!Visit(E->getSubExpr()))
8609 return false;
8610
8611 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8612 QualType From
8613 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8614
Richard Smith911e1422012-01-30 22:27:01 +00008615 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8616 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008617 return true;
8618 }
8619
8620 case CK_IntegralComplexToFloatingComplex: {
8621 if (!Visit(E->getSubExpr()))
8622 return false;
8623
Ted Kremenek28831752012-08-23 20:46:57 +00008624 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008625 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008626 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008627 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008628 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8629 To, Result.FloatReal) &&
8630 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8631 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008632 }
8633 }
8634
8635 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008636}
8637
John McCall93d91dc2010-05-07 17:22:02 +00008638bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008639 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008640 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8641
Chandler Carrutha216cad2014-10-11 00:57:18 +00008642 // Track whether the LHS or RHS is real at the type system level. When this is
8643 // the case we can simplify our evaluation strategy.
8644 bool LHSReal = false, RHSReal = false;
8645
8646 bool LHSOK;
8647 if (E->getLHS()->getType()->isRealFloatingType()) {
8648 LHSReal = true;
8649 APFloat &Real = Result.FloatReal;
8650 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8651 if (LHSOK) {
8652 Result.makeComplexFloat();
8653 Result.FloatImag = APFloat(Real.getSemantics());
8654 }
8655 } else {
8656 LHSOK = Visit(E->getLHS());
8657 }
George Burgess IVa145e252016-05-25 22:38:36 +00008658 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008659 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008660
John McCall93d91dc2010-05-07 17:22:02 +00008661 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008662 if (E->getRHS()->getType()->isRealFloatingType()) {
8663 RHSReal = true;
8664 APFloat &Real = RHS.FloatReal;
8665 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8666 return false;
8667 RHS.makeComplexFloat();
8668 RHS.FloatImag = APFloat(Real.getSemantics());
8669 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008670 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008671
Chandler Carrutha216cad2014-10-11 00:57:18 +00008672 assert(!(LHSReal && RHSReal) &&
8673 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008674 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008675 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008676 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008677 if (Result.isComplexFloat()) {
8678 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8679 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008680 if (LHSReal)
8681 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8682 else if (!RHSReal)
8683 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8684 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008685 } else {
8686 Result.getComplexIntReal() += RHS.getComplexIntReal();
8687 Result.getComplexIntImag() += RHS.getComplexIntImag();
8688 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008689 break;
John McCalle3027922010-08-25 11:45:40 +00008690 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008691 if (Result.isComplexFloat()) {
8692 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8693 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008694 if (LHSReal) {
8695 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8696 Result.getComplexFloatImag().changeSign();
8697 } else if (!RHSReal) {
8698 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8699 APFloat::rmNearestTiesToEven);
8700 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008701 } else {
8702 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8703 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8704 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008705 break;
John McCalle3027922010-08-25 11:45:40 +00008706 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008707 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008708 // This is an implementation of complex multiplication according to the
8709 // constraints laid out in C11 Annex G. The implemantion uses the
8710 // following naming scheme:
8711 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008712 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008713 APFloat &A = LHS.getComplexFloatReal();
8714 APFloat &B = LHS.getComplexFloatImag();
8715 APFloat &C = RHS.getComplexFloatReal();
8716 APFloat &D = RHS.getComplexFloatImag();
8717 APFloat &ResR = Result.getComplexFloatReal();
8718 APFloat &ResI = Result.getComplexFloatImag();
8719 if (LHSReal) {
8720 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8721 ResR = A * C;
8722 ResI = A * D;
8723 } else if (RHSReal) {
8724 ResR = C * A;
8725 ResI = C * B;
8726 } else {
8727 // In the fully general case, we need to handle NaNs and infinities
8728 // robustly.
8729 APFloat AC = A * C;
8730 APFloat BD = B * D;
8731 APFloat AD = A * D;
8732 APFloat BC = B * C;
8733 ResR = AC - BD;
8734 ResI = AD + BC;
8735 if (ResR.isNaN() && ResI.isNaN()) {
8736 bool Recalc = false;
8737 if (A.isInfinity() || B.isInfinity()) {
8738 A = APFloat::copySign(
8739 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8740 B = APFloat::copySign(
8741 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8742 if (C.isNaN())
8743 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8744 if (D.isNaN())
8745 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8746 Recalc = true;
8747 }
8748 if (C.isInfinity() || D.isInfinity()) {
8749 C = APFloat::copySign(
8750 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8751 D = APFloat::copySign(
8752 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8753 if (A.isNaN())
8754 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8755 if (B.isNaN())
8756 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8757 Recalc = true;
8758 }
8759 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8760 AD.isInfinity() || BC.isInfinity())) {
8761 if (A.isNaN())
8762 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8763 if (B.isNaN())
8764 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8765 if (C.isNaN())
8766 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8767 if (D.isNaN())
8768 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8769 Recalc = true;
8770 }
8771 if (Recalc) {
8772 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8773 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8774 }
8775 }
8776 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008777 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008778 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008779 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008780 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8781 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008782 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008783 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8784 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8785 }
8786 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008787 case BO_Div:
8788 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008789 // This is an implementation of complex division according to the
8790 // constraints laid out in C11 Annex G. The implemantion uses the
8791 // following naming scheme:
8792 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008793 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008794 APFloat &A = LHS.getComplexFloatReal();
8795 APFloat &B = LHS.getComplexFloatImag();
8796 APFloat &C = RHS.getComplexFloatReal();
8797 APFloat &D = RHS.getComplexFloatImag();
8798 APFloat &ResR = Result.getComplexFloatReal();
8799 APFloat &ResI = Result.getComplexFloatImag();
8800 if (RHSReal) {
8801 ResR = A / C;
8802 ResI = B / C;
8803 } else {
8804 if (LHSReal) {
8805 // No real optimizations we can do here, stub out with zero.
8806 B = APFloat::getZero(A.getSemantics());
8807 }
8808 int DenomLogB = 0;
8809 APFloat MaxCD = maxnum(abs(C), abs(D));
8810 if (MaxCD.isFinite()) {
8811 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00008812 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8813 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008814 }
8815 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00008816 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8817 APFloat::rmNearestTiesToEven);
8818 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8819 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008820 if (ResR.isNaN() && ResI.isNaN()) {
8821 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8822 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8823 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8824 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8825 D.isFinite()) {
8826 A = APFloat::copySign(
8827 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8828 B = APFloat::copySign(
8829 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8830 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8831 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8832 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8833 C = APFloat::copySign(
8834 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8835 D = APFloat::copySign(
8836 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8837 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8838 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8839 }
8840 }
8841 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008842 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008843 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8844 return Error(E, diag::note_expr_divide_by_zero);
8845
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008846 ComplexValue LHS = Result;
8847 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8848 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8849 Result.getComplexIntReal() =
8850 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8851 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8852 Result.getComplexIntImag() =
8853 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8854 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8855 }
8856 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008857 }
8858
John McCall93d91dc2010-05-07 17:22:02 +00008859 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008860}
8861
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008862bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8863 // Get the operand value into 'Result'.
8864 if (!Visit(E->getSubExpr()))
8865 return false;
8866
8867 switch (E->getOpcode()) {
8868 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008869 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008870 case UO_Extension:
8871 return true;
8872 case UO_Plus:
8873 // The result is always just the subexpr.
8874 return true;
8875 case UO_Minus:
8876 if (Result.isComplexFloat()) {
8877 Result.getComplexFloatReal().changeSign();
8878 Result.getComplexFloatImag().changeSign();
8879 }
8880 else {
8881 Result.getComplexIntReal() = -Result.getComplexIntReal();
8882 Result.getComplexIntImag() = -Result.getComplexIntImag();
8883 }
8884 return true;
8885 case UO_Not:
8886 if (Result.isComplexFloat())
8887 Result.getComplexFloatImag().changeSign();
8888 else
8889 Result.getComplexIntImag() = -Result.getComplexIntImag();
8890 return true;
8891 }
8892}
8893
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008894bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8895 if (E->getNumInits() == 2) {
8896 if (E->getType()->isComplexType()) {
8897 Result.makeComplexFloat();
8898 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8899 return false;
8900 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8901 return false;
8902 } else {
8903 Result.makeComplexInt();
8904 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8905 return false;
8906 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8907 return false;
8908 }
8909 return true;
8910 }
8911 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8912}
8913
Anders Carlsson537969c2008-11-16 20:27:53 +00008914//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008915// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8916// implicit conversion.
8917//===----------------------------------------------------------------------===//
8918
8919namespace {
8920class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008921 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008922 APValue &Result;
8923public:
8924 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8925 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8926
8927 bool Success(const APValue &V, const Expr *E) {
8928 Result = V;
8929 return true;
8930 }
8931
8932 bool ZeroInitialization(const Expr *E) {
8933 ImplicitValueInitExpr VIE(
8934 E->getType()->castAs<AtomicType>()->getValueType());
8935 return Evaluate(Result, Info, &VIE);
8936 }
8937
8938 bool VisitCastExpr(const CastExpr *E) {
8939 switch (E->getCastKind()) {
8940 default:
8941 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8942 case CK_NonAtomicToAtomic:
8943 return Evaluate(Result, Info, E->getSubExpr());
8944 }
8945 }
8946};
8947} // end anonymous namespace
8948
8949static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8950 assert(E->isRValue() && E->getType()->isAtomicType());
8951 return AtomicExprEvaluator(Info, Result).Visit(E);
8952}
8953
8954//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008955// Void expression evaluation, primarily for a cast to void on the LHS of a
8956// comma operator
8957//===----------------------------------------------------------------------===//
8958
8959namespace {
8960class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008961 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008962public:
8963 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8964
Richard Smith2e312c82012-03-03 22:46:17 +00008965 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008966
8967 bool VisitCastExpr(const CastExpr *E) {
8968 switch (E->getCastKind()) {
8969 default:
8970 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8971 case CK_ToVoid:
8972 VisitIgnoredValue(E->getSubExpr());
8973 return true;
8974 }
8975 }
Hal Finkela8443c32014-07-17 14:49:58 +00008976
8977 bool VisitCallExpr(const CallExpr *E) {
8978 switch (E->getBuiltinCallee()) {
8979 default:
8980 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8981 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008982 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008983 // The argument is not evaluated!
8984 return true;
8985 }
8986 }
Richard Smith42d3af92011-12-07 00:43:50 +00008987};
8988} // end anonymous namespace
8989
8990static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8991 assert(E->isRValue() && E->getType()->isVoidType());
8992 return VoidExprEvaluator(Info).Visit(E);
8993}
8994
8995//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008996// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008997//===----------------------------------------------------------------------===//
8998
Richard Smith2e312c82012-03-03 22:46:17 +00008999static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009000 // In C, function designators are not lvalues, but we evaluate them as if they
9001 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009002 QualType T = E->getType();
9003 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009004 LValue LV;
9005 if (!EvaluateLValue(E, LV, Info))
9006 return false;
9007 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009008 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009009 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009010 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009011 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009012 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009013 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009014 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009015 LValue LV;
9016 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009017 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009018 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009019 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009020 llvm::APFloat F(0.0);
9021 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009022 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009023 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009024 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009025 ComplexValue C;
9026 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009027 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009028 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009029 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009030 MemberPtr P;
9031 if (!EvaluateMemberPointer(E, P, Info))
9032 return false;
9033 P.moveInto(Result);
9034 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009035 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009036 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009037 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009038 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9039 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009040 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009041 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009042 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009043 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009044 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009045 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9046 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009047 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009048 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009049 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009050 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009051 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009052 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009053 if (!EvaluateVoid(E, Info))
9054 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009055 } else if (T->isAtomicType()) {
9056 if (!EvaluateAtomic(E, Result, Info))
9057 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009058 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009059 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009060 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009061 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009062 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009063 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009064 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009065
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009066 return true;
9067}
9068
Richard Smithb228a862012-02-15 02:18:13 +00009069/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9070/// cases, the in-place evaluation is essential, since later initializers for
9071/// an object can indirectly refer to subobjects which were initialized earlier.
9072static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009073 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009074 assert(!E->isValueDependent());
9075
Richard Smith7525ff62013-05-09 07:14:00 +00009076 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009077 return false;
9078
9079 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009080 // Evaluate arrays and record types in-place, so that later initializers can
9081 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009082 if (E->getType()->isArrayType())
9083 return EvaluateArray(E, This, Result, Info);
9084 else if (E->getType()->isRecordType())
9085 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009086 }
9087
9088 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009089 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009090}
9091
Richard Smithf57d8cb2011-12-09 22:58:01 +00009092/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9093/// lvalue-to-rvalue cast if it is an lvalue.
9094static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009095 if (E->getType().isNull())
9096 return false;
9097
Richard Smithfddd3842011-12-30 21:15:51 +00009098 if (!CheckLiteralType(Info, E))
9099 return false;
9100
Richard Smith2e312c82012-03-03 22:46:17 +00009101 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009102 return false;
9103
9104 if (E->isGLValue()) {
9105 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009106 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009107 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009108 return false;
9109 }
9110
Richard Smith2e312c82012-03-03 22:46:17 +00009111 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009112 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009113}
Richard Smith11562c52011-10-28 17:51:58 +00009114
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009115static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9116 const ASTContext &Ctx, bool &IsConst) {
9117 // Fast-path evaluations of integer literals, since we sometimes see files
9118 // containing vast quantities of these.
9119 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9120 Result.Val = APValue(APSInt(L->getValue(),
9121 L->getType()->isUnsignedIntegerType()));
9122 IsConst = true;
9123 return true;
9124 }
James Dennett0492ef02014-03-14 17:44:10 +00009125
9126 // This case should be rare, but we need to check it before we check on
9127 // the type below.
9128 if (Exp->getType().isNull()) {
9129 IsConst = false;
9130 return true;
9131 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009132
9133 // FIXME: Evaluating values of large array and record types can cause
9134 // performance problems. Only do so in C++11 for now.
9135 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9136 Exp->getType()->isRecordType()) &&
9137 !Ctx.getLangOpts().CPlusPlus11) {
9138 IsConst = false;
9139 return true;
9140 }
9141 return false;
9142}
9143
9144
Richard Smith7b553f12011-10-29 00:50:52 +00009145/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009146/// any crazy technique (that has nothing to do with language standards) that
9147/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009148/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9149/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009150bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009151 bool IsConst;
9152 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9153 return IsConst;
9154
Richard Smith6d4c6582013-11-05 22:18:15 +00009155 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009156 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009157}
9158
Jay Foad39c79802011-01-12 09:06:06 +00009159bool Expr::EvaluateAsBooleanCondition(bool &Result,
9160 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009161 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009162 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009163 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009164}
9165
Richard Smithce8eca52015-12-08 03:21:47 +00009166static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9167 Expr::SideEffectsKind SEK) {
9168 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9169 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9170}
9171
Richard Smith5fab0c92011-12-28 19:48:30 +00009172bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9173 SideEffectsKind AllowSideEffects) const {
9174 if (!getType()->isIntegralOrEnumerationType())
9175 return false;
9176
Richard Smith11562c52011-10-28 17:51:58 +00009177 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009178 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009179 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009180 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009181
Richard Smith11562c52011-10-28 17:51:58 +00009182 Result = ExprResult.Val.getInt();
9183 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009184}
9185
Richard Trieube234c32016-04-21 21:04:55 +00009186bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9187 SideEffectsKind AllowSideEffects) const {
9188 if (!getType()->isRealFloatingType())
9189 return false;
9190
9191 EvalResult ExprResult;
9192 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9193 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9194 return false;
9195
9196 Result = ExprResult.Val.getFloat();
9197 return true;
9198}
9199
Jay Foad39c79802011-01-12 09:06:06 +00009200bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009201 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009202
John McCall45d55e42010-05-07 21:00:08 +00009203 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009204 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9205 !CheckLValueConstantExpression(Info, getExprLoc(),
9206 Ctx.getLValueReferenceType(getType()), LV))
9207 return false;
9208
Richard Smith2e312c82012-03-03 22:46:17 +00009209 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009210 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009211}
9212
Richard Smithd0b4dd62011-12-19 06:19:21 +00009213bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9214 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009215 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009216 // FIXME: Evaluating initializers for large array and record types can cause
9217 // performance problems. Only do so in C++11 for now.
9218 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009219 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009220 return false;
9221
Richard Smithd0b4dd62011-12-19 06:19:21 +00009222 Expr::EvalStatus EStatus;
9223 EStatus.Diag = &Notes;
9224
Richard Smith0c6124b2015-12-03 01:36:22 +00009225 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9226 ? EvalInfo::EM_ConstantExpression
9227 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009228 InitInfo.setEvaluatingDecl(VD, Value);
9229
9230 LValue LVal;
9231 LVal.set(VD);
9232
Richard Smithfddd3842011-12-30 21:15:51 +00009233 // C++11 [basic.start.init]p2:
9234 // Variables with static storage duration or thread storage duration shall be
9235 // zero-initialized before any other initialization takes place.
9236 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009237 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009238 !VD->getType()->isReferenceType()) {
9239 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009240 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009241 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009242 return false;
9243 }
9244
Richard Smith7525ff62013-05-09 07:14:00 +00009245 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9246 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009247 EStatus.HasSideEffects)
9248 return false;
9249
9250 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9251 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009252}
9253
Richard Smith7b553f12011-10-29 00:50:52 +00009254/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9255/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009256bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009257 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009258 return EvaluateAsRValue(Result, Ctx) &&
9259 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009260}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009261
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009262APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009263 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009264 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009265 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009266 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009267 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009268 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009269 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009270
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009271 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009272}
John McCall864e3962010-05-07 05:32:02 +00009273
Richard Smithe9ff7702013-11-05 22:23:30 +00009274void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009275 bool IsConst;
9276 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009277 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009278 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009279 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9280 }
9281}
9282
Richard Smithe6c01442013-06-05 00:46:14 +00009283bool Expr::EvalResult::isGlobalLValue() const {
9284 assert(Val.isLValue());
9285 return IsGlobalLValue(Val.getLValueBase());
9286}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009287
9288
John McCall864e3962010-05-07 05:32:02 +00009289/// isIntegerConstantExpr - this recursive routine will test if an expression is
9290/// an integer constant expression.
9291
9292/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9293/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009294
9295// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009296// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9297// and a (possibly null) SourceLocation indicating the location of the problem.
9298//
John McCall864e3962010-05-07 05:32:02 +00009299// Note that to reduce code duplication, this helper does no evaluation
9300// itself; the caller checks whether the expression is evaluatable, and
9301// in the rare cases where CheckICE actually cares about the evaluated
9302// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009303
Dan Gohman28ade552010-07-26 21:25:24 +00009304namespace {
9305
Richard Smith9e575da2012-12-28 13:25:52 +00009306enum ICEKind {
9307 /// This expression is an ICE.
9308 IK_ICE,
9309 /// This expression is not an ICE, but if it isn't evaluated, it's
9310 /// a legal subexpression for an ICE. This return value is used to handle
9311 /// the comma operator in C99 mode, and non-constant subexpressions.
9312 IK_ICEIfUnevaluated,
9313 /// This expression is not an ICE, and is not a legal subexpression for one.
9314 IK_NotICE
9315};
9316
John McCall864e3962010-05-07 05:32:02 +00009317struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009318 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009319 SourceLocation Loc;
9320
Richard Smith9e575da2012-12-28 13:25:52 +00009321 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009322};
9323
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009324}
Dan Gohman28ade552010-07-26 21:25:24 +00009325
Richard Smith9e575da2012-12-28 13:25:52 +00009326static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9327
9328static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009329
Craig Toppera31a8822013-08-22 07:09:37 +00009330static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009331 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009332 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009333 !EVResult.Val.isInt())
9334 return ICEDiag(IK_NotICE, E->getLocStart());
9335
John McCall864e3962010-05-07 05:32:02 +00009336 return NoDiag();
9337}
9338
Craig Toppera31a8822013-08-22 07:09:37 +00009339static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009340 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009341 if (!E->getType()->isIntegralOrEnumerationType())
9342 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009343
9344 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009345#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009346#define STMT(Node, Base) case Expr::Node##Class:
9347#define EXPR(Node, Base)
9348#include "clang/AST/StmtNodes.inc"
9349 case Expr::PredefinedExprClass:
9350 case Expr::FloatingLiteralClass:
9351 case Expr::ImaginaryLiteralClass:
9352 case Expr::StringLiteralClass:
9353 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009354 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009355 case Expr::MemberExprClass:
9356 case Expr::CompoundAssignOperatorClass:
9357 case Expr::CompoundLiteralExprClass:
9358 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009359 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009360 case Expr::NoInitExprClass:
9361 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009362 case Expr::ImplicitValueInitExprClass:
9363 case Expr::ParenListExprClass:
9364 case Expr::VAArgExprClass:
9365 case Expr::AddrLabelExprClass:
9366 case Expr::StmtExprClass:
9367 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009368 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009369 case Expr::CXXDynamicCastExprClass:
9370 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009371 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009372 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009373 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009374 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009375 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009376 case Expr::CXXThisExprClass:
9377 case Expr::CXXThrowExprClass:
9378 case Expr::CXXNewExprClass:
9379 case Expr::CXXDeleteExprClass:
9380 case Expr::CXXPseudoDestructorExprClass:
9381 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009382 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009383 case Expr::DependentScopeDeclRefExprClass:
9384 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00009385 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009386 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009387 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009388 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009389 case Expr::CXXTemporaryObjectExprClass:
9390 case Expr::CXXUnresolvedConstructExprClass:
9391 case Expr::CXXDependentScopeMemberExprClass:
9392 case Expr::UnresolvedMemberExprClass:
9393 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009394 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009395 case Expr::ObjCArrayLiteralClass:
9396 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009397 case Expr::ObjCEncodeExprClass:
9398 case Expr::ObjCMessageExprClass:
9399 case Expr::ObjCSelectorExprClass:
9400 case Expr::ObjCProtocolExprClass:
9401 case Expr::ObjCIvarRefExprClass:
9402 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009403 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009404 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00009405 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +00009406 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009407 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009408 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009409 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009410 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009411 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009412 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009413 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009414 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009415 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009416 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009417 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009418 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009419 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009420 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009421 case Expr::CoawaitExprClass:
9422 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009423 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009424
Richard Smithf137f932014-01-25 20:50:08 +00009425 case Expr::InitListExprClass: {
9426 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9427 // form "T x = { a };" is equivalent to "T x = a;".
9428 // Unless we're initializing a reference, T is a scalar as it is known to be
9429 // of integral or enumeration type.
9430 if (E->isRValue())
9431 if (cast<InitListExpr>(E)->getNumInits() == 1)
9432 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9433 return ICEDiag(IK_NotICE, E->getLocStart());
9434 }
9435
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009436 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009437 case Expr::GNUNullExprClass:
9438 // GCC considers the GNU __null value to be an integral constant expression.
9439 return NoDiag();
9440
John McCall7c454bb2011-07-15 05:09:51 +00009441 case Expr::SubstNonTypeTemplateParmExprClass:
9442 return
9443 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9444
John McCall864e3962010-05-07 05:32:02 +00009445 case Expr::ParenExprClass:
9446 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009447 case Expr::GenericSelectionExprClass:
9448 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009449 case Expr::IntegerLiteralClass:
9450 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009451 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009452 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009453 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009454 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009455 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009456 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009457 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009458 return NoDiag();
9459 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009460 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009461 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9462 // constant expressions, but they can never be ICEs because an ICE cannot
9463 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009464 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009465 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009466 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009467 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009468 }
Richard Smith6365c912012-02-24 22:12:32 +00009469 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009470 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9471 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009472 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009473 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009474 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009475 // Parameter variables are never constants. Without this check,
9476 // getAnyInitializer() can find a default argument, which leads
9477 // to chaos.
9478 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009479 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009480
9481 // C++ 7.1.5.1p2
9482 // A variable of non-volatile const-qualified integral or enumeration
9483 // type initialized by an ICE can be used in ICEs.
9484 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009485 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009486 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009487
Richard Smithd0b4dd62011-12-19 06:19:21 +00009488 const VarDecl *VD;
9489 // Look for a declaration of this variable that has an initializer, and
9490 // check whether it is an ICE.
9491 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9492 return NoDiag();
9493 else
Richard Smith9e575da2012-12-28 13:25:52 +00009494 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009495 }
9496 }
Richard Smith9e575da2012-12-28 13:25:52 +00009497 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009498 }
John McCall864e3962010-05-07 05:32:02 +00009499 case Expr::UnaryOperatorClass: {
9500 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9501 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009502 case UO_PostInc:
9503 case UO_PostDec:
9504 case UO_PreInc:
9505 case UO_PreDec:
9506 case UO_AddrOf:
9507 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009508 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009509 // C99 6.6/3 allows increment and decrement within unevaluated
9510 // subexpressions of constant expressions, but they can never be ICEs
9511 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009512 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009513 case UO_Extension:
9514 case UO_LNot:
9515 case UO_Plus:
9516 case UO_Minus:
9517 case UO_Not:
9518 case UO_Real:
9519 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009520 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009521 }
Richard Smith9e575da2012-12-28 13:25:52 +00009522
John McCall864e3962010-05-07 05:32:02 +00009523 // OffsetOf falls through here.
9524 }
9525 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009526 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9527 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9528 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9529 // compliance: we should warn earlier for offsetof expressions with
9530 // array subscripts that aren't ICEs, and if the array subscripts
9531 // are ICEs, the value of the offsetof must be an integer constant.
9532 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009533 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009534 case Expr::UnaryExprOrTypeTraitExprClass: {
9535 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9536 if ((Exp->getKind() == UETT_SizeOf) &&
9537 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009538 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009539 return NoDiag();
9540 }
9541 case Expr::BinaryOperatorClass: {
9542 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9543 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009544 case BO_PtrMemD:
9545 case BO_PtrMemI:
9546 case BO_Assign:
9547 case BO_MulAssign:
9548 case BO_DivAssign:
9549 case BO_RemAssign:
9550 case BO_AddAssign:
9551 case BO_SubAssign:
9552 case BO_ShlAssign:
9553 case BO_ShrAssign:
9554 case BO_AndAssign:
9555 case BO_XorAssign:
9556 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009557 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9558 // constant expressions, but they can never be ICEs because an ICE cannot
9559 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009560 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009561
John McCalle3027922010-08-25 11:45:40 +00009562 case BO_Mul:
9563 case BO_Div:
9564 case BO_Rem:
9565 case BO_Add:
9566 case BO_Sub:
9567 case BO_Shl:
9568 case BO_Shr:
9569 case BO_LT:
9570 case BO_GT:
9571 case BO_LE:
9572 case BO_GE:
9573 case BO_EQ:
9574 case BO_NE:
9575 case BO_And:
9576 case BO_Xor:
9577 case BO_Or:
9578 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009579 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9580 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009581 if (Exp->getOpcode() == BO_Div ||
9582 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009583 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009584 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009585 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009586 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009587 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009588 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009589 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009590 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009591 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009592 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009593 }
9594 }
9595 }
John McCalle3027922010-08-25 11:45:40 +00009596 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009597 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009598 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9599 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009600 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9601 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009602 } else {
9603 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009604 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009605 }
9606 }
Richard Smith9e575da2012-12-28 13:25:52 +00009607 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009608 }
John McCalle3027922010-08-25 11:45:40 +00009609 case BO_LAnd:
9610 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009611 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9612 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009613 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009614 // Rare case where the RHS has a comma "side-effect"; we need
9615 // to actually check the condition to see whether the side
9616 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009617 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009618 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009619 return RHSResult;
9620 return NoDiag();
9621 }
9622
Richard Smith9e575da2012-12-28 13:25:52 +00009623 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009624 }
9625 }
9626 }
9627 case Expr::ImplicitCastExprClass:
9628 case Expr::CStyleCastExprClass:
9629 case Expr::CXXFunctionalCastExprClass:
9630 case Expr::CXXStaticCastExprClass:
9631 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009632 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009633 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009634 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009635 if (isa<ExplicitCastExpr>(E)) {
9636 if (const FloatingLiteral *FL
9637 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9638 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9639 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9640 APSInt IgnoredVal(DestWidth, !DestSigned);
9641 bool Ignored;
9642 // If the value does not fit in the destination type, the behavior is
9643 // undefined, so we are not required to treat it as a constant
9644 // expression.
9645 if (FL->getValue().convertToInteger(IgnoredVal,
9646 llvm::APFloat::rmTowardZero,
9647 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009648 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009649 return NoDiag();
9650 }
9651 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009652 switch (cast<CastExpr>(E)->getCastKind()) {
9653 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009654 case CK_AtomicToNonAtomic:
9655 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009656 case CK_NoOp:
9657 case CK_IntegralToBoolean:
9658 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009659 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009660 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009661 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009662 }
John McCall864e3962010-05-07 05:32:02 +00009663 }
John McCallc07a0c72011-02-17 10:25:35 +00009664 case Expr::BinaryConditionalOperatorClass: {
9665 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9666 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009667 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009668 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009669 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9670 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9671 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009672 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009673 return FalseResult;
9674 }
John McCall864e3962010-05-07 05:32:02 +00009675 case Expr::ConditionalOperatorClass: {
9676 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9677 // If the condition (ignoring parens) is a __builtin_constant_p call,
9678 // then only the true side is actually considered in an integer constant
9679 // expression, and it is fully evaluated. This is an important GNU
9680 // extension. See GCC PR38377 for discussion.
9681 if (const CallExpr *CallCE
9682 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009683 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009684 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009685 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009686 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009687 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009688
Richard Smithf57d8cb2011-12-09 22:58:01 +00009689 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9690 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009691
Richard Smith9e575da2012-12-28 13:25:52 +00009692 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009693 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009694 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009695 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009696 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009697 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009698 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009699 return NoDiag();
9700 // Rare case where the diagnostics depend on which side is evaluated
9701 // Note that if we get here, CondResult is 0, and at least one of
9702 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009703 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009704 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009705 return TrueResult;
9706 }
9707 case Expr::CXXDefaultArgExprClass:
9708 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009709 case Expr::CXXDefaultInitExprClass:
9710 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009711 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009712 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009713 }
9714 }
9715
David Blaikiee4d798f2012-01-20 21:50:17 +00009716 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009717}
9718
Richard Smithf57d8cb2011-12-09 22:58:01 +00009719/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009720static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009721 const Expr *E,
9722 llvm::APSInt *Value,
9723 SourceLocation *Loc) {
9724 if (!E->getType()->isIntegralOrEnumerationType()) {
9725 if (Loc) *Loc = E->getExprLoc();
9726 return false;
9727 }
9728
Richard Smith66e05fe2012-01-18 05:21:49 +00009729 APValue Result;
9730 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009731 return false;
9732
Richard Smith98710fc2014-11-13 23:03:19 +00009733 if (!Result.isInt()) {
9734 if (Loc) *Loc = E->getExprLoc();
9735 return false;
9736 }
9737
Richard Smith66e05fe2012-01-18 05:21:49 +00009738 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009739 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009740}
9741
Craig Toppera31a8822013-08-22 07:09:37 +00009742bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9743 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009744 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009745 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009746
Richard Smith9e575da2012-12-28 13:25:52 +00009747 ICEDiag D = CheckICE(this, Ctx);
9748 if (D.Kind != IK_ICE) {
9749 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009750 return false;
9751 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009752 return true;
9753}
9754
Craig Toppera31a8822013-08-22 07:09:37 +00009755bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009756 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009757 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009758 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9759
9760 if (!isIntegerConstantExpr(Ctx, Loc))
9761 return false;
Richard Smith5c40f092015-12-04 03:00:44 +00009762 // The only possible side-effects here are due to UB discovered in the
9763 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9764 // required to treat the expression as an ICE, so we produce the folded
9765 // value.
9766 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +00009767 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009768 return true;
9769}
Richard Smith66e05fe2012-01-18 05:21:49 +00009770
Craig Toppera31a8822013-08-22 07:09:37 +00009771bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009772 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009773}
9774
Craig Toppera31a8822013-08-22 07:09:37 +00009775bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009776 SourceLocation *Loc) const {
9777 // We support this checking in C++98 mode in order to diagnose compatibility
9778 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009779 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009780
Richard Smith98a0a492012-02-14 21:38:30 +00009781 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009782 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009783 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009784 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009785 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009786
9787 APValue Scratch;
9788 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9789
9790 if (!Diags.empty()) {
9791 IsConstExpr = false;
9792 if (Loc) *Loc = Diags[0].first;
9793 } else if (!IsConstExpr) {
9794 // FIXME: This shouldn't happen.
9795 if (Loc) *Loc = getExprLoc();
9796 }
9797
9798 return IsConstExpr;
9799}
Richard Smith253c2a32012-01-27 01:14:48 +00009800
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009801bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9802 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009803 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009804 Expr::EvalStatus Status;
9805 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9806
9807 ArgVector ArgValues(Args.size());
9808 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9809 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009810 if ((*I)->isValueDependent() ||
9811 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009812 // If evaluation fails, throw away the argument entirely.
9813 ArgValues[I - Args.begin()] = APValue();
9814 if (Info.EvalStatus.HasSideEffects)
9815 return false;
9816 }
9817
9818 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009819 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009820 ArgValues.data());
9821 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9822}
9823
Richard Smith253c2a32012-01-27 01:14:48 +00009824bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009825 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009826 PartialDiagnosticAt> &Diags) {
9827 // FIXME: It would be useful to check constexpr function templates, but at the
9828 // moment the constant expression evaluator cannot cope with the non-rigorous
9829 // ASTs which we build for dependent expressions.
9830 if (FD->isDependentContext())
9831 return true;
9832
9833 Expr::EvalStatus Status;
9834 Status.Diag = &Diags;
9835
Richard Smith6d4c6582013-11-05 22:18:15 +00009836 EvalInfo Info(FD->getASTContext(), Status,
9837 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009838
9839 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009840 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009841
Richard Smith7525ff62013-05-09 07:14:00 +00009842 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009843 // is a temporary being used as the 'this' pointer.
9844 LValue This;
9845 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009846 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009847
Richard Smith253c2a32012-01-27 01:14:48 +00009848 ArrayRef<const Expr*> Args;
9849
Richard Smith2e312c82012-03-03 22:46:17 +00009850 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009851 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9852 // Evaluate the call as a constant initializer, to allow the construction
9853 // of objects of non-literal types.
9854 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +00009855 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
9856 } else {
9857 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +00009858 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009859 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +00009860 }
Richard Smith253c2a32012-01-27 01:14:48 +00009861
9862 return Diags.empty();
9863}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009864
9865bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9866 const FunctionDecl *FD,
9867 SmallVectorImpl<
9868 PartialDiagnosticAt> &Diags) {
9869 Expr::EvalStatus Status;
9870 Status.Diag = &Diags;
9871
9872 EvalInfo Info(FD->getASTContext(), Status,
9873 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9874
9875 // Fabricate a call stack frame to give the arguments a plausible cover story.
9876 ArrayRef<const Expr*> Args;
9877 ArgVector ArgValues(0);
9878 bool Success = EvaluateArgs(Args, ArgValues, Info);
9879 (void)Success;
9880 assert(Success &&
9881 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009882 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009883
9884 APValue ResultScratch;
9885 Evaluate(ResultScratch, Info, E);
9886 return Diags.empty();
9887}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009888
9889bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9890 unsigned Type) const {
9891 if (!getType()->isPointerType())
9892 return false;
9893
9894 Expr::EvalStatus Status;
9895 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9896 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
9897}