blob: 8c24b0333e1f4762bb219a7de599232c9b4e179b [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.
161 bool Invalid : 1;
162
Richard Smitha8105bc2012-01-06 16:39:00 +0000163 /// Is this a pointer one past the end of an object?
164 bool 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.
167 bool MostDerivedIsArrayElement : 1;
168
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.
565 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
566 return false;
567 }
Richard Smith357362d2011-12-13 06:39:58 +0000568 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
569 return true;
570 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
571 << 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) {
587 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
588 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
Richard Smith357362d2011-12-13 06:39:58 +0000605 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000606 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000607 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
608 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000609 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000610 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000611 // If we have a prior diagnostic, it will be noting that the expression
612 // isn't a constant expression. This diagnostic is more important,
613 // unless we require this evaluation to produce a constant expression.
614 //
615 // FIXME: We might want to show both diagnostics to the user in
616 // EM_ConstantFold mode.
617 if (!EvalStatus.Diag->empty()) {
618 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000619 case EM_ConstantFold:
620 case EM_IgnoreSideEffects:
621 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000622 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000623 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000624 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000625 case EM_ConstantExpression:
626 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000627 case EM_ConstantExpressionUnevaluated:
628 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000629 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000630 HasActiveDiagnostic = false;
631 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000632 }
633 }
634
Richard Smithf6f003a2011-12-16 19:06:07 +0000635 unsigned CallStackNotes = CallStackDepth - 1;
636 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
637 if (Limit)
638 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000639 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000640 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000641
Richard Smith357362d2011-12-13 06:39:58 +0000642 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000643 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000644 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000645 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
646 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000647 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000648 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000649 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000650 }
Richard Smith357362d2011-12-13 06:39:58 +0000651 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000652 return OptionalDiagnostic();
653 }
654
Richard Smithce1ec5e2012-03-15 04:53:45 +0000655 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
656 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000657 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000658 if (EvalStatus.Diag)
Richard Smith0c6124b2015-12-03 01:36:22 +0000659 return Diag(E->getExprLoc(), DiagId, ExtraNotes, IsCCEDiag);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000660 HasActiveDiagnostic = false;
661 return OptionalDiagnostic();
662 }
663
Richard Smith92b1ce02011-12-12 09:28:41 +0000664 /// Diagnose that the evaluation does not produce a C++11 core constant
665 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000666 ///
667 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
668 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000669 template<typename LocArg>
670 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000671 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000672 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000673 // Don't override a previous diagnostic. Don't bother collecting
674 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000675 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000676 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000677 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000678 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000679 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000680 }
681
682 /// Add a note to a prior diagnostic.
683 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
684 if (!HasActiveDiagnostic)
685 return OptionalDiagnostic();
686 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000687 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000688
689 /// Add a stack of notes to a prior diagnostic.
690 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
691 if (HasActiveDiagnostic) {
692 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
693 Diags.begin(), Diags.end());
694 }
695 }
Richard Smith253c2a32012-01-27 01:14:48 +0000696
Richard Smith6d4c6582013-11-05 22:18:15 +0000697 /// Should we continue evaluation after encountering a side-effect that we
698 /// couldn't model?
699 bool keepEvaluatingAfterSideEffect() {
700 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000701 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000702 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 case EM_EvaluateForOverflow:
704 case EM_IgnoreSideEffects:
705 return true;
706
Richard Smith6d4c6582013-11-05 22:18:15 +0000707 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000708 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000709 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000710 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000711 return false;
712 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000713 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000714 }
715
716 /// Note that we have had a side-effect, and determine whether we should
717 /// keep evaluating.
718 bool noteSideEffect() {
719 EvalStatus.HasSideEffects = true;
720 return keepEvaluatingAfterSideEffect();
721 }
722
Richard Smithce8eca52015-12-08 03:21:47 +0000723 /// Should we continue evaluation after encountering undefined behavior?
724 bool keepEvaluatingAfterUndefinedBehavior() {
725 switch (EvalMode) {
726 case EM_EvaluateForOverflow:
727 case EM_IgnoreSideEffects:
728 case EM_ConstantFold:
729 case EM_DesignatorFold:
730 return true;
731
732 case EM_PotentialConstantExpression:
733 case EM_PotentialConstantExpressionUnevaluated:
734 case EM_ConstantExpression:
735 case EM_ConstantExpressionUnevaluated:
736 return false;
737 }
738 llvm_unreachable("Missed EvalMode case");
739 }
740
741 /// Note that we hit something that was technically undefined behavior, but
742 /// that we can evaluate past it (such as signed overflow or floating-point
743 /// division by zero.)
744 bool noteUndefinedBehavior() {
745 EvalStatus.HasUndefinedBehavior = true;
746 return keepEvaluatingAfterUndefinedBehavior();
747 }
748
Richard Smith253c2a32012-01-27 01:14:48 +0000749 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000750 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000751 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000752 if (!StepsLeft)
753 return false;
754
755 switch (EvalMode) {
756 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000757 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000758 case EM_EvaluateForOverflow:
759 return true;
760
761 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000762 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000763 case EM_ConstantFold:
764 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000765 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000766 return false;
767 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000768 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000769 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000770
George Burgess IV8c892b52016-05-25 22:31:54 +0000771 /// Notes that we failed to evaluate an expression that other expressions
772 /// directly depend on, and determine if we should keep evaluating. This
773 /// should only be called if we actually intend to keep evaluating.
774 ///
775 /// Call noteSideEffect() instead if we may be able to ignore the value that
776 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
777 ///
778 /// (Foo(), 1) // use noteSideEffect
779 /// (Foo() || true) // use noteSideEffect
780 /// Foo() + 1 // use noteFailure
781 LLVM_ATTRIBUTE_UNUSED_RESULT bool noteFailure() {
782 // Failure when evaluating some expression often means there is some
783 // subexpression whose evaluation was skipped. Therefore, (because we
784 // don't track whether we skipped an expression when unwinding after an
785 // evaluation failure) every evaluation failure that bubbles up from a
786 // subexpression implies that a side-effect has potentially happened. We
787 // skip setting the HasSideEffects flag to true until we decide to
788 // continue evaluating after that point, which happens here.
789 bool KeepGoing = keepEvaluatingAfterFailure();
790 EvalStatus.HasSideEffects |= KeepGoing;
791 return KeepGoing;
792 }
793
George Burgess IV3a03fab2015-09-04 21:28:13 +0000794 bool allowInvalidBaseExpr() const {
795 return EvalMode == EM_DesignatorFold;
796 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000797 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000798
799 /// Object used to treat all foldable expressions as constant expressions.
800 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000801 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000802 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000803 bool HadNoPriorDiags;
804 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000805
Richard Smith6d4c6582013-11-05 22:18:15 +0000806 explicit FoldConstant(EvalInfo &Info, bool Enabled)
807 : Info(Info),
808 Enabled(Enabled),
809 HadNoPriorDiags(Info.EvalStatus.Diag &&
810 Info.EvalStatus.Diag->empty() &&
811 !Info.EvalStatus.HasSideEffects),
812 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000813 if (Enabled &&
814 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
815 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000816 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000817 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000818 void keepDiagnostics() { Enabled = false; }
819 ~FoldConstant() {
820 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000821 !Info.EvalStatus.HasSideEffects)
822 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000823 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000824 }
825 };
Richard Smith17100ba2012-02-16 02:46:34 +0000826
George Burgess IV3a03fab2015-09-04 21:28:13 +0000827 /// RAII object used to treat the current evaluation as the correct pointer
828 /// offset fold for the current EvalMode
829 struct FoldOffsetRAII {
830 EvalInfo &Info;
831 EvalInfo::EvaluationMode OldMode;
832 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
833 : Info(Info), OldMode(Info.EvalMode) {
834 if (!Info.checkingPotentialConstantExpression())
835 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
836 : EvalInfo::EM_ConstantFold;
837 }
838
839 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
840 };
841
George Burgess IV8c892b52016-05-25 22:31:54 +0000842 /// RAII object used to optionally suppress diagnostics and side-effects from
843 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000844 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000845 /// Pair of EvalInfo, and a bit that stores whether or not we were
846 /// speculatively evaluating when we created this RAII.
847 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000848 Expr::EvalStatus Old;
849
George Burgess IV8c892b52016-05-25 22:31:54 +0000850 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
851 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
852 Old = Other.Old;
853 Other.InfoAndOldSpecEval.setPointer(nullptr);
854 }
855
856 void maybeRestoreState() {
857 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
858 if (!Info)
859 return;
860
861 Info->EvalStatus = Old;
862 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
863 }
864
Richard Smith17100ba2012-02-16 02:46:34 +0000865 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000866 SpeculativeEvaluationRAII() = default;
867
868 SpeculativeEvaluationRAII(
869 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
870 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
871 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000872 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000873 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000874 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000875
876 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
877 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
878 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000879 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000880
881 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
882 maybeRestoreState();
883 moveFromAndCancel(std::move(Other));
884 return *this;
885 }
886
887 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000888 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000889
890 /// RAII object wrapping a full-expression or block scope, and handling
891 /// the ending of the lifetime of temporaries created within it.
892 template<bool IsFullExpression>
893 class ScopeRAII {
894 EvalInfo &Info;
895 unsigned OldStackSize;
896 public:
897 ScopeRAII(EvalInfo &Info)
898 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
899 ~ScopeRAII() {
900 // Body moved to a static method to encourage the compiler to inline away
901 // instances of this class.
902 cleanup(Info, OldStackSize);
903 }
904 private:
905 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
906 unsigned NewEnd = OldStackSize;
907 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
908 I != N; ++I) {
909 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
910 // Full-expression cleanup of a lifetime-extended temporary: nothing
911 // to do, just move this cleanup to the right place in the stack.
912 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
913 ++NewEnd;
914 } else {
915 // End the lifetime of the object.
916 Info.CleanupStack[I].endLifetime();
917 }
918 }
919 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
920 Info.CleanupStack.end());
921 }
922 };
923 typedef ScopeRAII<false> BlockScopeRAII;
924 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000925}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000926
Richard Smitha8105bc2012-01-06 16:39:00 +0000927bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
928 CheckSubobjectKind CSK) {
929 if (Invalid)
930 return false;
931 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000932 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000933 << CSK;
934 setInvalid();
935 return false;
936 }
937 return true;
938}
939
940void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
941 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000942 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000943 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000944 << static_cast<int>(N) << /*array*/ 0
945 << static_cast<unsigned>(MostDerivedArraySize);
946 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000947 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000948 << static_cast<int>(N) << /*non-array*/ 1;
949 setInvalid();
950}
951
Richard Smithf6f003a2011-12-16 19:06:07 +0000952CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
953 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000954 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000955 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000956 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000957 Info.CurrentCall = this;
958 ++Info.CallStackDepth;
959}
960
961CallStackFrame::~CallStackFrame() {
962 assert(Info.CurrentCall == this && "calls retired out of order");
963 --Info.CallStackDepth;
964 Info.CurrentCall = Caller;
965}
966
Richard Smith08d6a2c2013-07-24 07:11:57 +0000967APValue &CallStackFrame::createTemporary(const void *Key,
968 bool IsLifetimeExtended) {
969 APValue &Result = Temporaries[Key];
970 assert(Result.isUninit() && "temporary created multiple times");
971 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
972 return Result;
973}
974
Richard Smith84401042013-06-03 05:03:02 +0000975static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000976
977void EvalInfo::addCallStack(unsigned Limit) {
978 // Determine which calls to skip, if any.
979 unsigned ActiveCalls = CallStackDepth - 1;
980 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
981 if (Limit && Limit < ActiveCalls) {
982 SkipStart = Limit / 2 + Limit % 2;
983 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000984 }
985
Richard Smithf6f003a2011-12-16 19:06:07 +0000986 // Walk the call stack and add the diagnostics.
987 unsigned CallIdx = 0;
988 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
989 Frame = Frame->Caller, ++CallIdx) {
990 // Skip this call?
991 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
992 if (CallIdx == SkipStart) {
993 // Note that we're skipping calls.
994 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
995 << unsigned(ActiveCalls - Limit);
996 }
997 continue;
998 }
999
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001000 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001001 llvm::raw_svector_ostream Out(Buffer);
1002 describeCall(Frame, Out);
1003 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1004 }
1005}
1006
1007namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001008 struct ComplexValue {
1009 private:
1010 bool IsInt;
1011
1012 public:
1013 APSInt IntReal, IntImag;
1014 APFloat FloatReal, FloatImag;
1015
1016 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
1017
1018 void makeComplexFloat() { IsInt = false; }
1019 bool isComplexFloat() const { return !IsInt; }
1020 APFloat &getComplexFloatReal() { return FloatReal; }
1021 APFloat &getComplexFloatImag() { return FloatImag; }
1022
1023 void makeComplexInt() { IsInt = true; }
1024 bool isComplexInt() const { return IsInt; }
1025 APSInt &getComplexIntReal() { return IntReal; }
1026 APSInt &getComplexIntImag() { return IntImag; }
1027
Richard Smith2e312c82012-03-03 22:46:17 +00001028 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001029 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001030 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001031 else
Richard Smith2e312c82012-03-03 22:46:17 +00001032 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001033 }
Richard Smith2e312c82012-03-03 22:46:17 +00001034 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001035 assert(v.isComplexFloat() || v.isComplexInt());
1036 if (v.isComplexFloat()) {
1037 makeComplexFloat();
1038 FloatReal = v.getComplexFloatReal();
1039 FloatImag = v.getComplexFloatImag();
1040 } else {
1041 makeComplexInt();
1042 IntReal = v.getComplexIntReal();
1043 IntImag = v.getComplexIntImag();
1044 }
1045 }
John McCall93d91dc2010-05-07 17:22:02 +00001046 };
John McCall45d55e42010-05-07 21:00:08 +00001047
1048 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001049 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001050 CharUnits Offset;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001051 bool InvalidBase : 1;
1052 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001053 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +00001054
Richard Smithce40ad62011-11-12 22:28:03 +00001055 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001056 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001057 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001058 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001059 SubobjectDesignator &getLValueDesignator() { return Designator; }
1060 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +00001061
Richard Smith2e312c82012-03-03 22:46:17 +00001062 void moveInto(APValue &V) const {
1063 if (Designator.Invalid)
1064 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1065 else
1066 V = APValue(Base, Offset, Designator.Entries,
1067 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +00001068 }
Richard Smith2e312c82012-03-03 22:46:17 +00001069 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001070 assert(V.isLValue());
1071 Base = V.getLValueBase();
1072 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001073 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001074 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001075 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +00001076 }
1077
George Burgess IV3a03fab2015-09-04 21:28:13 +00001078 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +00001079 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +00001080 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001081 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001082 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001083 Designator = SubobjectDesignator(getType(B));
1084 }
1085
George Burgess IV3a03fab2015-09-04 21:28:13 +00001086 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1087 set(B, I, true);
1088 }
1089
Richard Smitha8105bc2012-01-06 16:39:00 +00001090 // Check that this LValue is not based on a null pointer. If it is, produce
1091 // a diagnostic and mark the designator as invalid.
1092 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1093 CheckSubobjectKind CSK) {
1094 if (Designator.Invalid)
1095 return false;
1096 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001097 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001098 << CSK;
1099 Designator.setInvalid();
1100 return false;
1101 }
1102 return true;
1103 }
1104
1105 // Check this LValue refers to an object. If not, set the designator to be
1106 // invalid and emit a diagnostic.
1107 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001108 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001109 Designator.checkSubobject(Info, E, CSK);
1110 }
1111
1112 void addDecl(EvalInfo &Info, const Expr *E,
1113 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001114 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1115 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001116 }
1117 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001118 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1119 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001120 }
Richard Smith66c96992012-02-18 22:04:06 +00001121 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001122 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1123 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001124 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001125 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001126 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001127 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001128 }
John McCall45d55e42010-05-07 21:00:08 +00001129 };
Richard Smith027bf112011-11-17 22:56:20 +00001130
1131 struct MemberPtr {
1132 MemberPtr() {}
1133 explicit MemberPtr(const ValueDecl *Decl) :
1134 DeclAndIsDerivedMember(Decl, false), Path() {}
1135
1136 /// The member or (direct or indirect) field referred to by this member
1137 /// pointer, or 0 if this is a null member pointer.
1138 const ValueDecl *getDecl() const {
1139 return DeclAndIsDerivedMember.getPointer();
1140 }
1141 /// Is this actually a member of some type derived from the relevant class?
1142 bool isDerivedMember() const {
1143 return DeclAndIsDerivedMember.getInt();
1144 }
1145 /// Get the class which the declaration actually lives in.
1146 const CXXRecordDecl *getContainingRecord() const {
1147 return cast<CXXRecordDecl>(
1148 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1149 }
1150
Richard Smith2e312c82012-03-03 22:46:17 +00001151 void moveInto(APValue &V) const {
1152 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001153 }
Richard Smith2e312c82012-03-03 22:46:17 +00001154 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001155 assert(V.isMemberPointer());
1156 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1157 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1158 Path.clear();
1159 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1160 Path.insert(Path.end(), P.begin(), P.end());
1161 }
1162
1163 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1164 /// whether the member is a member of some class derived from the class type
1165 /// of the member pointer.
1166 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1167 /// Path - The path of base/derived classes from the member declaration's
1168 /// class (exclusive) to the class type of the member pointer (inclusive).
1169 SmallVector<const CXXRecordDecl*, 4> Path;
1170
1171 /// Perform a cast towards the class of the Decl (either up or down the
1172 /// hierarchy).
1173 bool castBack(const CXXRecordDecl *Class) {
1174 assert(!Path.empty());
1175 const CXXRecordDecl *Expected;
1176 if (Path.size() >= 2)
1177 Expected = Path[Path.size() - 2];
1178 else
1179 Expected = getContainingRecord();
1180 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1181 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1182 // if B does not contain the original member and is not a base or
1183 // derived class of the class containing the original member, the result
1184 // of the cast is undefined.
1185 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1186 // (D::*). We consider that to be a language defect.
1187 return false;
1188 }
1189 Path.pop_back();
1190 return true;
1191 }
1192 /// Perform a base-to-derived member pointer cast.
1193 bool castToDerived(const CXXRecordDecl *Derived) {
1194 if (!getDecl())
1195 return true;
1196 if (!isDerivedMember()) {
1197 Path.push_back(Derived);
1198 return true;
1199 }
1200 if (!castBack(Derived))
1201 return false;
1202 if (Path.empty())
1203 DeclAndIsDerivedMember.setInt(false);
1204 return true;
1205 }
1206 /// Perform a derived-to-base member pointer cast.
1207 bool castToBase(const CXXRecordDecl *Base) {
1208 if (!getDecl())
1209 return true;
1210 if (Path.empty())
1211 DeclAndIsDerivedMember.setInt(true);
1212 if (isDerivedMember()) {
1213 Path.push_back(Base);
1214 return true;
1215 }
1216 return castBack(Base);
1217 }
1218 };
Richard Smith357362d2011-12-13 06:39:58 +00001219
Richard Smith7bb00672012-02-01 01:42:44 +00001220 /// Compare two member pointers, which are assumed to be of the same type.
1221 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1222 if (!LHS.getDecl() || !RHS.getDecl())
1223 return !LHS.getDecl() && !RHS.getDecl();
1224 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1225 return false;
1226 return LHS.Path == RHS.Path;
1227 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001228}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001229
Richard Smith2e312c82012-03-03 22:46:17 +00001230static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001231static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1232 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001233 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001234static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1235static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001236static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1237 EvalInfo &Info);
1238static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001239static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001240static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001241 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001242static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001243static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001244static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001245static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001246
1247//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001248// Misc utilities
1249//===----------------------------------------------------------------------===//
1250
Richard Smith84401042013-06-03 05:03:02 +00001251/// Produce a string describing the given constexpr call.
1252static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1253 unsigned ArgIndex = 0;
1254 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1255 !isa<CXXConstructorDecl>(Frame->Callee) &&
1256 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1257
1258 if (!IsMemberCall)
1259 Out << *Frame->Callee << '(';
1260
1261 if (Frame->This && IsMemberCall) {
1262 APValue Val;
1263 Frame->This->moveInto(Val);
1264 Val.printPretty(Out, Frame->Info.Ctx,
1265 Frame->This->Designator.MostDerivedType);
1266 // FIXME: Add parens around Val if needed.
1267 Out << "->" << *Frame->Callee << '(';
1268 IsMemberCall = false;
1269 }
1270
1271 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1272 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1273 if (ArgIndex > (unsigned)IsMemberCall)
1274 Out << ", ";
1275
1276 const ParmVarDecl *Param = *I;
1277 const APValue &Arg = Frame->Arguments[ArgIndex];
1278 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1279
1280 if (ArgIndex == 0 && IsMemberCall)
1281 Out << "->" << *Frame->Callee << '(';
1282 }
1283
1284 Out << ')';
1285}
1286
Richard Smithd9f663b2013-04-22 15:31:51 +00001287/// Evaluate an expression to see if it had side-effects, and discard its
1288/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001289/// \return \c true if the caller should keep evaluating.
1290static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001291 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001292 if (!Evaluate(Scratch, Info, E))
1293 // We don't need the value, but we might have skipped a side effect here.
1294 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001295 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001296}
1297
Richard Smith861b5b52013-05-07 23:34:45 +00001298/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1299/// return its existing value.
1300static int64_t getExtValue(const APSInt &Value) {
1301 return Value.isSigned() ? Value.getSExtValue()
1302 : static_cast<int64_t>(Value.getZExtValue());
1303}
1304
Richard Smithd62306a2011-11-10 06:34:14 +00001305/// Should this call expression be treated as a string literal?
1306static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001307 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001308 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1309 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1310}
1311
Richard Smithce40ad62011-11-12 22:28:03 +00001312static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001313 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1314 // constant expression of pointer type that evaluates to...
1315
1316 // ... a null pointer value, or a prvalue core constant expression of type
1317 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001318 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001319
Richard Smithce40ad62011-11-12 22:28:03 +00001320 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1321 // ... the address of an object with static storage duration,
1322 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1323 return VD->hasGlobalStorage();
1324 // ... the address of a function,
1325 return isa<FunctionDecl>(D);
1326 }
1327
1328 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001329 switch (E->getStmtClass()) {
1330 default:
1331 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001332 case Expr::CompoundLiteralExprClass: {
1333 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1334 return CLE->isFileScope() && CLE->isLValue();
1335 }
Richard Smithe6c01442013-06-05 00:46:14 +00001336 case Expr::MaterializeTemporaryExprClass:
1337 // A materialized temporary might have been lifetime-extended to static
1338 // storage duration.
1339 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001340 // A string literal has static storage duration.
1341 case Expr::StringLiteralClass:
1342 case Expr::PredefinedExprClass:
1343 case Expr::ObjCStringLiteralClass:
1344 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001345 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001346 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001347 return true;
1348 case Expr::CallExprClass:
1349 return IsStringLiteralCall(cast<CallExpr>(E));
1350 // For GCC compatibility, &&label has static storage duration.
1351 case Expr::AddrLabelExprClass:
1352 return true;
1353 // A Block literal expression may be used as the initialization value for
1354 // Block variables at global or local static scope.
1355 case Expr::BlockExprClass:
1356 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001357 case Expr::ImplicitValueInitExprClass:
1358 // FIXME:
1359 // We can never form an lvalue with an implicit value initialization as its
1360 // base through expression evaluation, so these only appear in one case: the
1361 // implicit variable declaration we invent when checking whether a constexpr
1362 // constructor can produce a constant expression. We must assume that such
1363 // an expression might be a global lvalue.
1364 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001365 }
John McCall95007602010-05-10 23:27:23 +00001366}
1367
Richard Smithb228a862012-02-15 02:18:13 +00001368static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1369 assert(Base && "no location for a null lvalue");
1370 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1371 if (VD)
1372 Info.Note(VD->getLocation(), diag::note_declared_at);
1373 else
Ted Kremenek28831752012-08-23 20:46:57 +00001374 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001375 diag::note_constexpr_temporary_here);
1376}
1377
Richard Smith80815602011-11-07 05:07:52 +00001378/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001379/// value for an address or reference constant expression. Return true if we
1380/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001381static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1382 QualType Type, const LValue &LVal) {
1383 bool IsReferenceType = Type->isReferenceType();
1384
Richard Smith357362d2011-12-13 06:39:58 +00001385 APValue::LValueBase Base = LVal.getLValueBase();
1386 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1387
Richard Smith0dea49e2012-02-18 04:58:18 +00001388 // Check that the object is a global. Note that the fake 'this' object we
1389 // manufacture when checking potential constant expressions is conservatively
1390 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001391 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001392 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001393 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001394 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1395 << IsReferenceType << !Designator.Entries.empty()
1396 << !!VD << VD;
1397 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001398 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001399 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001400 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001401 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001402 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001403 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001404 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001405 LVal.getLValueCallIndex() == 0) &&
1406 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001407
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001408 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1409 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001410 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001411 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001412 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001413
Hans Wennborg82dd8772014-06-25 22:19:48 +00001414 // A dllimport variable never acts like a constant.
1415 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001416 return false;
1417 }
1418 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1419 // __declspec(dllimport) must be handled very carefully:
1420 // We must never initialize an expression with the thunk in C++.
1421 // Doing otherwise would allow the same id-expression to yield
1422 // different addresses for the same function in different translation
1423 // units. However, this means that we must dynamically initialize the
1424 // expression with the contents of the import address table at runtime.
1425 //
1426 // The C language has no notion of ODR; furthermore, it has no notion of
1427 // dynamic initialization. This means that we are permitted to
1428 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001429 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001430 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001431 }
1432 }
1433
Richard Smitha8105bc2012-01-06 16:39:00 +00001434 // Allow address constant expressions to be past-the-end pointers. This is
1435 // an extension: the standard requires them to point to an object.
1436 if (!IsReferenceType)
1437 return true;
1438
1439 // A reference constant expression must refer to an object.
1440 if (!Base) {
1441 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001442 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001443 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001444 }
1445
Richard Smith357362d2011-12-13 06:39:58 +00001446 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001447 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001448 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001449 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001450 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001451 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001452 }
1453
Richard Smith80815602011-11-07 05:07:52 +00001454 return true;
1455}
1456
Richard Smithfddd3842011-12-30 21:15:51 +00001457/// Check that this core constant expression is of literal type, and if not,
1458/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001459static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001460 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001461 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001462 return true;
1463
Richard Smith7525ff62013-05-09 07:14:00 +00001464 // C++1y: A constant initializer for an object o [...] may also invoke
1465 // constexpr constructors for o and its subobjects even if those objects
1466 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001467 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001468 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001469 return true;
1470
Richard Smithfddd3842011-12-30 21:15:51 +00001471 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001472 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001473 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001474 << E->getType();
1475 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001476 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001477 return false;
1478}
1479
Richard Smith0b0a0b62011-10-29 20:57:55 +00001480/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001481/// constant expression. If not, report an appropriate diagnostic. Does not
1482/// check that the expression is of literal type.
1483static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1484 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001485 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001486 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1487 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001488 return false;
1489 }
1490
Richard Smith77be48a2014-07-31 06:31:19 +00001491 // We allow _Atomic(T) to be initialized from anything that T can be
1492 // initialized from.
1493 if (const AtomicType *AT = Type->getAs<AtomicType>())
1494 Type = AT->getValueType();
1495
Richard Smithb228a862012-02-15 02:18:13 +00001496 // Core issue 1454: For a literal constant expression of array or class type,
1497 // each subobject of its value shall have been initialized by a constant
1498 // expression.
1499 if (Value.isArray()) {
1500 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1501 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1502 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1503 Value.getArrayInitializedElt(I)))
1504 return false;
1505 }
1506 if (!Value.hasArrayFiller())
1507 return true;
1508 return CheckConstantExpression(Info, DiagLoc, EltTy,
1509 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001510 }
Richard Smithb228a862012-02-15 02:18:13 +00001511 if (Value.isUnion() && Value.getUnionField()) {
1512 return CheckConstantExpression(Info, DiagLoc,
1513 Value.getUnionField()->getType(),
1514 Value.getUnionValue());
1515 }
1516 if (Value.isStruct()) {
1517 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1518 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1519 unsigned BaseIndex = 0;
1520 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1521 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1522 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1523 Value.getStructBase(BaseIndex)))
1524 return false;
1525 }
1526 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001527 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001528 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1529 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001530 return false;
1531 }
1532 }
1533
1534 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001535 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001536 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001537 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1538 }
1539
1540 // Everything else is fine.
1541 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001542}
1543
Benjamin Kramer8407df72015-03-09 16:47:52 +00001544static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001545 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001546}
1547
1548static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001549 if (Value.CallIndex)
1550 return false;
1551 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1552 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001553}
1554
Richard Smithcecf1842011-11-01 21:06:14 +00001555static bool IsWeakLValue(const LValue &Value) {
1556 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001557 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001558}
1559
David Majnemerb5116032014-12-09 23:32:34 +00001560static bool isZeroSized(const LValue &Value) {
1561 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001562 if (Decl && isa<VarDecl>(Decl)) {
1563 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001564 if (Ty->isArrayType())
1565 return Ty->isIncompleteType() ||
1566 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001567 }
1568 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001569}
1570
Richard Smith2e312c82012-03-03 22:46:17 +00001571static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001572 // A null base expression indicates a null pointer. These are always
1573 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001574 if (!Value.getLValueBase()) {
1575 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001576 return true;
1577 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001578
Richard Smith027bf112011-11-17 22:56:20 +00001579 // We have a non-null base. These are generally known to be true, but if it's
1580 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001581 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001582 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001583 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001584}
1585
Richard Smith2e312c82012-03-03 22:46:17 +00001586static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001587 switch (Val.getKind()) {
1588 case APValue::Uninitialized:
1589 return false;
1590 case APValue::Int:
1591 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001592 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001593 case APValue::Float:
1594 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001595 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001596 case APValue::ComplexInt:
1597 Result = Val.getComplexIntReal().getBoolValue() ||
1598 Val.getComplexIntImag().getBoolValue();
1599 return true;
1600 case APValue::ComplexFloat:
1601 Result = !Val.getComplexFloatReal().isZero() ||
1602 !Val.getComplexFloatImag().isZero();
1603 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001604 case APValue::LValue:
1605 return EvalPointerValueAsBool(Val, Result);
1606 case APValue::MemberPointer:
1607 Result = Val.getMemberPointerDecl();
1608 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001609 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001610 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001611 case APValue::Struct:
1612 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001613 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001614 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001615 }
1616
Richard Smith11562c52011-10-28 17:51:58 +00001617 llvm_unreachable("unknown APValue kind");
1618}
1619
1620static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1621 EvalInfo &Info) {
1622 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001623 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001624 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001625 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001626 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001627}
1628
Richard Smith357362d2011-12-13 06:39:58 +00001629template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001630static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001631 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001632 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001633 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001634 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001635}
1636
1637static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1638 QualType SrcType, const APFloat &Value,
1639 QualType DestType, APSInt &Result) {
1640 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001641 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001642 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001643
Richard Smith357362d2011-12-13 06:39:58 +00001644 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001645 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001646 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1647 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001648 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001649 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001650}
1651
Richard Smith357362d2011-12-13 06:39:58 +00001652static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1653 QualType SrcType, QualType DestType,
1654 APFloat &Result) {
1655 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001656 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001657 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1658 APFloat::rmNearestTiesToEven, &ignored)
1659 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001660 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001661 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001662}
1663
Richard Smith911e1422012-01-30 22:27:01 +00001664static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1665 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001666 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001667 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001668 APSInt Result = Value;
1669 // Figure out if this is a truncate, extend or noop cast.
1670 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001671 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001672 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001673 return Result;
1674}
1675
Richard Smith357362d2011-12-13 06:39:58 +00001676static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1677 QualType SrcType, const APSInt &Value,
1678 QualType DestType, APFloat &Result) {
1679 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1680 if (Result.convertFromAPInt(Value, Value.isSigned(),
1681 APFloat::rmNearestTiesToEven)
1682 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001683 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001684 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001685}
1686
Richard Smith49ca8aa2013-08-06 07:09:20 +00001687static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1688 APValue &Value, const FieldDecl *FD) {
1689 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1690
1691 if (!Value.isInt()) {
1692 // Trying to store a pointer-cast-to-integer into a bitfield.
1693 // FIXME: In this case, we should provide the diagnostic for casting
1694 // a pointer to an integer.
1695 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1696 Info.Diag(E);
1697 return false;
1698 }
1699
1700 APSInt &Int = Value.getInt();
1701 unsigned OldBitWidth = Int.getBitWidth();
1702 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1703 if (NewBitWidth < OldBitWidth)
1704 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1705 return true;
1706}
1707
Eli Friedman803acb32011-12-22 03:51:45 +00001708static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1709 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001710 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001711 if (!Evaluate(SVal, Info, E))
1712 return false;
1713 if (SVal.isInt()) {
1714 Res = SVal.getInt();
1715 return true;
1716 }
1717 if (SVal.isFloat()) {
1718 Res = SVal.getFloat().bitcastToAPInt();
1719 return true;
1720 }
1721 if (SVal.isVector()) {
1722 QualType VecTy = E->getType();
1723 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1724 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1725 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1726 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1727 Res = llvm::APInt::getNullValue(VecSize);
1728 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1729 APValue &Elt = SVal.getVectorElt(i);
1730 llvm::APInt EltAsInt;
1731 if (Elt.isInt()) {
1732 EltAsInt = Elt.getInt();
1733 } else if (Elt.isFloat()) {
1734 EltAsInt = Elt.getFloat().bitcastToAPInt();
1735 } else {
1736 // Don't try to handle vectors of anything other than int or float
1737 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001738 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001739 return false;
1740 }
1741 unsigned BaseEltSize = EltAsInt.getBitWidth();
1742 if (BigEndian)
1743 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1744 else
1745 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1746 }
1747 return true;
1748 }
1749 // Give up if the input isn't an int, float, or vector. For example, we
1750 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001751 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001752 return false;
1753}
1754
Richard Smith43e77732013-05-07 04:50:00 +00001755/// Perform the given integer operation, which is known to need at most BitWidth
1756/// bits, and check for overflow in the original type (if that type was not an
1757/// unsigned type).
1758template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001759static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1760 const APSInt &LHS, const APSInt &RHS,
1761 unsigned BitWidth, Operation Op,
1762 APSInt &Result) {
1763 if (LHS.isUnsigned()) {
1764 Result = Op(LHS, RHS);
1765 return true;
1766 }
Richard Smith43e77732013-05-07 04:50:00 +00001767
1768 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001769 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001770 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001771 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001772 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001773 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001774 << Result.toString(10) << E->getType();
1775 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001776 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001777 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001778 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001779}
1780
1781/// Perform the given binary integer operation.
1782static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1783 BinaryOperatorKind Opcode, APSInt RHS,
1784 APSInt &Result) {
1785 switch (Opcode) {
1786 default:
1787 Info.Diag(E);
1788 return false;
1789 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001790 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1791 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001792 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001793 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1794 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001795 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001796 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1797 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001798 case BO_And: Result = LHS & RHS; return true;
1799 case BO_Xor: Result = LHS ^ RHS; return true;
1800 case BO_Or: Result = LHS | RHS; return true;
1801 case BO_Div:
1802 case BO_Rem:
1803 if (RHS == 0) {
1804 Info.Diag(E, diag::note_expr_divide_by_zero);
1805 return false;
1806 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001807 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1808 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1809 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001810 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1811 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001812 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1813 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001814 return true;
1815 case BO_Shl: {
1816 if (Info.getLangOpts().OpenCL)
1817 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1818 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1819 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1820 RHS.isUnsigned());
1821 else if (RHS.isSigned() && RHS.isNegative()) {
1822 // During constant-folding, a negative shift is an opposite shift. Such
1823 // a shift is not a constant expression.
1824 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1825 RHS = -RHS;
1826 goto shift_right;
1827 }
1828 shift_left:
1829 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1830 // the shifted type.
1831 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1832 if (SA != RHS) {
1833 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1834 << RHS << E->getType() << LHS.getBitWidth();
1835 } else if (LHS.isSigned()) {
1836 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1837 // operand, and must not overflow the corresponding unsigned type.
1838 if (LHS.isNegative())
1839 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1840 else if (LHS.countLeadingZeros() < SA)
1841 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1842 }
1843 Result = LHS << SA;
1844 return true;
1845 }
1846 case BO_Shr: {
1847 if (Info.getLangOpts().OpenCL)
1848 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1849 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1850 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1851 RHS.isUnsigned());
1852 else if (RHS.isSigned() && RHS.isNegative()) {
1853 // During constant-folding, a negative shift is an opposite shift. Such a
1854 // shift is not a constant expression.
1855 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1856 RHS = -RHS;
1857 goto shift_left;
1858 }
1859 shift_right:
1860 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1861 // shifted type.
1862 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1863 if (SA != RHS)
1864 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1865 << RHS << E->getType() << LHS.getBitWidth();
1866 Result = LHS >> SA;
1867 return true;
1868 }
1869
1870 case BO_LT: Result = LHS < RHS; return true;
1871 case BO_GT: Result = LHS > RHS; return true;
1872 case BO_LE: Result = LHS <= RHS; return true;
1873 case BO_GE: Result = LHS >= RHS; return true;
1874 case BO_EQ: Result = LHS == RHS; return true;
1875 case BO_NE: Result = LHS != RHS; return true;
1876 }
1877}
1878
Richard Smith861b5b52013-05-07 23:34:45 +00001879/// Perform the given binary floating-point operation, in-place, on LHS.
1880static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1881 APFloat &LHS, BinaryOperatorKind Opcode,
1882 const APFloat &RHS) {
1883 switch (Opcode) {
1884 default:
1885 Info.Diag(E);
1886 return false;
1887 case BO_Mul:
1888 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1889 break;
1890 case BO_Add:
1891 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1892 break;
1893 case BO_Sub:
1894 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1895 break;
1896 case BO_Div:
1897 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1898 break;
1899 }
1900
Richard Smith0c6124b2015-12-03 01:36:22 +00001901 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001902 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001903 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001904 }
Richard Smith861b5b52013-05-07 23:34:45 +00001905 return true;
1906}
1907
Richard Smitha8105bc2012-01-06 16:39:00 +00001908/// Cast an lvalue referring to a base subobject to a derived class, by
1909/// truncating the lvalue's path to the given length.
1910static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1911 const RecordDecl *TruncatedType,
1912 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001913 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001914
1915 // Check we actually point to a derived class object.
1916 if (TruncatedElements == D.Entries.size())
1917 return true;
1918 assert(TruncatedElements >= D.MostDerivedPathLength &&
1919 "not casting to a derived class");
1920 if (!Result.checkSubobject(Info, E, CSK_Derived))
1921 return false;
1922
1923 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001924 const RecordDecl *RD = TruncatedType;
1925 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001926 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001927 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1928 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001929 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001930 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001931 else
Richard Smithd62306a2011-11-10 06:34:14 +00001932 Result.Offset -= Layout.getBaseClassOffset(Base);
1933 RD = Base;
1934 }
Richard Smith027bf112011-11-17 22:56:20 +00001935 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001936 return true;
1937}
1938
John McCalld7bca762012-05-01 00:38:49 +00001939static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001940 const CXXRecordDecl *Derived,
1941 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001942 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001943 if (!RL) {
1944 if (Derived->isInvalidDecl()) return false;
1945 RL = &Info.Ctx.getASTRecordLayout(Derived);
1946 }
1947
Richard Smithd62306a2011-11-10 06:34:14 +00001948 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001949 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001950 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001951}
1952
Richard Smitha8105bc2012-01-06 16:39:00 +00001953static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001954 const CXXRecordDecl *DerivedDecl,
1955 const CXXBaseSpecifier *Base) {
1956 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1957
John McCalld7bca762012-05-01 00:38:49 +00001958 if (!Base->isVirtual())
1959 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001960
Richard Smitha8105bc2012-01-06 16:39:00 +00001961 SubobjectDesignator &D = Obj.Designator;
1962 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001963 return false;
1964
Richard Smitha8105bc2012-01-06 16:39:00 +00001965 // Extract most-derived object and corresponding type.
1966 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1967 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1968 return false;
1969
1970 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001971 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001972 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1973 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001974 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001975 return true;
1976}
1977
Richard Smith84401042013-06-03 05:03:02 +00001978static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1979 QualType Type, LValue &Result) {
1980 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1981 PathE = E->path_end();
1982 PathI != PathE; ++PathI) {
1983 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1984 *PathI))
1985 return false;
1986 Type = (*PathI)->getType();
1987 }
1988 return true;
1989}
1990
Richard Smithd62306a2011-11-10 06:34:14 +00001991/// Update LVal to refer to the given field, which must be a member of the type
1992/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001993static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001994 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001995 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001996 if (!RL) {
1997 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001998 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001999 }
Richard Smithd62306a2011-11-10 06:34:14 +00002000
2001 unsigned I = FD->getFieldIndex();
2002 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00002003 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002004 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002005}
2006
Richard Smith1b78b3d2012-01-25 22:15:11 +00002007/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002008static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002009 LValue &LVal,
2010 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002011 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002012 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002013 return false;
2014 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002015}
2016
Richard Smithd62306a2011-11-10 06:34:14 +00002017/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002018static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2019 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002020 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2021 // extension.
2022 if (Type->isVoidType() || Type->isFunctionType()) {
2023 Size = CharUnits::One();
2024 return true;
2025 }
2026
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002027 if (Type->isDependentType()) {
2028 Info.Diag(Loc);
2029 return false;
2030 }
2031
Richard Smithd62306a2011-11-10 06:34:14 +00002032 if (!Type->isConstantSizeType()) {
2033 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002034 // FIXME: Better diagnostic.
2035 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002036 return false;
2037 }
2038
2039 Size = Info.Ctx.getTypeSizeInChars(Type);
2040 return true;
2041}
2042
2043/// Update a pointer value to model pointer arithmetic.
2044/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002045/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002046/// \param LVal - The pointer value to be updated.
2047/// \param EltTy - The pointee type represented by LVal.
2048/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002049static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2050 LValue &LVal, QualType EltTy,
2051 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002052 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002053 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002054 return false;
2055
2056 // Compute the new offset in the appropriate width.
2057 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00002058 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00002059 return true;
2060}
2061
Richard Smith66c96992012-02-18 22:04:06 +00002062/// Update an lvalue to refer to a component of a complex number.
2063/// \param Info - Information about the ongoing evaluation.
2064/// \param LVal - The lvalue to be updated.
2065/// \param EltTy - The complex number's component type.
2066/// \param Imag - False for the real component, true for the imaginary.
2067static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2068 LValue &LVal, QualType EltTy,
2069 bool Imag) {
2070 if (Imag) {
2071 CharUnits SizeOfComponent;
2072 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2073 return false;
2074 LVal.Offset += SizeOfComponent;
2075 }
2076 LVal.addComplex(Info, E, EltTy, Imag);
2077 return true;
2078}
2079
Richard Smith27908702011-10-24 17:54:18 +00002080/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002081///
2082/// \param Info Information about the ongoing evaluation.
2083/// \param E An expression to be used when printing diagnostics.
2084/// \param VD The variable whose initializer should be obtained.
2085/// \param Frame The frame in which the variable was created. Must be null
2086/// if this variable is not local to the evaluation.
2087/// \param Result Filled in with a pointer to the value of the variable.
2088static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2089 const VarDecl *VD, CallStackFrame *Frame,
2090 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002091 // If this is a parameter to an active constexpr function call, perform
2092 // argument substitution.
2093 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002094 // Assume arguments of a potential constant expression are unknown
2095 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002096 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002097 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002098 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002099 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002100 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002101 }
Richard Smith3229b742013-05-05 21:17:10 +00002102 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002103 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002104 }
Richard Smith27908702011-10-24 17:54:18 +00002105
Richard Smithd9f663b2013-04-22 15:31:51 +00002106 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002107 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002108 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002109 if (!Result) {
2110 // Assume variables referenced within a lambda's call operator that were
2111 // not declared within the call operator are captures and during checking
2112 // of a potential constant expression, assume they are unknown constant
2113 // expressions.
2114 assert(isLambdaCallOperator(Frame->Callee) &&
2115 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2116 "missing value for local variable");
2117 if (Info.checkingPotentialConstantExpression())
2118 return false;
2119 // FIXME: implement capture evaluation during constant expr evaluation.
2120 Info.Diag(E->getLocStart(),
2121 diag::note_unimplemented_constexpr_lambda_feature_ast)
2122 << "captures not currently allowed";
2123 return false;
2124 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002125 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002126 }
2127
Richard Smithd0b4dd62011-12-19 06:19:21 +00002128 // Dig out the initializer, and use the declaration which it's attached to.
2129 const Expr *Init = VD->getAnyInitializer(VD);
2130 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002131 // If we're checking a potential constant expression, the variable could be
2132 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002133 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002134 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002135 return false;
2136 }
2137
Richard Smithd62306a2011-11-10 06:34:14 +00002138 // If we're currently evaluating the initializer of this declaration, use that
2139 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002140 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002141 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002142 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002143 }
2144
Richard Smithcecf1842011-11-01 21:06:14 +00002145 // Never evaluate the initializer of a weak variable. We can't be sure that
2146 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002147 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002148 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002149 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002150 }
Richard Smithcecf1842011-11-01 21:06:14 +00002151
Richard Smithd0b4dd62011-12-19 06:19:21 +00002152 // Check that we can fold the initializer. In C++, we will have already done
2153 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002154 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002155 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002156 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002157 Notes.size() + 1) << VD;
2158 Info.Note(VD->getLocation(), diag::note_declared_at);
2159 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002160 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002161 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002162 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002163 Notes.size() + 1) << VD;
2164 Info.Note(VD->getLocation(), diag::note_declared_at);
2165 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002166 }
Richard Smith27908702011-10-24 17:54:18 +00002167
Richard Smith3229b742013-05-05 21:17:10 +00002168 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002169 return true;
Richard Smith27908702011-10-24 17:54:18 +00002170}
2171
Richard Smith11562c52011-10-28 17:51:58 +00002172static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002173 Qualifiers Quals = T.getQualifiers();
2174 return Quals.hasConst() && !Quals.hasVolatile();
2175}
2176
Richard Smithe97cbd72011-11-11 04:05:33 +00002177/// Get the base index of the given base class within an APValue representing
2178/// the given derived class.
2179static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2180 const CXXRecordDecl *Base) {
2181 Base = Base->getCanonicalDecl();
2182 unsigned Index = 0;
2183 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2184 E = Derived->bases_end(); I != E; ++I, ++Index) {
2185 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2186 return Index;
2187 }
2188
2189 llvm_unreachable("base class missing from derived class's bases list");
2190}
2191
Richard Smith3da88fa2013-04-26 14:36:30 +00002192/// Extract the value of a character from a string literal.
2193static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2194 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002195 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2196 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2197 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002198 const StringLiteral *S = cast<StringLiteral>(Lit);
2199 const ConstantArrayType *CAT =
2200 Info.Ctx.getAsConstantArrayType(S->getType());
2201 assert(CAT && "string literal isn't an array");
2202 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002203 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002204
2205 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002206 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002207 if (Index < S->getLength())
2208 Value = S->getCodeUnit(Index);
2209 return Value;
2210}
2211
Richard Smith3da88fa2013-04-26 14:36:30 +00002212// Expand a string literal into an array of characters.
2213static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2214 APValue &Result) {
2215 const StringLiteral *S = cast<StringLiteral>(Lit);
2216 const ConstantArrayType *CAT =
2217 Info.Ctx.getAsConstantArrayType(S->getType());
2218 assert(CAT && "string literal isn't an array");
2219 QualType CharType = CAT->getElementType();
2220 assert(CharType->isIntegerType() && "unexpected character type");
2221
2222 unsigned Elts = CAT->getSize().getZExtValue();
2223 Result = APValue(APValue::UninitArray(),
2224 std::min(S->getLength(), Elts), Elts);
2225 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2226 CharType->isUnsignedIntegerType());
2227 if (Result.hasArrayFiller())
2228 Result.getArrayFiller() = APValue(Value);
2229 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2230 Value = S->getCodeUnit(I);
2231 Result.getArrayInitializedElt(I) = APValue(Value);
2232 }
2233}
2234
2235// Expand an array so that it has more than Index filled elements.
2236static void expandArray(APValue &Array, unsigned Index) {
2237 unsigned Size = Array.getArraySize();
2238 assert(Index < Size);
2239
2240 // Always at least double the number of elements for which we store a value.
2241 unsigned OldElts = Array.getArrayInitializedElts();
2242 unsigned NewElts = std::max(Index+1, OldElts * 2);
2243 NewElts = std::min(Size, std::max(NewElts, 8u));
2244
2245 // Copy the data across.
2246 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2247 for (unsigned I = 0; I != OldElts; ++I)
2248 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2249 for (unsigned I = OldElts; I != NewElts; ++I)
2250 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2251 if (NewValue.hasArrayFiller())
2252 NewValue.getArrayFiller() = Array.getArrayFiller();
2253 Array.swap(NewValue);
2254}
2255
Richard Smithb01fe402014-09-16 01:24:02 +00002256/// Determine whether a type would actually be read by an lvalue-to-rvalue
2257/// conversion. If it's of class type, we may assume that the copy operation
2258/// is trivial. Note that this is never true for a union type with fields
2259/// (because the copy always "reads" the active member) and always true for
2260/// a non-class type.
2261static bool isReadByLvalueToRvalueConversion(QualType T) {
2262 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2263 if (!RD || (RD->isUnion() && !RD->field_empty()))
2264 return true;
2265 if (RD->isEmpty())
2266 return false;
2267
2268 for (auto *Field : RD->fields())
2269 if (isReadByLvalueToRvalueConversion(Field->getType()))
2270 return true;
2271
2272 for (auto &BaseSpec : RD->bases())
2273 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2274 return true;
2275
2276 return false;
2277}
2278
2279/// Diagnose an attempt to read from any unreadable field within the specified
2280/// type, which might be a class type.
2281static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2282 QualType T) {
2283 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2284 if (!RD)
2285 return false;
2286
2287 if (!RD->hasMutableFields())
2288 return false;
2289
2290 for (auto *Field : RD->fields()) {
2291 // If we're actually going to read this field in some way, then it can't
2292 // be mutable. If we're in a union, then assigning to a mutable field
2293 // (even an empty one) can change the active member, so that's not OK.
2294 // FIXME: Add core issue number for the union case.
2295 if (Field->isMutable() &&
2296 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2297 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2298 Info.Note(Field->getLocation(), diag::note_declared_at);
2299 return true;
2300 }
2301
2302 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2303 return true;
2304 }
2305
2306 for (auto &BaseSpec : RD->bases())
2307 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2308 return true;
2309
2310 // All mutable fields were empty, and thus not actually read.
2311 return false;
2312}
2313
Richard Smith861b5b52013-05-07 23:34:45 +00002314/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002315enum AccessKinds {
2316 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002317 AK_Assign,
2318 AK_Increment,
2319 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002320};
2321
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002322namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002323/// A handle to a complete object (an object that is not a subobject of
2324/// another object).
2325struct CompleteObject {
2326 /// The value of the complete object.
2327 APValue *Value;
2328 /// The type of the complete object.
2329 QualType Type;
2330
Craig Topper36250ad2014-05-12 05:36:57 +00002331 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002332 CompleteObject(APValue *Value, QualType Type)
2333 : Value(Value), Type(Type) {
2334 assert(Value && "missing value for complete object");
2335 }
2336
Aaron Ballman67347662015-02-15 22:00:28 +00002337 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002338};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002339} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002340
Richard Smith3da88fa2013-04-26 14:36:30 +00002341/// Find the designated sub-object of an rvalue.
2342template<typename SubobjectHandler>
2343typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002344findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002345 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002346 if (Sub.Invalid)
2347 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002348 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002349 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002350 if (Info.getLangOpts().CPlusPlus11)
2351 Info.Diag(E, diag::note_constexpr_access_past_end)
2352 << handler.AccessKind;
2353 else
2354 Info.Diag(E);
2355 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002356 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002357
Richard Smith3229b742013-05-05 21:17:10 +00002358 APValue *O = Obj.Value;
2359 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002360 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002361
Richard Smithd62306a2011-11-10 06:34:14 +00002362 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002363 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2364 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002365 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002366 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2367 return handler.failed();
2368 }
2369
Richard Smith49ca8aa2013-08-06 07:09:20 +00002370 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002371 // If we are reading an object of class type, there may still be more
2372 // things we need to check: if there are any mutable subobjects, we
2373 // cannot perform this read. (This only happens when performing a trivial
2374 // copy or assignment.)
2375 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2376 diagnoseUnreadableFields(Info, E, ObjType))
2377 return handler.failed();
2378
Richard Smith49ca8aa2013-08-06 07:09:20 +00002379 if (!handler.found(*O, ObjType))
2380 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002381
Richard Smith49ca8aa2013-08-06 07:09:20 +00002382 // If we modified a bit-field, truncate it to the right width.
2383 if (handler.AccessKind != AK_Read &&
2384 LastField && LastField->isBitField() &&
2385 !truncateBitfieldValue(Info, E, *O, LastField))
2386 return false;
2387
2388 return true;
2389 }
2390
Craig Topper36250ad2014-05-12 05:36:57 +00002391 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002392 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002393 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002394 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002395 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002396 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002397 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002398 // Note, it should not be possible to form a pointer with a valid
2399 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002400 if (Info.getLangOpts().CPlusPlus11)
2401 Info.Diag(E, diag::note_constexpr_access_past_end)
2402 << handler.AccessKind;
2403 else
2404 Info.Diag(E);
2405 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002406 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002407
2408 ObjType = CAT->getElementType();
2409
Richard Smith14a94132012-02-17 03:35:37 +00002410 // An array object is represented as either an Array APValue or as an
2411 // LValue which refers to a string literal.
2412 if (O->isLValue()) {
2413 assert(I == N - 1 && "extracting subobject of character?");
2414 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002415 if (handler.AccessKind != AK_Read)
2416 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2417 *O);
2418 else
2419 return handler.foundString(*O, ObjType, Index);
2420 }
2421
2422 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002423 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002424 else if (handler.AccessKind != AK_Read) {
2425 expandArray(*O, Index);
2426 O = &O->getArrayInitializedElt(Index);
2427 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002428 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002429 } else if (ObjType->isAnyComplexType()) {
2430 // Next subobject is a complex number.
2431 uint64_t Index = Sub.Entries[I].ArrayIndex;
2432 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002433 if (Info.getLangOpts().CPlusPlus11)
2434 Info.Diag(E, diag::note_constexpr_access_past_end)
2435 << handler.AccessKind;
2436 else
2437 Info.Diag(E);
2438 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002439 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002440
2441 bool WasConstQualified = ObjType.isConstQualified();
2442 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2443 if (WasConstQualified)
2444 ObjType.addConst();
2445
Richard Smith66c96992012-02-18 22:04:06 +00002446 assert(I == N - 1 && "extracting subobject of scalar?");
2447 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002448 return handler.found(Index ? O->getComplexIntImag()
2449 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002450 } else {
2451 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002452 return handler.found(Index ? O->getComplexFloatImag()
2453 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002454 }
Richard Smithd62306a2011-11-10 06:34:14 +00002455 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002456 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002457 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002458 << Field;
2459 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002460 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002461 }
2462
Richard Smithd62306a2011-11-10 06:34:14 +00002463 // Next subobject is a class, struct or union field.
2464 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2465 if (RD->isUnion()) {
2466 const FieldDecl *UnionField = O->getUnionField();
2467 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002468 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002469 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2470 << handler.AccessKind << Field << !UnionField << UnionField;
2471 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002472 }
Richard Smithd62306a2011-11-10 06:34:14 +00002473 O = &O->getUnionValue();
2474 } else
2475 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002476
2477 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002478 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002479 if (WasConstQualified && !Field->isMutable())
2480 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002481
2482 if (ObjType.isVolatileQualified()) {
2483 if (Info.getLangOpts().CPlusPlus) {
2484 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002485 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2486 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002487 Info.Note(Field->getLocation(), diag::note_declared_at);
2488 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002489 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002490 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002491 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002492 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002493
2494 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002495 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002496 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002497 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2498 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2499 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002500
2501 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002502 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002503 if (WasConstQualified)
2504 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002505 }
2506 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002507}
2508
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002509namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002510struct ExtractSubobjectHandler {
2511 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002512 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002513
2514 static const AccessKinds AccessKind = AK_Read;
2515
2516 typedef bool result_type;
2517 bool failed() { return false; }
2518 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002519 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002520 return true;
2521 }
2522 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002523 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002524 return true;
2525 }
2526 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002527 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002528 return true;
2529 }
2530 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002531 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002532 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2533 return true;
2534 }
2535};
Richard Smith3229b742013-05-05 21:17:10 +00002536} // end anonymous namespace
2537
Richard Smith3da88fa2013-04-26 14:36:30 +00002538const AccessKinds ExtractSubobjectHandler::AccessKind;
2539
2540/// Extract the designated sub-object of an rvalue.
2541static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002542 const CompleteObject &Obj,
2543 const SubobjectDesignator &Sub,
2544 APValue &Result) {
2545 ExtractSubobjectHandler Handler = { Info, Result };
2546 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002547}
2548
Richard Smith3229b742013-05-05 21:17:10 +00002549namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002550struct ModifySubobjectHandler {
2551 EvalInfo &Info;
2552 APValue &NewVal;
2553 const Expr *E;
2554
2555 typedef bool result_type;
2556 static const AccessKinds AccessKind = AK_Assign;
2557
2558 bool checkConst(QualType QT) {
2559 // Assigning to a const object has undefined behavior.
2560 if (QT.isConstQualified()) {
2561 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2562 return false;
2563 }
2564 return true;
2565 }
2566
2567 bool failed() { return false; }
2568 bool found(APValue &Subobj, QualType SubobjType) {
2569 if (!checkConst(SubobjType))
2570 return false;
2571 // We've been given ownership of NewVal, so just swap it in.
2572 Subobj.swap(NewVal);
2573 return true;
2574 }
2575 bool found(APSInt &Value, QualType SubobjType) {
2576 if (!checkConst(SubobjType))
2577 return false;
2578 if (!NewVal.isInt()) {
2579 // Maybe trying to write a cast pointer value into a complex?
2580 Info.Diag(E);
2581 return false;
2582 }
2583 Value = NewVal.getInt();
2584 return true;
2585 }
2586 bool found(APFloat &Value, QualType SubobjType) {
2587 if (!checkConst(SubobjType))
2588 return false;
2589 Value = NewVal.getFloat();
2590 return true;
2591 }
2592 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2593 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2594 }
2595};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002596} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002597
Richard Smith3229b742013-05-05 21:17:10 +00002598const AccessKinds ModifySubobjectHandler::AccessKind;
2599
Richard Smith3da88fa2013-04-26 14:36:30 +00002600/// Update the designated sub-object of an rvalue to the given value.
2601static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002602 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002603 const SubobjectDesignator &Sub,
2604 APValue &NewVal) {
2605 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002606 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002607}
2608
Richard Smith84f6dcf2012-02-02 01:16:57 +00002609/// Find the position where two subobject designators diverge, or equivalently
2610/// the length of the common initial subsequence.
2611static unsigned FindDesignatorMismatch(QualType ObjType,
2612 const SubobjectDesignator &A,
2613 const SubobjectDesignator &B,
2614 bool &WasArrayIndex) {
2615 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2616 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002617 if (!ObjType.isNull() &&
2618 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002619 // Next subobject is an array element.
2620 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2621 WasArrayIndex = true;
2622 return I;
2623 }
Richard Smith66c96992012-02-18 22:04:06 +00002624 if (ObjType->isAnyComplexType())
2625 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2626 else
2627 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002628 } else {
2629 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2630 WasArrayIndex = false;
2631 return I;
2632 }
2633 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2634 // Next subobject is a field.
2635 ObjType = FD->getType();
2636 else
2637 // Next subobject is a base class.
2638 ObjType = QualType();
2639 }
2640 }
2641 WasArrayIndex = false;
2642 return I;
2643}
2644
2645/// Determine whether the given subobject designators refer to elements of the
2646/// same array object.
2647static bool AreElementsOfSameArray(QualType ObjType,
2648 const SubobjectDesignator &A,
2649 const SubobjectDesignator &B) {
2650 if (A.Entries.size() != B.Entries.size())
2651 return false;
2652
George Burgess IVa51c4072015-10-16 01:49:01 +00002653 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002654 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2655 // A is a subobject of the array element.
2656 return false;
2657
2658 // If A (and B) designates an array element, the last entry will be the array
2659 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2660 // of length 1' case, and the entire path must match.
2661 bool WasArrayIndex;
2662 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2663 return CommonLength >= A.Entries.size() - IsArray;
2664}
2665
Richard Smith3229b742013-05-05 21:17:10 +00002666/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002667static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2668 AccessKinds AK, const LValue &LVal,
2669 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002670 if (!LVal.Base) {
2671 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2672 return CompleteObject();
2673 }
2674
Craig Topper36250ad2014-05-12 05:36:57 +00002675 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002676 if (LVal.CallIndex) {
2677 Frame = Info.getCallFrame(LVal.CallIndex);
2678 if (!Frame) {
2679 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2680 << AK << LVal.Base.is<const ValueDecl*>();
2681 NoteLValueLocation(Info, LVal.Base);
2682 return CompleteObject();
2683 }
Richard Smith3229b742013-05-05 21:17:10 +00002684 }
2685
2686 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2687 // is not a constant expression (even if the object is non-volatile). We also
2688 // apply this rule to C++98, in order to conform to the expected 'volatile'
2689 // semantics.
2690 if (LValType.isVolatileQualified()) {
2691 if (Info.getLangOpts().CPlusPlus)
2692 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2693 << AK << LValType;
2694 else
2695 Info.Diag(E);
2696 return CompleteObject();
2697 }
2698
2699 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002700 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002701 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002702
2703 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2704 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2705 // In C++11, constexpr, non-volatile variables initialized with constant
2706 // expressions are constant expressions too. Inside constexpr functions,
2707 // parameters are constant expressions even if they're non-const.
2708 // In C++1y, objects local to a constant expression (those with a Frame) are
2709 // both readable and writable inside constant expressions.
2710 // In C, such things can also be folded, although they are not ICEs.
2711 const VarDecl *VD = dyn_cast<VarDecl>(D);
2712 if (VD) {
2713 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2714 VD = VDef;
2715 }
2716 if (!VD || VD->isInvalidDecl()) {
2717 Info.Diag(E);
2718 return CompleteObject();
2719 }
2720
2721 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002722 if (BaseType.isVolatileQualified()) {
2723 if (Info.getLangOpts().CPlusPlus) {
2724 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2725 << AK << 1 << VD;
2726 Info.Note(VD->getLocation(), diag::note_declared_at);
2727 } else {
2728 Info.Diag(E);
2729 }
2730 return CompleteObject();
2731 }
2732
2733 // Unless we're looking at a local variable or argument in a constexpr call,
2734 // the variable we're reading must be const.
2735 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002736 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002737 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2738 // OK, we can read and modify an object if we're in the process of
2739 // evaluating its initializer, because its lifetime began in this
2740 // evaluation.
2741 } else if (AK != AK_Read) {
2742 // All the remaining cases only permit reading.
2743 Info.Diag(E, diag::note_constexpr_modify_global);
2744 return CompleteObject();
2745 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002746 // OK, we can read this variable.
2747 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pana2195522016-06-07 03:41:07 +00002748 if (!BaseType.isConstQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002749 if (Info.getLangOpts().CPlusPlus) {
2750 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2751 Info.Note(VD->getLocation(), diag::note_declared_at);
2752 } else {
2753 Info.Diag(E);
2754 }
2755 return CompleteObject();
2756 }
2757 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2758 // We support folding of const floating-point types, in order to make
2759 // static const data members of such types (supported as an extension)
2760 // more useful.
2761 if (Info.getLangOpts().CPlusPlus11) {
2762 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2763 Info.Note(VD->getLocation(), diag::note_declared_at);
2764 } else {
2765 Info.CCEDiag(E);
2766 }
2767 } else {
2768 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002769 if (Info.checkingPotentialConstantExpression() &&
2770 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2771 // The definition of this variable could be constexpr. We can't
2772 // access it right now, but may be able to in future.
2773 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith3229b742013-05-05 21:17:10 +00002774 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2775 Info.Note(VD->getLocation(), diag::note_declared_at);
2776 } else {
2777 Info.Diag(E);
2778 }
2779 return CompleteObject();
2780 }
2781 }
2782
2783 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2784 return CompleteObject();
2785 } else {
2786 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2787
2788 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002789 if (const MaterializeTemporaryExpr *MTE =
2790 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2791 assert(MTE->getStorageDuration() == SD_Static &&
2792 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002793
Richard Smithe6c01442013-06-05 00:46:14 +00002794 // Per C++1y [expr.const]p2:
2795 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2796 // - a [...] glvalue of integral or enumeration type that refers to
2797 // a non-volatile const object [...]
2798 // [...]
2799 // - a [...] glvalue of literal type that refers to a non-volatile
2800 // object whose lifetime began within the evaluation of e.
2801 //
2802 // C++11 misses the 'began within the evaluation of e' check and
2803 // instead allows all temporaries, including things like:
2804 // int &&r = 1;
2805 // int x = ++r;
2806 // constexpr int k = r;
2807 // Therefore we use the C++1y rules in C++11 too.
2808 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2809 const ValueDecl *ED = MTE->getExtendingDecl();
2810 if (!(BaseType.isConstQualified() &&
2811 BaseType->isIntegralOrEnumerationType()) &&
2812 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2813 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2814 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2815 return CompleteObject();
2816 }
2817
2818 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2819 assert(BaseVal && "got reference to unevaluated temporary");
2820 } else {
2821 Info.Diag(E);
2822 return CompleteObject();
2823 }
2824 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002825 BaseVal = Frame->getTemporary(Base);
2826 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002827 }
Richard Smith3229b742013-05-05 21:17:10 +00002828
2829 // Volatile temporary objects cannot be accessed in constant expressions.
2830 if (BaseType.isVolatileQualified()) {
2831 if (Info.getLangOpts().CPlusPlus) {
2832 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2833 << AK << 0;
2834 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2835 } else {
2836 Info.Diag(E);
2837 }
2838 return CompleteObject();
2839 }
2840 }
2841
Richard Smith7525ff62013-05-09 07:14:00 +00002842 // During the construction of an object, it is not yet 'const'.
2843 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2844 // and this doesn't do quite the right thing for const subobjects of the
2845 // object under construction.
2846 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2847 BaseType = Info.Ctx.getCanonicalType(BaseType);
2848 BaseType.removeLocalConst();
2849 }
2850
Richard Smith6d4c6582013-11-05 22:18:15 +00002851 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002852 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002853 //
2854 // FIXME: Not all local state is mutable. Allow local constant subobjects
2855 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002856 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2857 Info.EvalStatus.HasSideEffects) ||
2858 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002859 return CompleteObject();
2860
2861 return CompleteObject(BaseVal, BaseType);
2862}
2863
Richard Smith243ef902013-05-05 23:31:59 +00002864/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2865/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2866/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002867///
2868/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002869/// \param Conv - The expression for which we are performing the conversion.
2870/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002871/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2872/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002873/// \param LVal - The glvalue on which we are attempting to perform this action.
2874/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002875static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002876 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002877 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002878 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002879 return false;
2880
Richard Smith3229b742013-05-05 21:17:10 +00002881 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002882 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002883 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002884 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2885 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2886 // initializer until now for such expressions. Such an expression can't be
2887 // an ICE in C, so this only matters for fold.
2888 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2889 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002890 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002891 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002892 }
Richard Smith3229b742013-05-05 21:17:10 +00002893 APValue Lit;
2894 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2895 return false;
2896 CompleteObject LitObj(&Lit, Base->getType());
2897 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002898 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002899 // We represent a string literal array as an lvalue pointing at the
2900 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002901 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002902 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2903 CompleteObject StrObj(&Str, Base->getType());
2904 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002905 }
Richard Smith11562c52011-10-28 17:51:58 +00002906 }
2907
Richard Smith3229b742013-05-05 21:17:10 +00002908 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2909 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002910}
2911
2912/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002913static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002914 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002915 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002916 return false;
2917
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002918 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002919 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002920 return false;
2921 }
2922
Richard Smith3229b742013-05-05 21:17:10 +00002923 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2924 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002925}
2926
Richard Smith243ef902013-05-05 23:31:59 +00002927static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2928 return T->isSignedIntegerType() &&
2929 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2930}
2931
2932namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002933struct CompoundAssignSubobjectHandler {
2934 EvalInfo &Info;
2935 const Expr *E;
2936 QualType PromotedLHSType;
2937 BinaryOperatorKind Opcode;
2938 const APValue &RHS;
2939
2940 static const AccessKinds AccessKind = AK_Assign;
2941
2942 typedef bool result_type;
2943
2944 bool checkConst(QualType QT) {
2945 // Assigning to a const object has undefined behavior.
2946 if (QT.isConstQualified()) {
2947 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2948 return false;
2949 }
2950 return true;
2951 }
2952
2953 bool failed() { return false; }
2954 bool found(APValue &Subobj, QualType SubobjType) {
2955 switch (Subobj.getKind()) {
2956 case APValue::Int:
2957 return found(Subobj.getInt(), SubobjType);
2958 case APValue::Float:
2959 return found(Subobj.getFloat(), SubobjType);
2960 case APValue::ComplexInt:
2961 case APValue::ComplexFloat:
2962 // FIXME: Implement complex compound assignment.
2963 Info.Diag(E);
2964 return false;
2965 case APValue::LValue:
2966 return foundPointer(Subobj, SubobjType);
2967 default:
2968 // FIXME: can this happen?
2969 Info.Diag(E);
2970 return false;
2971 }
2972 }
2973 bool found(APSInt &Value, QualType SubobjType) {
2974 if (!checkConst(SubobjType))
2975 return false;
2976
2977 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2978 // We don't support compound assignment on integer-cast-to-pointer
2979 // values.
2980 Info.Diag(E);
2981 return false;
2982 }
2983
2984 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2985 SubobjType, Value);
2986 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2987 return false;
2988 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2989 return true;
2990 }
2991 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002992 return checkConst(SubobjType) &&
2993 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2994 Value) &&
2995 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2996 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002997 }
2998 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2999 if (!checkConst(SubobjType))
3000 return false;
3001
3002 QualType PointeeType;
3003 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3004 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003005
3006 if (PointeeType.isNull() || !RHS.isInt() ||
3007 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00003008 Info.Diag(E);
3009 return false;
3010 }
3011
Richard Smith861b5b52013-05-07 23:34:45 +00003012 int64_t Offset = getExtValue(RHS.getInt());
3013 if (Opcode == BO_Sub)
3014 Offset = -Offset;
3015
3016 LValue LVal;
3017 LVal.setFrom(Info.Ctx, Subobj);
3018 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3019 return false;
3020 LVal.moveInto(Subobj);
3021 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003022 }
3023 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3024 llvm_unreachable("shouldn't encounter string elements here");
3025 }
3026};
3027} // end anonymous namespace
3028
3029const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3030
3031/// Perform a compound assignment of LVal <op>= RVal.
3032static bool handleCompoundAssignment(
3033 EvalInfo &Info, const Expr *E,
3034 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3035 BinaryOperatorKind Opcode, const APValue &RVal) {
3036 if (LVal.Designator.Invalid)
3037 return false;
3038
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003039 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00003040 Info.Diag(E);
3041 return false;
3042 }
3043
3044 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3045 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3046 RVal };
3047 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3048}
3049
3050namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003051struct IncDecSubobjectHandler {
3052 EvalInfo &Info;
3053 const Expr *E;
3054 AccessKinds AccessKind;
3055 APValue *Old;
3056
3057 typedef bool result_type;
3058
3059 bool checkConst(QualType QT) {
3060 // Assigning to a const object has undefined behavior.
3061 if (QT.isConstQualified()) {
3062 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
3063 return false;
3064 }
3065 return true;
3066 }
3067
3068 bool failed() { return false; }
3069 bool found(APValue &Subobj, QualType SubobjType) {
3070 // Stash the old value. Also clear Old, so we don't clobber it later
3071 // if we're post-incrementing a complex.
3072 if (Old) {
3073 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003074 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003075 }
3076
3077 switch (Subobj.getKind()) {
3078 case APValue::Int:
3079 return found(Subobj.getInt(), SubobjType);
3080 case APValue::Float:
3081 return found(Subobj.getFloat(), SubobjType);
3082 case APValue::ComplexInt:
3083 return found(Subobj.getComplexIntReal(),
3084 SubobjType->castAs<ComplexType>()->getElementType()
3085 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3086 case APValue::ComplexFloat:
3087 return found(Subobj.getComplexFloatReal(),
3088 SubobjType->castAs<ComplexType>()->getElementType()
3089 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3090 case APValue::LValue:
3091 return foundPointer(Subobj, SubobjType);
3092 default:
3093 // FIXME: can this happen?
3094 Info.Diag(E);
3095 return false;
3096 }
3097 }
3098 bool found(APSInt &Value, QualType SubobjType) {
3099 if (!checkConst(SubobjType))
3100 return false;
3101
3102 if (!SubobjType->isIntegerType()) {
3103 // We don't support increment / decrement on integer-cast-to-pointer
3104 // values.
3105 Info.Diag(E);
3106 return false;
3107 }
3108
3109 if (Old) *Old = APValue(Value);
3110
3111 // bool arithmetic promotes to int, and the conversion back to bool
3112 // doesn't reduce mod 2^n, so special-case it.
3113 if (SubobjType->isBooleanType()) {
3114 if (AccessKind == AK_Increment)
3115 Value = 1;
3116 else
3117 Value = !Value;
3118 return true;
3119 }
3120
3121 bool WasNegative = Value.isNegative();
3122 if (AccessKind == AK_Increment) {
3123 ++Value;
3124
3125 if (!WasNegative && Value.isNegative() &&
3126 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3127 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003128 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003129 }
3130 } else {
3131 --Value;
3132
3133 if (WasNegative && !Value.isNegative() &&
3134 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3135 unsigned BitWidth = Value.getBitWidth();
3136 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3137 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003138 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003139 }
3140 }
3141 return true;
3142 }
3143 bool found(APFloat &Value, QualType SubobjType) {
3144 if (!checkConst(SubobjType))
3145 return false;
3146
3147 if (Old) *Old = APValue(Value);
3148
3149 APFloat One(Value.getSemantics(), 1);
3150 if (AccessKind == AK_Increment)
3151 Value.add(One, APFloat::rmNearestTiesToEven);
3152 else
3153 Value.subtract(One, APFloat::rmNearestTiesToEven);
3154 return true;
3155 }
3156 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3157 if (!checkConst(SubobjType))
3158 return false;
3159
3160 QualType PointeeType;
3161 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3162 PointeeType = PT->getPointeeType();
3163 else {
3164 Info.Diag(E);
3165 return false;
3166 }
3167
3168 LValue LVal;
3169 LVal.setFrom(Info.Ctx, Subobj);
3170 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3171 AccessKind == AK_Increment ? 1 : -1))
3172 return false;
3173 LVal.moveInto(Subobj);
3174 return true;
3175 }
3176 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3177 llvm_unreachable("shouldn't encounter string elements here");
3178 }
3179};
3180} // end anonymous namespace
3181
3182/// Perform an increment or decrement on LVal.
3183static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3184 QualType LValType, bool IsIncrement, APValue *Old) {
3185 if (LVal.Designator.Invalid)
3186 return false;
3187
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003188 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003189 Info.Diag(E);
3190 return false;
3191 }
3192
3193 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3194 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3195 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3196 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3197}
3198
Richard Smithe97cbd72011-11-11 04:05:33 +00003199/// Build an lvalue for the object argument of a member function call.
3200static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3201 LValue &This) {
3202 if (Object->getType()->isPointerType())
3203 return EvaluatePointer(Object, This, Info);
3204
3205 if (Object->isGLValue())
3206 return EvaluateLValue(Object, This, Info);
3207
Richard Smithd9f663b2013-04-22 15:31:51 +00003208 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003209 return EvaluateTemporary(Object, This, Info);
3210
Richard Smith3e79a572014-06-11 19:53:12 +00003211 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003212 return false;
3213}
3214
3215/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3216/// lvalue referring to the result.
3217///
3218/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003219/// \param LV - An lvalue referring to the base of the member pointer.
3220/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003221/// \param IncludeMember - Specifies whether the member itself is included in
3222/// the resulting LValue subobject designator. This is not possible when
3223/// creating a bound member function.
3224/// \return The field or method declaration to which the member pointer refers,
3225/// or 0 if evaluation fails.
3226static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003227 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003228 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003229 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003230 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003231 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003232 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003233 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003234
3235 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3236 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003237 if (!MemPtr.getDecl()) {
3238 // FIXME: Specific diagnostic.
3239 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003240 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003241 }
Richard Smith253c2a32012-01-27 01:14:48 +00003242
Richard Smith027bf112011-11-17 22:56:20 +00003243 if (MemPtr.isDerivedMember()) {
3244 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003245 // The end of the derived-to-base path for the base object must match the
3246 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003247 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003248 LV.Designator.Entries.size()) {
3249 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003250 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003251 }
Richard Smith027bf112011-11-17 22:56:20 +00003252 unsigned PathLengthToMember =
3253 LV.Designator.Entries.size() - MemPtr.Path.size();
3254 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3255 const CXXRecordDecl *LVDecl = getAsBaseClass(
3256 LV.Designator.Entries[PathLengthToMember + I]);
3257 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003258 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3259 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003260 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003261 }
Richard Smith027bf112011-11-17 22:56:20 +00003262 }
3263
3264 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003265 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003266 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003267 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003268 } else if (!MemPtr.Path.empty()) {
3269 // Extend the LValue path with the member pointer's path.
3270 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3271 MemPtr.Path.size() + IncludeMember);
3272
3273 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003274 if (const PointerType *PT = LVType->getAs<PointerType>())
3275 LVType = PT->getPointeeType();
3276 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3277 assert(RD && "member pointer access on non-class-type expression");
3278 // The first class in the path is that of the lvalue.
3279 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3280 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003281 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003282 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003283 RD = Base;
3284 }
3285 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003286 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3287 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003288 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003289 }
3290
3291 // Add the member. Note that we cannot build bound member functions here.
3292 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003293 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003294 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003295 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003296 } else if (const IndirectFieldDecl *IFD =
3297 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003298 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003299 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003300 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003301 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003302 }
Richard Smith027bf112011-11-17 22:56:20 +00003303 }
3304
3305 return MemPtr.getDecl();
3306}
3307
Richard Smith84401042013-06-03 05:03:02 +00003308static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3309 const BinaryOperator *BO,
3310 LValue &LV,
3311 bool IncludeMember = true) {
3312 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3313
3314 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003315 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003316 MemberPtr MemPtr;
3317 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3318 }
Craig Topper36250ad2014-05-12 05:36:57 +00003319 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003320 }
3321
3322 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3323 BO->getRHS(), IncludeMember);
3324}
3325
Richard Smith027bf112011-11-17 22:56:20 +00003326/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3327/// the provided lvalue, which currently refers to the base object.
3328static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3329 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003330 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003331 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003332 return false;
3333
Richard Smitha8105bc2012-01-06 16:39:00 +00003334 QualType TargetQT = E->getType();
3335 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3336 TargetQT = PT->getPointeeType();
3337
3338 // Check this cast lands within the final derived-to-base subobject path.
3339 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003340 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003341 << D.MostDerivedType << TargetQT;
3342 return false;
3343 }
3344
Richard Smith027bf112011-11-17 22:56:20 +00003345 // Check the type of the final cast. We don't need to check the path,
3346 // since a cast can only be formed if the path is unique.
3347 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003348 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3349 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003350 if (NewEntriesSize == D.MostDerivedPathLength)
3351 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3352 else
Richard Smith027bf112011-11-17 22:56:20 +00003353 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003354 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003355 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003356 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003357 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003358 }
Richard Smith027bf112011-11-17 22:56:20 +00003359
3360 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003361 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003362}
3363
Mike Stump876387b2009-10-27 22:09:17 +00003364namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003365enum EvalStmtResult {
3366 /// Evaluation failed.
3367 ESR_Failed,
3368 /// Hit a 'return' statement.
3369 ESR_Returned,
3370 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003371 ESR_Succeeded,
3372 /// Hit a 'continue' statement.
3373 ESR_Continue,
3374 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003375 ESR_Break,
3376 /// Still scanning for 'case' or 'default' statement.
3377 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003378};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003379}
Richard Smith254a73d2011-10-28 22:34:42 +00003380
Richard Smithd9f663b2013-04-22 15:31:51 +00003381static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3382 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3383 // We don't need to evaluate the initializer for a static local.
3384 if (!VD->hasLocalStorage())
3385 return true;
3386
3387 LValue Result;
3388 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003389 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003390
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003391 const Expr *InitE = VD->getInit();
3392 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003393 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3394 << false << VD->getType();
3395 Val = APValue();
3396 return false;
3397 }
3398
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003399 if (InitE->isValueDependent())
3400 return false;
3401
3402 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003403 // Wipe out any partially-computed value, to allow tracking that this
3404 // evaluation failed.
3405 Val = APValue();
3406 return false;
3407 }
3408 }
3409
3410 return true;
3411}
3412
Richard Smith4e18ca52013-05-06 05:56:11 +00003413/// Evaluate a condition (either a variable declaration or an expression).
3414static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3415 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003416 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003417 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3418 return false;
3419 return EvaluateAsBooleanCondition(Cond, Result, Info);
3420}
3421
Richard Smith89210072016-04-04 23:29:43 +00003422namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003423/// \brief A location where the result (returned value) of evaluating a
3424/// statement should be stored.
3425struct StmtResult {
3426 /// The APValue that should be filled in with the returned value.
3427 APValue &Value;
3428 /// The location containing the result, if any (used to support RVO).
3429 const LValue *Slot;
3430};
Richard Smith89210072016-04-04 23:29:43 +00003431}
Richard Smith52a980a2015-08-28 02:43:42 +00003432
3433static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003434 const Stmt *S,
3435 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003436
3437/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003438static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003439 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003440 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003441 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003442 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003443 case ESR_Break:
3444 return ESR_Succeeded;
3445 case ESR_Succeeded:
3446 case ESR_Continue:
3447 return ESR_Continue;
3448 case ESR_Failed:
3449 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003450 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003451 return ESR;
3452 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003453 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003454}
3455
Richard Smith496ddcf2013-05-12 17:32:42 +00003456/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003457static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003458 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003459 BlockScopeRAII Scope(Info);
3460
Richard Smith496ddcf2013-05-12 17:32:42 +00003461 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003462 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003463 {
3464 FullExpressionRAII Scope(Info);
3465 if (SS->getConditionVariable() &&
3466 !EvaluateDecl(Info, SS->getConditionVariable()))
3467 return ESR_Failed;
3468 if (!EvaluateInteger(SS->getCond(), Value, Info))
3469 return ESR_Failed;
3470 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003471
3472 // Find the switch case corresponding to the value of the condition.
3473 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003474 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003475 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3476 SC = SC->getNextSwitchCase()) {
3477 if (isa<DefaultStmt>(SC)) {
3478 Found = SC;
3479 continue;
3480 }
3481
3482 const CaseStmt *CS = cast<CaseStmt>(SC);
3483 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3484 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3485 : LHS;
3486 if (LHS <= Value && Value <= RHS) {
3487 Found = SC;
3488 break;
3489 }
3490 }
3491
3492 if (!Found)
3493 return ESR_Succeeded;
3494
3495 // Search the switch body for the switch case and evaluate it from there.
3496 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3497 case ESR_Break:
3498 return ESR_Succeeded;
3499 case ESR_Succeeded:
3500 case ESR_Continue:
3501 case ESR_Failed:
3502 case ESR_Returned:
3503 return ESR;
3504 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003505 // This can only happen if the switch case is nested within a statement
3506 // expression. We have no intention of supporting that.
3507 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3508 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003509 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003510 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003511}
3512
Richard Smith254a73d2011-10-28 22:34:42 +00003513// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003514static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003515 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003516 if (!Info.nextStep(S))
3517 return ESR_Failed;
3518
Richard Smith496ddcf2013-05-12 17:32:42 +00003519 // If we're hunting down a 'case' or 'default' label, recurse through
3520 // substatements until we hit the label.
3521 if (Case) {
3522 // FIXME: We don't start the lifetime of objects whose initialization we
3523 // jump over. However, such objects must be of class type with a trivial
3524 // default constructor that initialize all subobjects, so must be empty,
3525 // so this almost never matters.
3526 switch (S->getStmtClass()) {
3527 case Stmt::CompoundStmtClass:
3528 // FIXME: Precompute which substatement of a compound statement we
3529 // would jump to, and go straight there rather than performing a
3530 // linear scan each time.
3531 case Stmt::LabelStmtClass:
3532 case Stmt::AttributedStmtClass:
3533 case Stmt::DoStmtClass:
3534 break;
3535
3536 case Stmt::CaseStmtClass:
3537 case Stmt::DefaultStmtClass:
3538 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003539 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003540 break;
3541
3542 case Stmt::IfStmtClass: {
3543 // FIXME: Precompute which side of an 'if' we would jump to, and go
3544 // straight there rather than scanning both sides.
3545 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003546
3547 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3548 // preceded by our switch label.
3549 BlockScopeRAII Scope(Info);
3550
Richard Smith496ddcf2013-05-12 17:32:42 +00003551 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3552 if (ESR != ESR_CaseNotFound || !IS->getElse())
3553 return ESR;
3554 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3555 }
3556
3557 case Stmt::WhileStmtClass: {
3558 EvalStmtResult ESR =
3559 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3560 if (ESR != ESR_Continue)
3561 return ESR;
3562 break;
3563 }
3564
3565 case Stmt::ForStmtClass: {
3566 const ForStmt *FS = cast<ForStmt>(S);
3567 EvalStmtResult ESR =
3568 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3569 if (ESR != ESR_Continue)
3570 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003571 if (FS->getInc()) {
3572 FullExpressionRAII IncScope(Info);
3573 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3574 return ESR_Failed;
3575 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003576 break;
3577 }
3578
3579 case Stmt::DeclStmtClass:
3580 // FIXME: If the variable has initialization that can't be jumped over,
3581 // bail out of any immediately-surrounding compound-statement too.
3582 default:
3583 return ESR_CaseNotFound;
3584 }
3585 }
3586
Richard Smith254a73d2011-10-28 22:34:42 +00003587 switch (S->getStmtClass()) {
3588 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003589 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003590 // Don't bother evaluating beyond an expression-statement which couldn't
3591 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003592 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003593 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003594 return ESR_Failed;
3595 return ESR_Succeeded;
3596 }
3597
3598 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003599 return ESR_Failed;
3600
3601 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003602 return ESR_Succeeded;
3603
Richard Smithd9f663b2013-04-22 15:31:51 +00003604 case Stmt::DeclStmtClass: {
3605 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003606 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003607 // Each declaration initialization is its own full-expression.
3608 // FIXME: This isn't quite right; if we're performing aggregate
3609 // initialization, each braced subexpression is its own full-expression.
3610 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003611 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003612 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003613 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003614 return ESR_Succeeded;
3615 }
3616
Richard Smith357362d2011-12-13 06:39:58 +00003617 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003618 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003619 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003620 if (RetExpr &&
3621 !(Result.Slot
3622 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3623 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003624 return ESR_Failed;
3625 return ESR_Returned;
3626 }
Richard Smith254a73d2011-10-28 22:34:42 +00003627
3628 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003629 BlockScopeRAII Scope(Info);
3630
Richard Smith254a73d2011-10-28 22:34:42 +00003631 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003632 for (const auto *BI : CS->body()) {
3633 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003634 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003635 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003636 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003637 return ESR;
3638 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003639 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003640 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003641
3642 case Stmt::IfStmtClass: {
3643 const IfStmt *IS = cast<IfStmt>(S);
3644
3645 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003646 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003647 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003648 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003649 return ESR_Failed;
3650
3651 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3652 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3653 if (ESR != ESR_Succeeded)
3654 return ESR;
3655 }
3656 return ESR_Succeeded;
3657 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003658
3659 case Stmt::WhileStmtClass: {
3660 const WhileStmt *WS = cast<WhileStmt>(S);
3661 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003662 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003663 bool Continue;
3664 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3665 Continue))
3666 return ESR_Failed;
3667 if (!Continue)
3668 break;
3669
3670 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3671 if (ESR != ESR_Continue)
3672 return ESR;
3673 }
3674 return ESR_Succeeded;
3675 }
3676
3677 case Stmt::DoStmtClass: {
3678 const DoStmt *DS = cast<DoStmt>(S);
3679 bool Continue;
3680 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003681 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003682 if (ESR != ESR_Continue)
3683 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003684 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003685
Richard Smith08d6a2c2013-07-24 07:11:57 +00003686 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003687 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3688 return ESR_Failed;
3689 } while (Continue);
3690 return ESR_Succeeded;
3691 }
3692
3693 case Stmt::ForStmtClass: {
3694 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003695 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003696 if (FS->getInit()) {
3697 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3698 if (ESR != ESR_Succeeded)
3699 return ESR;
3700 }
3701 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003702 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003703 bool Continue = true;
3704 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3705 FS->getCond(), Continue))
3706 return ESR_Failed;
3707 if (!Continue)
3708 break;
3709
3710 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3711 if (ESR != ESR_Continue)
3712 return ESR;
3713
Richard Smith08d6a2c2013-07-24 07:11:57 +00003714 if (FS->getInc()) {
3715 FullExpressionRAII IncScope(Info);
3716 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3717 return ESR_Failed;
3718 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003719 }
3720 return ESR_Succeeded;
3721 }
3722
Richard Smith896e0d72013-05-06 06:51:17 +00003723 case Stmt::CXXForRangeStmtClass: {
3724 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003725 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003726
3727 // Initialize the __range variable.
3728 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3729 if (ESR != ESR_Succeeded)
3730 return ESR;
3731
3732 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003733 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3734 if (ESR != ESR_Succeeded)
3735 return ESR;
3736 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003737 if (ESR != ESR_Succeeded)
3738 return ESR;
3739
3740 while (true) {
3741 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003742 {
3743 bool Continue = true;
3744 FullExpressionRAII CondExpr(Info);
3745 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3746 return ESR_Failed;
3747 if (!Continue)
3748 break;
3749 }
Richard Smith896e0d72013-05-06 06:51:17 +00003750
3751 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003752 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003753 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3754 if (ESR != ESR_Succeeded)
3755 return ESR;
3756
3757 // Loop body.
3758 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3759 if (ESR != ESR_Continue)
3760 return ESR;
3761
3762 // Increment: ++__begin
3763 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3764 return ESR_Failed;
3765 }
3766
3767 return ESR_Succeeded;
3768 }
3769
Richard Smith496ddcf2013-05-12 17:32:42 +00003770 case Stmt::SwitchStmtClass:
3771 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3772
Richard Smith4e18ca52013-05-06 05:56:11 +00003773 case Stmt::ContinueStmtClass:
3774 return ESR_Continue;
3775
3776 case Stmt::BreakStmtClass:
3777 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003778
3779 case Stmt::LabelStmtClass:
3780 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3781
3782 case Stmt::AttributedStmtClass:
3783 // As a general principle, C++11 attributes can be ignored without
3784 // any semantic impact.
3785 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3786 Case);
3787
3788 case Stmt::CaseStmtClass:
3789 case Stmt::DefaultStmtClass:
3790 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003791 }
3792}
3793
Richard Smithcc36f692011-12-22 02:22:31 +00003794/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3795/// default constructor. If so, we'll fold it whether or not it's marked as
3796/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3797/// so we need special handling.
3798static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003799 const CXXConstructorDecl *CD,
3800 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003801 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3802 return false;
3803
Richard Smith66e05fe2012-01-18 05:21:49 +00003804 // Value-initialization does not call a trivial default constructor, so such a
3805 // call is a core constant expression whether or not the constructor is
3806 // constexpr.
3807 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003808 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003809 // FIXME: If DiagDecl is an implicitly-declared special member function,
3810 // we should be much more explicit about why it's not constexpr.
3811 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3812 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3813 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003814 } else {
3815 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3816 }
3817 }
3818 return true;
3819}
3820
Richard Smith357362d2011-12-13 06:39:58 +00003821/// CheckConstexprFunction - Check that a function can be called in a constant
3822/// expression.
3823static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3824 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003825 const FunctionDecl *Definition,
3826 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003827 // Potential constant expressions can contain calls to declared, but not yet
3828 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003829 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003830 Declaration->isConstexpr())
3831 return false;
3832
Richard Smith0838f3a2013-05-14 05:18:44 +00003833 // Bail out with no diagnostic if the function declaration itself is invalid.
3834 // We will have produced a relevant diagnostic while parsing it.
3835 if (Declaration->isInvalidDecl())
3836 return false;
3837
Richard Smith357362d2011-12-13 06:39:58 +00003838 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003839 if (Definition && Definition->isConstexpr() &&
3840 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003841 return true;
3842
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003843 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003844 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003845 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3846 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003847 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3848 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3849 << DiagDecl;
3850 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3851 } else {
3852 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3853 }
3854 return false;
3855}
3856
Richard Smithbe6dd812014-11-19 21:27:17 +00003857/// Determine if a class has any fields that might need to be copied by a
3858/// trivial copy or move operation.
3859static bool hasFields(const CXXRecordDecl *RD) {
3860 if (!RD || RD->isEmpty())
3861 return false;
3862 for (auto *FD : RD->fields()) {
3863 if (FD->isUnnamedBitfield())
3864 continue;
3865 return true;
3866 }
3867 for (auto &Base : RD->bases())
3868 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3869 return true;
3870 return false;
3871}
3872
Richard Smithd62306a2011-11-10 06:34:14 +00003873namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003874typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003875}
3876
3877/// EvaluateArgs - Evaluate the arguments to a function call.
3878static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3879 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003880 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003881 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003882 I != E; ++I) {
3883 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3884 // If we're checking for a potential constant expression, evaluate all
3885 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00003886 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00003887 return false;
3888 Success = false;
3889 }
3890 }
3891 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003892}
3893
Richard Smith254a73d2011-10-28 22:34:42 +00003894/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003895static bool HandleFunctionCall(SourceLocation CallLoc,
3896 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003897 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003898 EvalInfo &Info, APValue &Result,
3899 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003900 ArgVector ArgValues(Args.size());
3901 if (!EvaluateArgs(Args, ArgValues, Info))
3902 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003903
Richard Smith253c2a32012-01-27 01:14:48 +00003904 if (!Info.CheckCallLimit(CallLoc))
3905 return false;
3906
3907 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003908
3909 // For a trivial copy or move assignment, perform an APValue copy. This is
3910 // essential for unions, where the operations performed by the assignment
3911 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003912 //
3913 // Skip this for non-union classes with no fields; in that case, the defaulted
3914 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003915 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003916 if (MD && MD->isDefaulted() &&
3917 (MD->getParent()->isUnion() ||
3918 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003919 assert(This &&
3920 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3921 LValue RHS;
3922 RHS.setFrom(Info.Ctx, ArgValues[0]);
3923 APValue RHSValue;
3924 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3925 RHS, RHSValue))
3926 return false;
3927 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3928 RHSValue))
3929 return false;
3930 This->moveInto(Result);
3931 return true;
3932 }
3933
Richard Smith52a980a2015-08-28 02:43:42 +00003934 StmtResult Ret = {Result, ResultSlot};
3935 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003936 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003937 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003938 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003939 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003940 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003941 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003942}
3943
Richard Smithd62306a2011-11-10 06:34:14 +00003944/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003945static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003946 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003947 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003948 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003949 ArgVector ArgValues(Args.size());
3950 if (!EvaluateArgs(Args, ArgValues, Info))
3951 return false;
3952
Richard Smith253c2a32012-01-27 01:14:48 +00003953 if (!Info.CheckCallLimit(CallLoc))
3954 return false;
3955
Richard Smith3607ffe2012-02-13 03:54:03 +00003956 const CXXRecordDecl *RD = Definition->getParent();
3957 if (RD->getNumVBases()) {
3958 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3959 return false;
3960 }
3961
Richard Smith253c2a32012-01-27 01:14:48 +00003962 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003963
Richard Smith52a980a2015-08-28 02:43:42 +00003964 // FIXME: Creating an APValue just to hold a nonexistent return value is
3965 // wasteful.
3966 APValue RetVal;
3967 StmtResult Ret = {RetVal, nullptr};
3968
Richard Smithd62306a2011-11-10 06:34:14 +00003969 // If it's a delegating constructor, just delegate.
3970 if (Definition->isDelegatingConstructor()) {
3971 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003972 {
3973 FullExpressionRAII InitScope(Info);
3974 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3975 return false;
3976 }
Richard Smith52a980a2015-08-28 02:43:42 +00003977 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003978 }
3979
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003980 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003981 // essential for unions (or classes with anonymous union members), where the
3982 // operations performed by the constructor cannot be represented by
3983 // ctor-initializers.
3984 //
3985 // Skip this for empty non-union classes; we should not perform an
3986 // lvalue-to-rvalue conversion on them because their copy constructor does not
3987 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003988 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003989 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003990 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003991 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003992 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003993 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003994 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003995 }
3996
3997 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003998 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003999 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004000 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004001
John McCalld7bca762012-05-01 00:38:49 +00004002 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004003 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4004
Richard Smith08d6a2c2013-07-24 07:11:57 +00004005 // A scope for temporaries lifetime-extended by reference members.
4006 BlockScopeRAII LifetimeExtendedScope(Info);
4007
Richard Smith253c2a32012-01-27 01:14:48 +00004008 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004009 unsigned BasesSeen = 0;
4010#ifndef NDEBUG
4011 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4012#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004013 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004014 LValue Subobject = This;
4015 APValue *Value = &Result;
4016
4017 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004018 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004019 if (I->isBaseInitializer()) {
4020 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004021#ifndef NDEBUG
4022 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004023 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004024 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4025 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4026 "base class initializers not in expected order");
4027 ++BaseIt;
4028#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004029 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004030 BaseType->getAsCXXRecordDecl(), &Layout))
4031 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004032 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004033 } else if ((FD = I->getMember())) {
4034 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004035 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004036 if (RD->isUnion()) {
4037 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004038 Value = &Result.getUnionValue();
4039 } else {
4040 Value = &Result.getStructField(FD->getFieldIndex());
4041 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004042 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004043 // Walk the indirect field decl's chain to find the object to initialize,
4044 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004045 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004046 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004047 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4048 // Switch the union field if it differs. This happens if we had
4049 // preceding zero-initialization, and we're now initializing a union
4050 // subobject other than the first.
4051 // FIXME: In this case, the values of the other subobjects are
4052 // specified, since zero-initialization sets all padding bits to zero.
4053 if (Value->isUninit() ||
4054 (Value->isUnion() && Value->getUnionField() != FD)) {
4055 if (CD->isUnion())
4056 *Value = APValue(FD);
4057 else
4058 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004059 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004060 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004061 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004062 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004063 if (CD->isUnion())
4064 Value = &Value->getUnionValue();
4065 else
4066 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004067 }
Richard Smithd62306a2011-11-10 06:34:14 +00004068 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004069 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004070 }
Richard Smith253c2a32012-01-27 01:14:48 +00004071
Richard Smith08d6a2c2013-07-24 07:11:57 +00004072 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004073 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4074 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004075 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004076 // If we're checking for a potential constant expression, evaluate all
4077 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004078 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004079 return false;
4080 Success = false;
4081 }
Richard Smithd62306a2011-11-10 06:34:14 +00004082 }
4083
Richard Smithd9f663b2013-04-22 15:31:51 +00004084 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004085 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004086}
4087
Eli Friedman9a156e52008-11-12 09:44:48 +00004088//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004089// Generic Evaluation
4090//===----------------------------------------------------------------------===//
4091namespace {
4092
Aaron Ballman68af21c2014-01-03 19:26:43 +00004093template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004094class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004095 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004096private:
Richard Smith52a980a2015-08-28 02:43:42 +00004097 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004098 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004099 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004100 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004101 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004102 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004103 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004104
Richard Smith17100ba2012-02-16 02:46:34 +00004105 // Check whether a conditional operator with a non-constant condition is a
4106 // potential constant expression. If neither arm is a potential constant
4107 // expression, then the conditional operator is not either.
4108 template<typename ConditionalOperator>
4109 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004110 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004111
4112 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004113 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004114 {
Richard Smith17100ba2012-02-16 02:46:34 +00004115 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004116 StmtVisitorTy::Visit(E->getFalseExpr());
4117 if (Diag.empty())
4118 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004119 }
Richard Smith17100ba2012-02-16 02:46:34 +00004120
George Burgess IV8c892b52016-05-25 22:31:54 +00004121 {
4122 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004123 Diag.clear();
4124 StmtVisitorTy::Visit(E->getTrueExpr());
4125 if (Diag.empty())
4126 return;
4127 }
4128
4129 Error(E, diag::note_constexpr_conditional_never_const);
4130 }
4131
4132
4133 template<typename ConditionalOperator>
4134 bool HandleConditionalOperator(const ConditionalOperator *E) {
4135 bool BoolResult;
4136 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004137 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004138 CheckPotentialConstantConditional(E);
4139 return false;
4140 }
4141
4142 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4143 return StmtVisitorTy::Visit(EvalExpr);
4144 }
4145
Peter Collingbournee9200682011-05-13 03:29:01 +00004146protected:
4147 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004148 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004149 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4150
Richard Smith92b1ce02011-12-12 09:28:41 +00004151 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004152 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004153 }
4154
Aaron Ballman68af21c2014-01-03 19:26:43 +00004155 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004156
4157public:
4158 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4159
4160 EvalInfo &getEvalInfo() { return Info; }
4161
Richard Smithf57d8cb2011-12-09 22:58:01 +00004162 /// Report an evaluation error. This should only be called when an error is
4163 /// first discovered. When propagating an error, just return false.
4164 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004165 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004166 return false;
4167 }
4168 bool Error(const Expr *E) {
4169 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4170 }
4171
Aaron Ballman68af21c2014-01-03 19:26:43 +00004172 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004173 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004174 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004175 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004176 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004177 }
4178
Aaron Ballman68af21c2014-01-03 19:26:43 +00004179 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004180 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004181 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004182 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004183 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004184 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004185 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004186 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004187 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004188 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004189 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004190 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004191 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004192 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004193 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004194 // The initializer may not have been parsed yet, or might be erroneous.
4195 if (!E->getExpr())
4196 return Error(E);
4197 return StmtVisitorTy::Visit(E->getExpr());
4198 }
Richard Smith5894a912011-12-19 22:12:41 +00004199 // We cannot create any objects for which cleanups are required, so there is
4200 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004201 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004202 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004203
Aaron Ballman68af21c2014-01-03 19:26:43 +00004204 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004205 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4206 return static_cast<Derived*>(this)->VisitCastExpr(E);
4207 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004208 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004209 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4210 return static_cast<Derived*>(this)->VisitCastExpr(E);
4211 }
4212
Aaron Ballman68af21c2014-01-03 19:26:43 +00004213 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004214 switch (E->getOpcode()) {
4215 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004216 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004217
4218 case BO_Comma:
4219 VisitIgnoredValue(E->getLHS());
4220 return StmtVisitorTy::Visit(E->getRHS());
4221
4222 case BO_PtrMemD:
4223 case BO_PtrMemI: {
4224 LValue Obj;
4225 if (!HandleMemberPointerAccess(Info, E, Obj))
4226 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004227 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004228 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004229 return false;
4230 return DerivedSuccess(Result, E);
4231 }
4232 }
4233 }
4234
Aaron Ballman68af21c2014-01-03 19:26:43 +00004235 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004236 // Evaluate and cache the common expression. We treat it as a temporary,
4237 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004238 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004239 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004240 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004241
Richard Smith17100ba2012-02-16 02:46:34 +00004242 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004243 }
4244
Aaron Ballman68af21c2014-01-03 19:26:43 +00004245 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004246 bool IsBcpCall = false;
4247 // If the condition (ignoring parens) is a __builtin_constant_p call,
4248 // the result is a constant expression if it can be folded without
4249 // side-effects. This is an important GNU extension. See GCC PR38377
4250 // for discussion.
4251 if (const CallExpr *CallCE =
4252 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004253 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004254 IsBcpCall = true;
4255
4256 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4257 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004258 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004259 return false;
4260
Richard Smith6d4c6582013-11-05 22:18:15 +00004261 FoldConstant Fold(Info, IsBcpCall);
4262 if (!HandleConditionalOperator(E)) {
4263 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004264 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004265 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004266
4267 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004268 }
4269
Aaron Ballman68af21c2014-01-03 19:26:43 +00004270 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004271 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4272 return DerivedSuccess(*Value, E);
4273
4274 const Expr *Source = E->getSourceExpr();
4275 if (!Source)
4276 return Error(E);
4277 if (Source == E) { // sanity checking.
4278 assert(0 && "OpaqueValueExpr recursively refers to itself");
4279 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004280 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004281 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004282 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004283
Aaron Ballman68af21c2014-01-03 19:26:43 +00004284 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004285 APValue Result;
4286 if (!handleCallExpr(E, Result, nullptr))
4287 return false;
4288 return DerivedSuccess(Result, E);
4289 }
4290
4291 bool handleCallExpr(const CallExpr *E, APValue &Result,
4292 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004293 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004294 QualType CalleeType = Callee->getType();
4295
Craig Topper36250ad2014-05-12 05:36:57 +00004296 const FunctionDecl *FD = nullptr;
4297 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004298 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004299 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004300
Richard Smithe97cbd72011-11-11 04:05:33 +00004301 // Extract function decl and 'this' pointer from the callee.
4302 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004303 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004304 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4305 // Explicit bound member calls, such as x.f() or p->g();
4306 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004307 return false;
4308 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004309 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004310 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004311 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4312 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004313 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4314 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004315 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004316 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004317 return Error(Callee);
4318
4319 FD = dyn_cast<FunctionDecl>(Member);
4320 if (!FD)
4321 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004322 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004323 LValue Call;
4324 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004325 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004326
Richard Smitha8105bc2012-01-06 16:39:00 +00004327 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004328 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004329 FD = dyn_cast_or_null<FunctionDecl>(
4330 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004331 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004332 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004333
4334 // Overloaded operator calls to member functions are represented as normal
4335 // calls with '*this' as the first argument.
4336 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4337 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004338 // FIXME: When selecting an implicit conversion for an overloaded
4339 // operator delete, we sometimes try to evaluate calls to conversion
4340 // operators without a 'this' parameter!
4341 if (Args.empty())
4342 return Error(E);
4343
Richard Smithe97cbd72011-11-11 04:05:33 +00004344 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4345 return false;
4346 This = &ThisVal;
4347 Args = Args.slice(1);
4348 }
4349
4350 // Don't call function pointers which have been cast to some other type.
4351 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004352 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004353 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004354 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004355
Richard Smith47b34932012-02-01 02:39:43 +00004356 if (This && !This->checkSubobject(Info, E, CSK_This))
4357 return false;
4358
Richard Smith3607ffe2012-02-13 03:54:03 +00004359 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4360 // calls to such functions in constant expressions.
4361 if (This && !HasQualifier &&
4362 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4363 return Error(E, diag::note_constexpr_virtual_call);
4364
Craig Topper36250ad2014-05-12 05:36:57 +00004365 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004366 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004367
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004368 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004369 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4370 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004371 return false;
4372
Richard Smith52a980a2015-08-28 02:43:42 +00004373 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004374 }
4375
Aaron Ballman68af21c2014-01-03 19:26:43 +00004376 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004377 return StmtVisitorTy::Visit(E->getInitializer());
4378 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004379 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004380 if (E->getNumInits() == 0)
4381 return DerivedZeroInitialization(E);
4382 if (E->getNumInits() == 1)
4383 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004384 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004385 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004386 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004387 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004388 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004389 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004390 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004391 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004392 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004393 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004394 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004395
Richard Smithd62306a2011-11-10 06:34:14 +00004396 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004397 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004398 assert(!E->isArrow() && "missing call to bound member function?");
4399
Richard Smith2e312c82012-03-03 22:46:17 +00004400 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004401 if (!Evaluate(Val, Info, E->getBase()))
4402 return false;
4403
4404 QualType BaseTy = E->getBase()->getType();
4405
4406 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004407 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004408 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004409 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004410 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4411
Richard Smith3229b742013-05-05 21:17:10 +00004412 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004413 SubobjectDesignator Designator(BaseTy);
4414 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004415
Richard Smith3229b742013-05-05 21:17:10 +00004416 APValue Result;
4417 return extractSubobject(Info, E, Obj, Designator, Result) &&
4418 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004419 }
4420
Aaron Ballman68af21c2014-01-03 19:26:43 +00004421 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004422 switch (E->getCastKind()) {
4423 default:
4424 break;
4425
Richard Smitha23ab512013-05-23 00:30:41 +00004426 case CK_AtomicToNonAtomic: {
4427 APValue AtomicVal;
4428 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4429 return false;
4430 return DerivedSuccess(AtomicVal, E);
4431 }
4432
Richard Smith11562c52011-10-28 17:51:58 +00004433 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004434 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004435 return StmtVisitorTy::Visit(E->getSubExpr());
4436
4437 case CK_LValueToRValue: {
4438 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004439 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4440 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004441 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004442 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004443 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004444 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004445 return false;
4446 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004447 }
4448 }
4449
Richard Smithf57d8cb2011-12-09 22:58:01 +00004450 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004451 }
4452
Aaron Ballman68af21c2014-01-03 19:26:43 +00004453 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004454 return VisitUnaryPostIncDec(UO);
4455 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004456 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004457 return VisitUnaryPostIncDec(UO);
4458 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004459 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004460 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004461 return Error(UO);
4462
4463 LValue LVal;
4464 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4465 return false;
4466 APValue RVal;
4467 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4468 UO->isIncrementOp(), &RVal))
4469 return false;
4470 return DerivedSuccess(RVal, UO);
4471 }
4472
Aaron Ballman68af21c2014-01-03 19:26:43 +00004473 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004474 // We will have checked the full-expressions inside the statement expression
4475 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004476 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004477 return Error(E);
4478
Richard Smith08d6a2c2013-07-24 07:11:57 +00004479 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004480 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004481 if (CS->body_empty())
4482 return true;
4483
Richard Smith51f03172013-06-20 03:00:05 +00004484 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4485 BE = CS->body_end();
4486 /**/; ++BI) {
4487 if (BI + 1 == BE) {
4488 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4489 if (!FinalExpr) {
4490 Info.Diag((*BI)->getLocStart(),
4491 diag::note_constexpr_stmt_expr_unsupported);
4492 return false;
4493 }
4494 return this->Visit(FinalExpr);
4495 }
4496
4497 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004498 StmtResult Result = { ReturnValue, nullptr };
4499 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004500 if (ESR != ESR_Succeeded) {
4501 // FIXME: If the statement-expression terminated due to 'return',
4502 // 'break', or 'continue', it would be nice to propagate that to
4503 // the outer statement evaluation rather than bailing out.
4504 if (ESR != ESR_Failed)
4505 Info.Diag((*BI)->getLocStart(),
4506 diag::note_constexpr_stmt_expr_unsupported);
4507 return false;
4508 }
4509 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004510
4511 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004512 }
4513
Richard Smith4a678122011-10-24 18:44:57 +00004514 /// Visit a value which is evaluated, but whose value is ignored.
4515 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004516 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004517 }
David Majnemere9807b22016-02-26 04:23:19 +00004518
4519 /// Potentially visit a MemberExpr's base expression.
4520 void VisitIgnoredBaseExpression(const Expr *E) {
4521 // While MSVC doesn't evaluate the base expression, it does diagnose the
4522 // presence of side-effecting behavior.
4523 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4524 return;
4525 VisitIgnoredValue(E);
4526 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004527};
4528
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004529}
Peter Collingbournee9200682011-05-13 03:29:01 +00004530
4531//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004532// Common base class for lvalue and temporary evaluation.
4533//===----------------------------------------------------------------------===//
4534namespace {
4535template<class Derived>
4536class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004537 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004538protected:
4539 LValue &Result;
4540 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004541 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004542
4543 bool Success(APValue::LValueBase B) {
4544 Result.set(B);
4545 return true;
4546 }
4547
4548public:
4549 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4550 ExprEvaluatorBaseTy(Info), Result(Result) {}
4551
Richard Smith2e312c82012-03-03 22:46:17 +00004552 bool Success(const APValue &V, const Expr *E) {
4553 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004554 return true;
4555 }
Richard Smith027bf112011-11-17 22:56:20 +00004556
Richard Smith027bf112011-11-17 22:56:20 +00004557 bool VisitMemberExpr(const MemberExpr *E) {
4558 // Handle non-static data members.
4559 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004560 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004561 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004562 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004563 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004564 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004565 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004566 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004567 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004568 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004569 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004570 BaseTy = E->getBase()->getType();
4571 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004572 if (!EvalOK) {
4573 if (!this->Info.allowInvalidBaseExpr())
4574 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004575 Result.setInvalid(E);
4576 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004577 }
Richard Smith027bf112011-11-17 22:56:20 +00004578
Richard Smith1b78b3d2012-01-25 22:15:11 +00004579 const ValueDecl *MD = E->getMemberDecl();
4580 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4581 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4582 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4583 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004584 if (!HandleLValueMember(this->Info, E, Result, FD))
4585 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004586 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004587 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4588 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004589 } else
4590 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004591
Richard Smith1b78b3d2012-01-25 22:15:11 +00004592 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004593 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004594 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004595 RefValue))
4596 return false;
4597 return Success(RefValue, E);
4598 }
4599 return true;
4600 }
4601
4602 bool VisitBinaryOperator(const BinaryOperator *E) {
4603 switch (E->getOpcode()) {
4604 default:
4605 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4606
4607 case BO_PtrMemD:
4608 case BO_PtrMemI:
4609 return HandleMemberPointerAccess(this->Info, E, Result);
4610 }
4611 }
4612
4613 bool VisitCastExpr(const CastExpr *E) {
4614 switch (E->getCastKind()) {
4615 default:
4616 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4617
4618 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004619 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004620 if (!this->Visit(E->getSubExpr()))
4621 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004622
4623 // Now figure out the necessary offset to add to the base LV to get from
4624 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004625 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4626 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004627 }
4628 }
4629};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004630}
Richard Smith027bf112011-11-17 22:56:20 +00004631
4632//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004633// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004634//
4635// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4636// function designators (in C), decl references to void objects (in C), and
4637// temporaries (if building with -Wno-address-of-temporary).
4638//
4639// LValue evaluation produces values comprising a base expression of one of the
4640// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004641// - Declarations
4642// * VarDecl
4643// * FunctionDecl
4644// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004645// * CompoundLiteralExpr in C
4646// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004647// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004648// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004649// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004650// * ObjCEncodeExpr
4651// * AddrLabelExpr
4652// * BlockExpr
4653// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004654// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004655// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004656// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004657// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4658// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004659// * A MaterializeTemporaryExpr that has static storage duration, with no
4660// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004661// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004662//===----------------------------------------------------------------------===//
4663namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004664class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004665 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004666public:
Richard Smith027bf112011-11-17 22:56:20 +00004667 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4668 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004669
Richard Smith11562c52011-10-28 17:51:58 +00004670 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004671 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004672
Peter Collingbournee9200682011-05-13 03:29:01 +00004673 bool VisitDeclRefExpr(const DeclRefExpr *E);
4674 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004675 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004676 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4677 bool VisitMemberExpr(const MemberExpr *E);
4678 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4679 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004680 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004681 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004682 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4683 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004684 bool VisitUnaryReal(const UnaryOperator *E);
4685 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004686 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4687 return VisitUnaryPreIncDec(UO);
4688 }
4689 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4690 return VisitUnaryPreIncDec(UO);
4691 }
Richard Smith3229b742013-05-05 21:17:10 +00004692 bool VisitBinAssign(const BinaryOperator *BO);
4693 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004694
Peter Collingbournee9200682011-05-13 03:29:01 +00004695 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004696 switch (E->getCastKind()) {
4697 default:
Richard Smith027bf112011-11-17 22:56:20 +00004698 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004699
Eli Friedmance3e02a2011-10-11 00:13:24 +00004700 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004701 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004702 if (!Visit(E->getSubExpr()))
4703 return false;
4704 Result.Designator.setInvalid();
4705 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004706
Richard Smith027bf112011-11-17 22:56:20 +00004707 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004708 if (!Visit(E->getSubExpr()))
4709 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004710 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004711 }
4712 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004713};
4714} // end anonymous namespace
4715
Richard Smith11562c52011-10-28 17:51:58 +00004716/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004717/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004718/// * function designators in C, and
4719/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004720/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004721static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4722 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004723 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004724 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004725}
4726
Peter Collingbournee9200682011-05-13 03:29:01 +00004727bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004728 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004729 return Success(FD);
4730 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004731 return VisitVarDecl(E, VD);
4732 return Error(E);
4733}
Richard Smith733237d2011-10-24 23:14:33 +00004734
Richard Smith11562c52011-10-28 17:51:58 +00004735bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004736 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004737 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4738 Frame = Info.CurrentCall;
4739
Richard Smithfec09922011-11-01 16:57:24 +00004740 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004741 if (Frame) {
4742 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004743 return true;
4744 }
Richard Smithce40ad62011-11-12 22:28:03 +00004745 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004746 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004747
Richard Smith3229b742013-05-05 21:17:10 +00004748 APValue *V;
4749 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004750 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004751 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004752 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004753 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4754 return false;
4755 }
Richard Smith3229b742013-05-05 21:17:10 +00004756 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004757}
4758
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004759bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4760 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004761 // Walk through the expression to find the materialized temporary itself.
4762 SmallVector<const Expr *, 2> CommaLHSs;
4763 SmallVector<SubobjectAdjustment, 2> Adjustments;
4764 const Expr *Inner = E->GetTemporaryExpr()->
4765 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004766
Richard Smith84401042013-06-03 05:03:02 +00004767 // If we passed any comma operators, evaluate their LHSs.
4768 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4769 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4770 return false;
4771
Richard Smithe6c01442013-06-05 00:46:14 +00004772 // A materialized temporary with static storage duration can appear within the
4773 // result of a constant expression evaluation, so we need to preserve its
4774 // value for use outside this evaluation.
4775 APValue *Value;
4776 if (E->getStorageDuration() == SD_Static) {
4777 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004778 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004779 Result.set(E);
4780 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004781 Value = &Info.CurrentCall->
4782 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004783 Result.set(E, Info.CurrentCall->Index);
4784 }
4785
Richard Smithea4ad5d2013-06-06 08:19:16 +00004786 QualType Type = Inner->getType();
4787
Richard Smith84401042013-06-03 05:03:02 +00004788 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004789 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4790 (E->getStorageDuration() == SD_Static &&
4791 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4792 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004793 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004794 }
Richard Smith84401042013-06-03 05:03:02 +00004795
4796 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004797 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4798 --I;
4799 switch (Adjustments[I].Kind) {
4800 case SubobjectAdjustment::DerivedToBaseAdjustment:
4801 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4802 Type, Result))
4803 return false;
4804 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4805 break;
4806
4807 case SubobjectAdjustment::FieldAdjustment:
4808 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4809 return false;
4810 Type = Adjustments[I].Field->getType();
4811 break;
4812
4813 case SubobjectAdjustment::MemberPointerAdjustment:
4814 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4815 Adjustments[I].Ptr.RHS))
4816 return false;
4817 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4818 break;
4819 }
4820 }
4821
4822 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004823}
4824
Peter Collingbournee9200682011-05-13 03:29:01 +00004825bool
4826LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004827 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4828 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4829 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004830 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004831}
4832
Richard Smith6e525142011-12-27 12:18:28 +00004833bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004834 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004835 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004836
4837 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4838 << E->getExprOperand()->getType()
4839 << E->getExprOperand()->getSourceRange();
4840 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004841}
4842
Francois Pichet0066db92012-04-16 04:08:35 +00004843bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4844 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004845}
Francois Pichet0066db92012-04-16 04:08:35 +00004846
Peter Collingbournee9200682011-05-13 03:29:01 +00004847bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004848 // Handle static data members.
4849 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004850 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004851 return VisitVarDecl(E, VD);
4852 }
4853
Richard Smith254a73d2011-10-28 22:34:42 +00004854 // Handle static member functions.
4855 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4856 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004857 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004858 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004859 }
4860 }
4861
Richard Smithd62306a2011-11-10 06:34:14 +00004862 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004863 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004864}
4865
Peter Collingbournee9200682011-05-13 03:29:01 +00004866bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004867 // FIXME: Deal with vectors as array subscript bases.
4868 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004869 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004870
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004871 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004872 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004873
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004874 APSInt Index;
4875 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004876 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004877
Richard Smith861b5b52013-05-07 23:34:45 +00004878 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4879 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004880}
Eli Friedman9a156e52008-11-12 09:44:48 +00004881
Peter Collingbournee9200682011-05-13 03:29:01 +00004882bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004883 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004884}
4885
Richard Smith66c96992012-02-18 22:04:06 +00004886bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4887 if (!Visit(E->getSubExpr()))
4888 return false;
4889 // __real is a no-op on scalar lvalues.
4890 if (E->getSubExpr()->getType()->isAnyComplexType())
4891 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4892 return true;
4893}
4894
4895bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4896 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4897 "lvalue __imag__ on scalar?");
4898 if (!Visit(E->getSubExpr()))
4899 return false;
4900 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4901 return true;
4902}
4903
Richard Smith243ef902013-05-05 23:31:59 +00004904bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004905 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004906 return Error(UO);
4907
4908 if (!this->Visit(UO->getSubExpr()))
4909 return false;
4910
Richard Smith243ef902013-05-05 23:31:59 +00004911 return handleIncDec(
4912 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004913 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004914}
4915
4916bool LValueExprEvaluator::VisitCompoundAssignOperator(
4917 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004918 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004919 return Error(CAO);
4920
Richard Smith3229b742013-05-05 21:17:10 +00004921 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004922
4923 // The overall lvalue result is the result of evaluating the LHS.
4924 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00004925 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004926 Evaluate(RHS, this->Info, CAO->getRHS());
4927 return false;
4928 }
4929
Richard Smith3229b742013-05-05 21:17:10 +00004930 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4931 return false;
4932
Richard Smith43e77732013-05-07 04:50:00 +00004933 return handleCompoundAssignment(
4934 this->Info, CAO,
4935 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4936 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004937}
4938
4939bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004940 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004941 return Error(E);
4942
Richard Smith3229b742013-05-05 21:17:10 +00004943 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004944
4945 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00004946 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004947 Evaluate(NewVal, this->Info, E->getRHS());
4948 return false;
4949 }
4950
Richard Smith3229b742013-05-05 21:17:10 +00004951 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4952 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004953
4954 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004955 NewVal);
4956}
4957
Eli Friedman9a156e52008-11-12 09:44:48 +00004958//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004959// Pointer Evaluation
4960//===----------------------------------------------------------------------===//
4961
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004962namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004963class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004964 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004965 LValue &Result;
4966
Peter Collingbournee9200682011-05-13 03:29:01 +00004967 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004968 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004969 return true;
4970 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004971public:
Mike Stump11289f42009-09-09 15:08:12 +00004972
John McCall45d55e42010-05-07 21:00:08 +00004973 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004974 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004975
Richard Smith2e312c82012-03-03 22:46:17 +00004976 bool Success(const APValue &V, const Expr *E) {
4977 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004978 return true;
4979 }
Richard Smithfddd3842011-12-30 21:15:51 +00004980 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004981 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004982 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004983
John McCall45d55e42010-05-07 21:00:08 +00004984 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004985 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004986 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004987 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004988 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004989 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004990 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004991 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004992 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004993 bool VisitCallExpr(const CallExpr *E);
4994 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004995 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004996 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004997 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004998 }
Richard Smithd62306a2011-11-10 06:34:14 +00004999 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005000 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005001 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005002 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005003 if (!Info.CurrentCall->This) {
5004 if (Info.getLangOpts().CPlusPlus11)
5005 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
5006 else
5007 Info.Diag(E);
5008 return false;
5009 }
Richard Smithd62306a2011-11-10 06:34:14 +00005010 Result = *Info.CurrentCall->This;
5011 return true;
5012 }
John McCallc07a0c72011-02-17 10:25:35 +00005013
Eli Friedman449fe542009-03-23 04:56:01 +00005014 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005015};
Chris Lattner05706e882008-07-11 18:11:29 +00005016} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005017
John McCall45d55e42010-05-07 21:00:08 +00005018static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005019 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005020 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005021}
5022
John McCall45d55e42010-05-07 21:00:08 +00005023bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005024 if (E->getOpcode() != BO_Add &&
5025 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005026 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005027
Chris Lattner05706e882008-07-11 18:11:29 +00005028 const Expr *PExp = E->getLHS();
5029 const Expr *IExp = E->getRHS();
5030 if (IExp->getType()->isPointerType())
5031 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005032
Richard Smith253c2a32012-01-27 01:14:48 +00005033 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005034 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005035 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005036
John McCall45d55e42010-05-07 21:00:08 +00005037 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005038 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005039 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005040
5041 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005042 if (E->getOpcode() == BO_Sub)
5043 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005044
Ted Kremenek28831752012-08-23 20:46:57 +00005045 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005046 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5047 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005048}
Eli Friedman9a156e52008-11-12 09:44:48 +00005049
John McCall45d55e42010-05-07 21:00:08 +00005050bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5051 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005052}
Mike Stump11289f42009-09-09 15:08:12 +00005053
Peter Collingbournee9200682011-05-13 03:29:01 +00005054bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5055 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005056
Eli Friedman847a2bc2009-12-27 05:43:15 +00005057 switch (E->getCastKind()) {
5058 default:
5059 break;
5060
John McCalle3027922010-08-25 11:45:40 +00005061 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005062 case CK_CPointerToObjCPointerCast:
5063 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005064 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005065 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005066 if (!Visit(SubExpr))
5067 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005068 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5069 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5070 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005071 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005072 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005073 if (SubExpr->getType()->isVoidPointerType())
5074 CCEDiag(E, diag::note_constexpr_invalid_cast)
5075 << 3 << SubExpr->getType();
5076 else
5077 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5078 }
Richard Smith96e0c102011-11-04 02:25:55 +00005079 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005080
Anders Carlsson18275092010-10-31 20:41:46 +00005081 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005082 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005083 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005084 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005085 if (!Result.Base && Result.Offset.isZero())
5086 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005087
Richard Smithd62306a2011-11-10 06:34:14 +00005088 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005089 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005090 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5091 castAs<PointerType>()->getPointeeType(),
5092 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005093
Richard Smith027bf112011-11-17 22:56:20 +00005094 case CK_BaseToDerived:
5095 if (!Visit(E->getSubExpr()))
5096 return false;
5097 if (!Result.Base && Result.Offset.isZero())
5098 return true;
5099 return HandleBaseToDerivedCast(Info, E, Result);
5100
Richard Smith0b0a0b62011-10-29 20:57:55 +00005101 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005102 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005103 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005104
John McCalle3027922010-08-25 11:45:40 +00005105 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005106 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5107
Richard Smith2e312c82012-03-03 22:46:17 +00005108 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005109 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005110 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005111
John McCall45d55e42010-05-07 21:00:08 +00005112 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005113 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5114 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005115 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005116 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005117 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005118 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005119 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005120 return true;
5121 } else {
5122 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005123 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005124 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005125 }
5126 }
John McCalle3027922010-08-25 11:45:40 +00005127 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005128 if (SubExpr->isGLValue()) {
5129 if (!EvaluateLValue(SubExpr, Result, Info))
5130 return false;
5131 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005132 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005133 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005134 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005135 return false;
5136 }
Richard Smith96e0c102011-11-04 02:25:55 +00005137 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005138 if (const ConstantArrayType *CAT
5139 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5140 Result.addArray(Info, E, CAT);
5141 else
5142 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005143 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005144
John McCalle3027922010-08-25 11:45:40 +00005145 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005146 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005147 }
5148
Richard Smith11562c52011-10-28 17:51:58 +00005149 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005150}
Chris Lattner05706e882008-07-11 18:11:29 +00005151
Hal Finkel0dd05d42014-10-03 17:18:37 +00005152static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5153 // C++ [expr.alignof]p3:
5154 // When alignof is applied to a reference type, the result is the
5155 // alignment of the referenced type.
5156 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5157 T = Ref->getPointeeType();
5158
5159 // __alignof is defined to return the preferred alignment.
5160 return Info.Ctx.toCharUnitsFromBits(
5161 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5162}
5163
5164static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5165 E = E->IgnoreParens();
5166
5167 // The kinds of expressions that we have special-case logic here for
5168 // should be kept up to date with the special checks for those
5169 // expressions in Sema.
5170
5171 // alignof decl is always accepted, even if it doesn't make sense: we default
5172 // to 1 in those cases.
5173 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5174 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5175 /*RefAsPointee*/true);
5176
5177 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5178 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5179 /*RefAsPointee*/true);
5180
5181 return GetAlignOfType(Info, E->getType());
5182}
5183
Peter Collingbournee9200682011-05-13 03:29:01 +00005184bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005185 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005186 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005187
Alp Tokera724cff2013-12-28 21:59:02 +00005188 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005189 case Builtin::BI__builtin_addressof:
5190 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005191 case Builtin::BI__builtin_assume_aligned: {
5192 // We need to be very careful here because: if the pointer does not have the
5193 // asserted alignment, then the behavior is undefined, and undefined
5194 // behavior is non-constant.
5195 if (!EvaluatePointer(E->getArg(0), Result, Info))
5196 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005197
Hal Finkel0dd05d42014-10-03 17:18:37 +00005198 LValue OffsetResult(Result);
5199 APSInt Alignment;
5200 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5201 return false;
5202 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5203
5204 if (E->getNumArgs() > 2) {
5205 APSInt Offset;
5206 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5207 return false;
5208
5209 int64_t AdditionalOffset = -getExtValue(Offset);
5210 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5211 }
5212
5213 // If there is a base object, then it must have the correct alignment.
5214 if (OffsetResult.Base) {
5215 CharUnits BaseAlignment;
5216 if (const ValueDecl *VD =
5217 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5218 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5219 } else {
5220 BaseAlignment =
5221 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5222 }
5223
5224 if (BaseAlignment < Align) {
5225 Result.Designator.setInvalid();
5226 // FIXME: Quantities here cast to integers because the plural modifier
5227 // does not work on APSInts yet.
5228 CCEDiag(E->getArg(0),
5229 diag::note_constexpr_baa_insufficient_alignment) << 0
5230 << (int) BaseAlignment.getQuantity()
5231 << (unsigned) getExtValue(Alignment);
5232 return false;
5233 }
5234 }
5235
5236 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005237 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005238 Result.Designator.setInvalid();
5239 APSInt Offset(64, false);
5240 Offset = OffsetResult.Offset.getQuantity();
5241
5242 if (OffsetResult.Base)
5243 CCEDiag(E->getArg(0),
5244 diag::note_constexpr_baa_insufficient_alignment) << 1
5245 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5246 else
5247 CCEDiag(E->getArg(0),
5248 diag::note_constexpr_baa_value_insufficient_alignment)
5249 << Offset << (unsigned) getExtValue(Alignment);
5250
5251 return false;
5252 }
5253
5254 return true;
5255 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005256 default:
5257 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5258 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005259}
Chris Lattner05706e882008-07-11 18:11:29 +00005260
5261//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005262// Member Pointer Evaluation
5263//===----------------------------------------------------------------------===//
5264
5265namespace {
5266class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005267 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005268 MemberPtr &Result;
5269
5270 bool Success(const ValueDecl *D) {
5271 Result = MemberPtr(D);
5272 return true;
5273 }
5274public:
5275
5276 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5277 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5278
Richard Smith2e312c82012-03-03 22:46:17 +00005279 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005280 Result.setFrom(V);
5281 return true;
5282 }
Richard Smithfddd3842011-12-30 21:15:51 +00005283 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005284 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005285 }
5286
5287 bool VisitCastExpr(const CastExpr *E);
5288 bool VisitUnaryAddrOf(const UnaryOperator *E);
5289};
5290} // end anonymous namespace
5291
5292static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5293 EvalInfo &Info) {
5294 assert(E->isRValue() && E->getType()->isMemberPointerType());
5295 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5296}
5297
5298bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5299 switch (E->getCastKind()) {
5300 default:
5301 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5302
5303 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005304 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005305 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005306
5307 case CK_BaseToDerivedMemberPointer: {
5308 if (!Visit(E->getSubExpr()))
5309 return false;
5310 if (E->path_empty())
5311 return true;
5312 // Base-to-derived member pointer casts store the path in derived-to-base
5313 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5314 // the wrong end of the derived->base arc, so stagger the path by one class.
5315 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5316 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5317 PathI != PathE; ++PathI) {
5318 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5319 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5320 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005321 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005322 }
5323 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5324 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005325 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005326 return true;
5327 }
5328
5329 case CK_DerivedToBaseMemberPointer:
5330 if (!Visit(E->getSubExpr()))
5331 return false;
5332 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5333 PathE = E->path_end(); PathI != PathE; ++PathI) {
5334 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5335 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5336 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005337 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005338 }
5339 return true;
5340 }
5341}
5342
5343bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5344 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5345 // member can be formed.
5346 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5347}
5348
5349//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005350// Record Evaluation
5351//===----------------------------------------------------------------------===//
5352
5353namespace {
5354 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005355 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005356 const LValue &This;
5357 APValue &Result;
5358 public:
5359
5360 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5361 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5362
Richard Smith2e312c82012-03-03 22:46:17 +00005363 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005364 Result = V;
5365 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005366 }
Richard Smithb8348f52016-05-12 22:16:28 +00005367 bool ZeroInitialization(const Expr *E) {
5368 return ZeroInitialization(E, E->getType());
5369 }
5370 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005371
Richard Smith52a980a2015-08-28 02:43:42 +00005372 bool VisitCallExpr(const CallExpr *E) {
5373 return handleCallExpr(E, Result, &This);
5374 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005375 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005376 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005377 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5378 return VisitCXXConstructExpr(E, E->getType());
5379 }
5380 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005381 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005382 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005383}
Richard Smithd62306a2011-11-10 06:34:14 +00005384
Richard Smithfddd3842011-12-30 21:15:51 +00005385/// Perform zero-initialization on an object of non-union class type.
5386/// C++11 [dcl.init]p5:
5387/// To zero-initialize an object or reference of type T means:
5388/// [...]
5389/// -- if T is a (possibly cv-qualified) non-union class type,
5390/// each non-static data member and each base-class subobject is
5391/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005392static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5393 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005394 const LValue &This, APValue &Result) {
5395 assert(!RD->isUnion() && "Expected non-union class type");
5396 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5397 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005398 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005399
John McCalld7bca762012-05-01 00:38:49 +00005400 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005401 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5402
5403 if (CD) {
5404 unsigned Index = 0;
5405 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005406 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005407 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5408 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005409 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5410 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005411 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005412 Result.getStructBase(Index)))
5413 return false;
5414 }
5415 }
5416
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005417 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005418 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005419 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005420 continue;
5421
5422 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005423 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005424 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005425
David Blaikie2d7c57e2012-04-30 02:36:29 +00005426 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005427 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005428 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005429 return false;
5430 }
5431
5432 return true;
5433}
5434
Richard Smithb8348f52016-05-12 22:16:28 +00005435bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5436 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005437 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005438 if (RD->isUnion()) {
5439 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5440 // object's first non-static named data member is zero-initialized
5441 RecordDecl::field_iterator I = RD->field_begin();
5442 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005443 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005444 return true;
5445 }
5446
5447 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005448 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005449 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005450 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005451 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005452 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005453 }
5454
Richard Smith5d108602012-02-17 00:44:16 +00005455 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005456 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005457 return false;
5458 }
5459
Richard Smitha8105bc2012-01-06 16:39:00 +00005460 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005461}
5462
Richard Smithe97cbd72011-11-11 04:05:33 +00005463bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5464 switch (E->getCastKind()) {
5465 default:
5466 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5467
5468 case CK_ConstructorConversion:
5469 return Visit(E->getSubExpr());
5470
5471 case CK_DerivedToBase:
5472 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005473 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005474 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005475 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005476 if (!DerivedObject.isStruct())
5477 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005478
5479 // Derived-to-base rvalue conversion: just slice off the derived part.
5480 APValue *Value = &DerivedObject;
5481 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5482 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5483 PathE = E->path_end(); PathI != PathE; ++PathI) {
5484 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5485 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5486 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5487 RD = Base;
5488 }
5489 Result = *Value;
5490 return true;
5491 }
5492 }
5493}
5494
Richard Smithd62306a2011-11-10 06:34:14 +00005495bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5496 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005497 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005498 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5499
5500 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005501 const FieldDecl *Field = E->getInitializedFieldInUnion();
5502 Result = APValue(Field);
5503 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005504 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005505
5506 // If the initializer list for a union does not contain any elements, the
5507 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005508 // FIXME: The element should be initialized from an initializer list.
5509 // Is this difference ever observable for initializer lists which
5510 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005511 ImplicitValueInitExpr VIE(Field->getType());
5512 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5513
Richard Smithd62306a2011-11-10 06:34:14 +00005514 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005515 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5516 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005517
5518 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5519 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5520 isa<CXXDefaultInitExpr>(InitExpr));
5521
Richard Smithb228a862012-02-15 02:18:13 +00005522 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005523 }
5524
Richard Smith872307e2016-03-08 22:17:41 +00005525 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005526 if (Result.isUninit())
5527 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5528 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005529 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005530 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005531
5532 // Initialize base classes.
5533 if (CXXRD) {
5534 for (const auto &Base : CXXRD->bases()) {
5535 assert(ElementNo < E->getNumInits() && "missing init for base class");
5536 const Expr *Init = E->getInit(ElementNo);
5537
5538 LValue Subobject = This;
5539 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5540 return false;
5541
5542 APValue &FieldVal = Result.getStructBase(ElementNo);
5543 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00005544 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00005545 return false;
5546 Success = false;
5547 }
5548 ++ElementNo;
5549 }
5550 }
5551
5552 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005553 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005554 // Anonymous bit-fields are not considered members of the class for
5555 // purposes of aggregate initialization.
5556 if (Field->isUnnamedBitfield())
5557 continue;
5558
5559 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005560
Richard Smith253c2a32012-01-27 01:14:48 +00005561 bool HaveInit = ElementNo < E->getNumInits();
5562
5563 // FIXME: Diagnostics here should point to the end of the initializer
5564 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005565 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005566 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005567 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005568
5569 // Perform an implicit value-initialization for members beyond the end of
5570 // the initializer list.
5571 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005572 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005573
Richard Smith852c9db2013-04-20 22:23:05 +00005574 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5575 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5576 isa<CXXDefaultInitExpr>(Init));
5577
Richard Smith49ca8aa2013-08-06 07:09:20 +00005578 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5579 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5580 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005581 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00005582 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005583 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005584 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005585 }
5586 }
5587
Richard Smith253c2a32012-01-27 01:14:48 +00005588 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005589}
5590
Richard Smithb8348f52016-05-12 22:16:28 +00005591bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5592 QualType T) {
5593 // Note that E's type is not necessarily the type of our class here; we might
5594 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005595 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005596 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5597
Richard Smithfddd3842011-12-30 21:15:51 +00005598 bool ZeroInit = E->requiresZeroInitialization();
5599 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005600 // If we've already performed zero-initialization, we're already done.
5601 if (!Result.isUninit())
5602 return true;
5603
Richard Smithda3f4fd2014-03-05 23:32:50 +00005604 // We can get here in two different ways:
5605 // 1) We're performing value-initialization, and should zero-initialize
5606 // the object, or
5607 // 2) We're performing default-initialization of an object with a trivial
5608 // constexpr default constructor, in which case we should start the
5609 // lifetimes of all the base subobjects (there can be no data member
5610 // subobjects in this case) per [basic.life]p1.
5611 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005612 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005613 }
5614
Craig Topper36250ad2014-05-12 05:36:57 +00005615 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005616 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005617
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005618 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005619 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005620
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005621 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005622 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005623 if (const MaterializeTemporaryExpr *ME
5624 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5625 return Visit(ME->GetTemporaryExpr());
5626
Richard Smithb8348f52016-05-12 22:16:28 +00005627 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005628 return false;
5629
Craig Topper5fc8fc22014-08-27 06:28:36 +00005630 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005631 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005632 cast<CXXConstructorDecl>(Definition), Info,
5633 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005634}
5635
Richard Smithcc1b96d2013-06-12 22:31:48 +00005636bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5637 const CXXStdInitializerListExpr *E) {
5638 const ConstantArrayType *ArrayType =
5639 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5640
5641 LValue Array;
5642 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5643 return false;
5644
5645 // Get a pointer to the first element of the array.
5646 Array.addArray(Info, E, ArrayType);
5647
5648 // FIXME: Perform the checks on the field types in SemaInit.
5649 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5650 RecordDecl::field_iterator Field = Record->field_begin();
5651 if (Field == Record->field_end())
5652 return Error(E);
5653
5654 // Start pointer.
5655 if (!Field->getType()->isPointerType() ||
5656 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5657 ArrayType->getElementType()))
5658 return Error(E);
5659
5660 // FIXME: What if the initializer_list type has base classes, etc?
5661 Result = APValue(APValue::UninitStruct(), 0, 2);
5662 Array.moveInto(Result.getStructField(0));
5663
5664 if (++Field == Record->field_end())
5665 return Error(E);
5666
5667 if (Field->getType()->isPointerType() &&
5668 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5669 ArrayType->getElementType())) {
5670 // End pointer.
5671 if (!HandleLValueArrayAdjustment(Info, E, Array,
5672 ArrayType->getElementType(),
5673 ArrayType->getSize().getZExtValue()))
5674 return false;
5675 Array.moveInto(Result.getStructField(1));
5676 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5677 // Length.
5678 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5679 else
5680 return Error(E);
5681
5682 if (++Field != Record->field_end())
5683 return Error(E);
5684
5685 return true;
5686}
5687
Richard Smithd62306a2011-11-10 06:34:14 +00005688static bool EvaluateRecord(const Expr *E, const LValue &This,
5689 APValue &Result, EvalInfo &Info) {
5690 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005691 "can't evaluate expression as a record rvalue");
5692 return RecordExprEvaluator(Info, This, Result).Visit(E);
5693}
5694
5695//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005696// Temporary Evaluation
5697//
5698// Temporaries are represented in the AST as rvalues, but generally behave like
5699// lvalues. The full-object of which the temporary is a subobject is implicitly
5700// materialized so that a reference can bind to it.
5701//===----------------------------------------------------------------------===//
5702namespace {
5703class TemporaryExprEvaluator
5704 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5705public:
5706 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5707 LValueExprEvaluatorBaseTy(Info, Result) {}
5708
5709 /// Visit an expression which constructs the value of this temporary.
5710 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005711 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005712 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5713 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005714 }
5715
5716 bool VisitCastExpr(const CastExpr *E) {
5717 switch (E->getCastKind()) {
5718 default:
5719 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5720
5721 case CK_ConstructorConversion:
5722 return VisitConstructExpr(E->getSubExpr());
5723 }
5724 }
5725 bool VisitInitListExpr(const InitListExpr *E) {
5726 return VisitConstructExpr(E);
5727 }
5728 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5729 return VisitConstructExpr(E);
5730 }
5731 bool VisitCallExpr(const CallExpr *E) {
5732 return VisitConstructExpr(E);
5733 }
Richard Smith513955c2014-12-17 19:24:30 +00005734 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5735 return VisitConstructExpr(E);
5736 }
Richard Smith027bf112011-11-17 22:56:20 +00005737};
5738} // end anonymous namespace
5739
5740/// Evaluate an expression of record type as a temporary.
5741static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005742 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005743 return TemporaryExprEvaluator(Info, Result).Visit(E);
5744}
5745
5746//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005747// Vector Evaluation
5748//===----------------------------------------------------------------------===//
5749
5750namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005751 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005752 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005753 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005754 public:
Mike Stump11289f42009-09-09 15:08:12 +00005755
Richard Smith2d406342011-10-22 21:10:00 +00005756 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5757 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005758
Craig Topper9798b932015-09-29 04:30:05 +00005759 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005760 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5761 // FIXME: remove this APValue copy.
5762 Result = APValue(V.data(), V.size());
5763 return true;
5764 }
Richard Smith2e312c82012-03-03 22:46:17 +00005765 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005766 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005767 Result = V;
5768 return true;
5769 }
Richard Smithfddd3842011-12-30 21:15:51 +00005770 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005771
Richard Smith2d406342011-10-22 21:10:00 +00005772 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005773 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005774 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005775 bool VisitInitListExpr(const InitListExpr *E);
5776 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005777 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005778 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005779 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005780 };
5781} // end anonymous namespace
5782
5783static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005784 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005785 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005786}
5787
George Burgess IV533ff002015-12-11 00:23:35 +00005788bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005789 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005790 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005791
Richard Smith161f09a2011-12-06 22:44:34 +00005792 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005793 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005794
Eli Friedmanc757de22011-03-25 00:43:55 +00005795 switch (E->getCastKind()) {
5796 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005797 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005798 if (SETy->isIntegerType()) {
5799 APSInt IntResult;
5800 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00005801 return false;
5802 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005803 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00005804 APFloat FloatResult(0.0);
5805 if (!EvaluateFloat(SE, FloatResult, Info))
5806 return false;
5807 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005808 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005809 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005810 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005811
5812 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005813 SmallVector<APValue, 4> Elts(NElts, Val);
5814 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005815 }
Eli Friedman803acb32011-12-22 03:51:45 +00005816 case CK_BitCast: {
5817 // Evaluate the operand into an APInt we can extract from.
5818 llvm::APInt SValInt;
5819 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5820 return false;
5821 // Extract the elements
5822 QualType EltTy = VTy->getElementType();
5823 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5824 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5825 SmallVector<APValue, 4> Elts;
5826 if (EltTy->isRealFloatingType()) {
5827 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005828 unsigned FloatEltSize = EltSize;
5829 if (&Sem == &APFloat::x87DoubleExtended)
5830 FloatEltSize = 80;
5831 for (unsigned i = 0; i < NElts; i++) {
5832 llvm::APInt Elt;
5833 if (BigEndian)
5834 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5835 else
5836 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005837 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005838 }
5839 } else if (EltTy->isIntegerType()) {
5840 for (unsigned i = 0; i < NElts; i++) {
5841 llvm::APInt Elt;
5842 if (BigEndian)
5843 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5844 else
5845 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5846 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5847 }
5848 } else {
5849 return Error(E);
5850 }
5851 return Success(Elts, E);
5852 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005853 default:
Richard Smith11562c52011-10-28 17:51:58 +00005854 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005855 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005856}
5857
Richard Smith2d406342011-10-22 21:10:00 +00005858bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005859VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005860 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005861 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005862 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005863
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005864 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005865 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005866
Eli Friedmanb9c71292012-01-03 23:24:20 +00005867 // The number of initializers can be less than the number of
5868 // vector elements. For OpenCL, this can be due to nested vector
5869 // initialization. For GCC compatibility, missing trailing elements
5870 // should be initialized with zeroes.
5871 unsigned CountInits = 0, CountElts = 0;
5872 while (CountElts < NumElements) {
5873 // Handle nested vector initialization.
5874 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005875 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005876 APValue v;
5877 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5878 return Error(E);
5879 unsigned vlen = v.getVectorLength();
5880 for (unsigned j = 0; j < vlen; j++)
5881 Elements.push_back(v.getVectorElt(j));
5882 CountElts += vlen;
5883 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005884 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005885 if (CountInits < NumInits) {
5886 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005887 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005888 } else // trailing integer zero.
5889 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5890 Elements.push_back(APValue(sInt));
5891 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005892 } else {
5893 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005894 if (CountInits < NumInits) {
5895 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005896 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005897 } else // trailing float zero.
5898 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5899 Elements.push_back(APValue(f));
5900 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005901 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005902 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005903 }
Richard Smith2d406342011-10-22 21:10:00 +00005904 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005905}
5906
Richard Smith2d406342011-10-22 21:10:00 +00005907bool
Richard Smithfddd3842011-12-30 21:15:51 +00005908VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005909 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005910 QualType EltTy = VT->getElementType();
5911 APValue ZeroElement;
5912 if (EltTy->isIntegerType())
5913 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5914 else
5915 ZeroElement =
5916 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5917
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005918 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005919 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005920}
5921
Richard Smith2d406342011-10-22 21:10:00 +00005922bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005923 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005924 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005925}
5926
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005927//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005928// Array Evaluation
5929//===----------------------------------------------------------------------===//
5930
5931namespace {
5932 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005933 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005934 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005935 APValue &Result;
5936 public:
5937
Richard Smithd62306a2011-11-10 06:34:14 +00005938 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5939 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005940
5941 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005942 assert((V.isArray() || V.isLValue()) &&
5943 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005944 Result = V;
5945 return true;
5946 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005947
Richard Smithfddd3842011-12-30 21:15:51 +00005948 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005949 const ConstantArrayType *CAT =
5950 Info.Ctx.getAsConstantArrayType(E->getType());
5951 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005952 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005953
5954 Result = APValue(APValue::UninitArray(), 0,
5955 CAT->getSize().getZExtValue());
5956 if (!Result.hasArrayFiller()) return true;
5957
Richard Smithfddd3842011-12-30 21:15:51 +00005958 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005959 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005960 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005961 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005962 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005963 }
5964
Richard Smith52a980a2015-08-28 02:43:42 +00005965 bool VisitCallExpr(const CallExpr *E) {
5966 return handleCallExpr(E, Result, &This);
5967 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005968 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005969 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005970 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5971 const LValue &Subobject,
5972 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005973 };
5974} // end anonymous namespace
5975
Richard Smithd62306a2011-11-10 06:34:14 +00005976static bool EvaluateArray(const Expr *E, const LValue &This,
5977 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005978 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005979 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005980}
5981
5982bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5983 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5984 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005985 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005986
Richard Smithca2cfbf2011-12-22 01:07:19 +00005987 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5988 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005989 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005990 LValue LV;
5991 if (!EvaluateLValue(E->getInit(0), LV, Info))
5992 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005993 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005994 LV.moveInto(Val);
5995 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005996 }
5997
Richard Smith253c2a32012-01-27 01:14:48 +00005998 bool Success = true;
5999
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006000 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6001 "zero-initialized array shouldn't have any initialized elts");
6002 APValue Filler;
6003 if (Result.isArray() && Result.hasArrayFiller())
6004 Filler = Result.getArrayFiller();
6005
Richard Smith9543c5e2013-04-22 14:44:29 +00006006 unsigned NumEltsToInit = E->getNumInits();
6007 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006008 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006009
6010 // If the initializer might depend on the array index, run it for each
6011 // array element. For now, just whitelist non-class value-initialization.
6012 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6013 NumEltsToInit = NumElts;
6014
6015 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006016
6017 // If the array was previously zero-initialized, preserve the
6018 // zero-initialized values.
6019 if (!Filler.isUninit()) {
6020 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6021 Result.getArrayInitializedElt(I) = Filler;
6022 if (Result.hasArrayFiller())
6023 Result.getArrayFiller() = Filler;
6024 }
6025
Richard Smithd62306a2011-11-10 06:34:14 +00006026 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006027 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006028 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6029 const Expr *Init =
6030 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006031 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006032 Info, Subobject, Init) ||
6033 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006034 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006035 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006036 return false;
6037 Success = false;
6038 }
Richard Smithd62306a2011-11-10 06:34:14 +00006039 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006040
Richard Smith9543c5e2013-04-22 14:44:29 +00006041 if (!Result.hasArrayFiller())
6042 return Success;
6043
6044 // If we get here, we have a trivial filler, which we can just evaluate
6045 // once and splat over the rest of the array elements.
6046 assert(FillerExpr && "no array filler for incomplete init list");
6047 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6048 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006049}
6050
Richard Smith027bf112011-11-17 22:56:20 +00006051bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006052 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6053}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006054
Richard Smith9543c5e2013-04-22 14:44:29 +00006055bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6056 const LValue &Subobject,
6057 APValue *Value,
6058 QualType Type) {
6059 bool HadZeroInit = !Value->isUninit();
6060
6061 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6062 unsigned N = CAT->getSize().getZExtValue();
6063
6064 // Preserve the array filler if we had prior zero-initialization.
6065 APValue Filler =
6066 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6067 : APValue();
6068
6069 *Value = APValue(APValue::UninitArray(), N, N);
6070
6071 if (HadZeroInit)
6072 for (unsigned I = 0; I != N; ++I)
6073 Value->getArrayInitializedElt(I) = Filler;
6074
6075 // Initialize the elements.
6076 LValue ArrayElt = Subobject;
6077 ArrayElt.addArray(Info, E, CAT);
6078 for (unsigned I = 0; I != N; ++I)
6079 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6080 CAT->getElementType()) ||
6081 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6082 CAT->getElementType(), 1))
6083 return false;
6084
6085 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006086 }
Richard Smith027bf112011-11-17 22:56:20 +00006087
Richard Smith9543c5e2013-04-22 14:44:29 +00006088 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006089 return Error(E);
6090
Richard Smithb8348f52016-05-12 22:16:28 +00006091 return RecordExprEvaluator(Info, Subobject, *Value)
6092 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006093}
6094
Richard Smithf3e9e432011-11-07 09:22:26 +00006095//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006096// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006097//
6098// As a GNU extension, we support casting pointers to sufficiently-wide integer
6099// types and back in constant folding. Integer values are thus represented
6100// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006101//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006102
6103namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006104class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006105 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006106 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006107public:
Richard Smith2e312c82012-03-03 22:46:17 +00006108 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006109 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006110
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006111 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006112 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006113 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006114 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006115 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006116 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006117 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006118 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006119 return true;
6120 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006121 bool Success(const llvm::APSInt &SI, const Expr *E) {
6122 return Success(SI, E, Result);
6123 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006124
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006125 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006126 assert(E->getType()->isIntegralOrEnumerationType() &&
6127 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006128 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006129 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006130 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006131 Result.getInt().setIsUnsigned(
6132 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006133 return true;
6134 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006135 bool Success(const llvm::APInt &I, const Expr *E) {
6136 return Success(I, E, Result);
6137 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006138
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006139 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006140 assert(E->getType()->isIntegralOrEnumerationType() &&
6141 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006142 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006143 return true;
6144 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006145 bool Success(uint64_t Value, const Expr *E) {
6146 return Success(Value, E, Result);
6147 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006148
Ken Dyckdbc01912011-03-11 02:13:43 +00006149 bool Success(CharUnits Size, const Expr *E) {
6150 return Success(Size.getQuantity(), E);
6151 }
6152
Richard Smith2e312c82012-03-03 22:46:17 +00006153 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006154 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006155 Result = V;
6156 return true;
6157 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006158 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006159 }
Mike Stump11289f42009-09-09 15:08:12 +00006160
Richard Smithfddd3842011-12-30 21:15:51 +00006161 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006162
Peter Collingbournee9200682011-05-13 03:29:01 +00006163 //===--------------------------------------------------------------------===//
6164 // Visitor Methods
6165 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006166
Chris Lattner7174bf32008-07-12 00:38:25 +00006167 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006168 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006169 }
6170 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006171 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006172 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006173
6174 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6175 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006176 if (CheckReferencedDecl(E, E->getDecl()))
6177 return true;
6178
6179 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006180 }
6181 bool VisitMemberExpr(const MemberExpr *E) {
6182 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006183 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006184 return true;
6185 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006186
6187 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006188 }
6189
Peter Collingbournee9200682011-05-13 03:29:01 +00006190 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006191 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006192 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006193 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006194
Peter Collingbournee9200682011-05-13 03:29:01 +00006195 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006196 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006197
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006198 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006199 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006200 }
Mike Stump11289f42009-09-09 15:08:12 +00006201
Ted Kremeneke65b0862012-03-06 20:05:56 +00006202 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6203 return Success(E->getValue(), E);
6204 }
6205
Richard Smith4ce706a2011-10-11 21:43:33 +00006206 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006207 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006208 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006209 }
6210
Douglas Gregor29c42f22012-02-24 07:38:34 +00006211 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6212 return Success(E->getValue(), E);
6213 }
6214
John Wiegley6242b6a2011-04-28 00:16:57 +00006215 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6216 return Success(E->getValue(), E);
6217 }
6218
John Wiegleyf9f65842011-04-25 06:54:41 +00006219 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6220 return Success(E->getValue(), E);
6221 }
6222
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006223 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006224 bool VisitUnaryImag(const UnaryOperator *E);
6225
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006226 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006227 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006228
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006229private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006230 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006231 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006232};
Chris Lattner05706e882008-07-11 18:11:29 +00006233} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006234
Richard Smith11562c52011-10-28 17:51:58 +00006235/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6236/// produce either the integer value or a pointer.
6237///
6238/// GCC has a heinous extension which folds casts between pointer types and
6239/// pointer-sized integral types. We support this by allowing the evaluation of
6240/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6241/// Some simple arithmetic on such values is supported (they are treated much
6242/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006243static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006244 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006245 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006246 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006247}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006248
Richard Smithf57d8cb2011-12-09 22:58:01 +00006249static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006250 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006251 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006252 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006253 if (!Val.isInt()) {
6254 // FIXME: It would be better to produce the diagnostic for casting
6255 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006256 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006257 return false;
6258 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006259 Result = Val.getInt();
6260 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006261}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006262
Richard Smithf57d8cb2011-12-09 22:58:01 +00006263/// Check whether the given declaration can be directly converted to an integral
6264/// rvalue. If not, no diagnostic is produced; there are other things we can
6265/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006266bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006267 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006268 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006269 // Check for signedness/width mismatches between E type and ECD value.
6270 bool SameSign = (ECD->getInitVal().isSigned()
6271 == E->getType()->isSignedIntegerOrEnumerationType());
6272 bool SameWidth = (ECD->getInitVal().getBitWidth()
6273 == Info.Ctx.getIntWidth(E->getType()));
6274 if (SameSign && SameWidth)
6275 return Success(ECD->getInitVal(), E);
6276 else {
6277 // Get rid of mismatch (otherwise Success assertions will fail)
6278 // by computing a new value matching the type of E.
6279 llvm::APSInt Val = ECD->getInitVal();
6280 if (!SameSign)
6281 Val.setIsSigned(!ECD->getInitVal().isSigned());
6282 if (!SameWidth)
6283 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6284 return Success(Val, E);
6285 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006286 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006287 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006288}
6289
Chris Lattner86ee2862008-10-06 06:40:35 +00006290/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6291/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006292static int EvaluateBuiltinClassifyType(const CallExpr *E,
6293 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006294 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006295 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006296 enum gcc_type_class {
6297 no_type_class = -1,
6298 void_type_class, integer_type_class, char_type_class,
6299 enumeral_type_class, boolean_type_class,
6300 pointer_type_class, reference_type_class, offset_type_class,
6301 real_type_class, complex_type_class,
6302 function_type_class, method_type_class,
6303 record_type_class, union_type_class,
6304 array_type_class, string_type_class,
6305 lang_type_class
6306 };
Mike Stump11289f42009-09-09 15:08:12 +00006307
6308 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006309 // ideal, however it is what gcc does.
6310 if (E->getNumArgs() == 0)
6311 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006312
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006313 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6314 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6315
6316 switch (CanTy->getTypeClass()) {
6317#define TYPE(ID, BASE)
6318#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6319#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6320#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6321#include "clang/AST/TypeNodes.def"
6322 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6323
6324 case Type::Builtin:
6325 switch (BT->getKind()) {
6326#define BUILTIN_TYPE(ID, SINGLETON_ID)
6327#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6328#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6329#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6330#include "clang/AST/BuiltinTypes.def"
6331 case BuiltinType::Void:
6332 return void_type_class;
6333
6334 case BuiltinType::Bool:
6335 return boolean_type_class;
6336
6337 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6338 case BuiltinType::UChar:
6339 case BuiltinType::UShort:
6340 case BuiltinType::UInt:
6341 case BuiltinType::ULong:
6342 case BuiltinType::ULongLong:
6343 case BuiltinType::UInt128:
6344 return integer_type_class;
6345
6346 case BuiltinType::NullPtr:
6347 return pointer_type_class;
6348
6349 case BuiltinType::WChar_U:
6350 case BuiltinType::Char16:
6351 case BuiltinType::Char32:
6352 case BuiltinType::ObjCId:
6353 case BuiltinType::ObjCClass:
6354 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006355#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6356 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006357#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006358 case BuiltinType::OCLSampler:
6359 case BuiltinType::OCLEvent:
6360 case BuiltinType::OCLClkEvent:
6361 case BuiltinType::OCLQueue:
6362 case BuiltinType::OCLNDRange:
6363 case BuiltinType::OCLReserveID:
6364 case BuiltinType::Dependent:
6365 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6366 };
6367
6368 case Type::Enum:
6369 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6370 break;
6371
6372 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006373 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006374 break;
6375
6376 case Type::MemberPointer:
6377 if (CanTy->isMemberDataPointerType())
6378 return offset_type_class;
6379 else {
6380 // We expect member pointers to be either data or function pointers,
6381 // nothing else.
6382 assert(CanTy->isMemberFunctionPointerType());
6383 return method_type_class;
6384 }
6385
6386 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006387 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006388
6389 case Type::FunctionNoProto:
6390 case Type::FunctionProto:
6391 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6392
6393 case Type::Record:
6394 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6395 switch (RT->getDecl()->getTagKind()) {
6396 case TagTypeKind::TTK_Struct:
6397 case TagTypeKind::TTK_Class:
6398 case TagTypeKind::TTK_Interface:
6399 return record_type_class;
6400
6401 case TagTypeKind::TTK_Enum:
6402 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6403
6404 case TagTypeKind::TTK_Union:
6405 return union_type_class;
6406 }
6407 }
David Blaikie83d382b2011-09-23 05:06:16 +00006408 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006409
6410 case Type::ConstantArray:
6411 case Type::VariableArray:
6412 case Type::IncompleteArray:
6413 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6414
6415 case Type::BlockPointer:
6416 case Type::LValueReference:
6417 case Type::RValueReference:
6418 case Type::Vector:
6419 case Type::ExtVector:
6420 case Type::Auto:
6421 case Type::ObjCObject:
6422 case Type::ObjCInterface:
6423 case Type::ObjCObjectPointer:
6424 case Type::Pipe:
6425 case Type::Atomic:
6426 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6427 }
6428
6429 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006430}
6431
Richard Smith5fab0c92011-12-28 19:48:30 +00006432/// EvaluateBuiltinConstantPForLValue - Determine the result of
6433/// __builtin_constant_p when applied to the given lvalue.
6434///
6435/// An lvalue is only "constant" if it is a pointer or reference to the first
6436/// character of a string literal.
6437template<typename LValue>
6438static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006439 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006440 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6441}
6442
6443/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6444/// GCC as we can manage.
6445static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6446 QualType ArgType = Arg->getType();
6447
6448 // __builtin_constant_p always has one operand. The rules which gcc follows
6449 // are not precisely documented, but are as follows:
6450 //
6451 // - If the operand is of integral, floating, complex or enumeration type,
6452 // and can be folded to a known value of that type, it returns 1.
6453 // - If the operand and can be folded to a pointer to the first character
6454 // of a string literal (or such a pointer cast to an integral type), it
6455 // returns 1.
6456 //
6457 // Otherwise, it returns 0.
6458 //
6459 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6460 // its support for this does not currently work.
6461 if (ArgType->isIntegralOrEnumerationType()) {
6462 Expr::EvalResult Result;
6463 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6464 return false;
6465
6466 APValue &V = Result.Val;
6467 if (V.getKind() == APValue::Int)
6468 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006469 if (V.getKind() == APValue::LValue)
6470 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006471 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6472 return Arg->isEvaluatable(Ctx);
6473 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6474 LValue LV;
6475 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006476 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006477 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6478 : EvaluatePointer(Arg, LV, Info)) &&
6479 !Status.HasSideEffects)
6480 return EvaluateBuiltinConstantPForLValue(LV);
6481 }
6482
6483 // Anything else isn't considered to be sufficiently constant.
6484 return false;
6485}
6486
John McCall95007602010-05-10 23:27:23 +00006487/// Retrieves the "underlying object type" of the given expression,
6488/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006489static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006490 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6491 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006492 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006493 } else if (const Expr *E = B.get<const Expr*>()) {
6494 if (isa<CompoundLiteralExpr>(E))
6495 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006496 }
6497
6498 return QualType();
6499}
6500
George Burgess IV3a03fab2015-09-04 21:28:13 +00006501/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006502/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6503/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006504/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6505///
6506/// Always returns an RValue with a pointer representation.
6507static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6508 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6509
6510 auto *NoParens = E->IgnoreParens();
6511 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006512 if (Cast == nullptr)
6513 return NoParens;
6514
6515 // We only conservatively allow a few kinds of casts, because this code is
6516 // inherently a simple solution that seeks to support the common case.
6517 auto CastKind = Cast->getCastKind();
6518 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6519 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006520 return NoParens;
6521
6522 auto *SubExpr = Cast->getSubExpr();
6523 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6524 return NoParens;
6525 return ignorePointerCastsAndParens(SubExpr);
6526}
6527
George Burgess IVa51c4072015-10-16 01:49:01 +00006528/// Checks to see if the given LValue's Designator is at the end of the LValue's
6529/// record layout. e.g.
6530/// struct { struct { int a, b; } fst, snd; } obj;
6531/// obj.fst // no
6532/// obj.snd // yes
6533/// obj.fst.a // no
6534/// obj.fst.b // no
6535/// obj.snd.a // no
6536/// obj.snd.b // yes
6537///
6538/// Please note: this function is specialized for how __builtin_object_size
6539/// views "objects".
6540static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6541 assert(!LVal.Designator.Invalid);
6542
6543 auto IsLastFieldDecl = [&Ctx](const FieldDecl *FD) {
6544 if (FD->getParent()->isUnion())
6545 return true;
6546 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
6547 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6548 };
6549
6550 auto &Base = LVal.getLValueBase();
6551 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6552 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
6553 if (!IsLastFieldDecl(FD))
6554 return false;
6555 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
6556 for (auto *FD : IFD->chain())
6557 if (!IsLastFieldDecl(cast<FieldDecl>(FD)))
6558 return false;
6559 }
6560 }
6561
6562 QualType BaseType = getType(Base);
6563 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6564 if (BaseType->isArrayType()) {
6565 // Because __builtin_object_size treats arrays as objects, we can ignore
6566 // the index iff this is the last array in the Designator.
6567 if (I + 1 == E)
6568 return true;
6569 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6570 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6571 if (Index + 1 != CAT->getSize())
6572 return false;
6573 BaseType = CAT->getElementType();
6574 } else if (BaseType->isAnyComplexType()) {
6575 auto *CT = BaseType->castAs<ComplexType>();
6576 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6577 if (Index != 1)
6578 return false;
6579 BaseType = CT->getElementType();
6580 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
6581 if (!IsLastFieldDecl(FD))
6582 return false;
6583 BaseType = FD->getType();
6584 } else {
6585 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6586 "Expecting cast to a base class");
6587 return false;
6588 }
6589 }
6590 return true;
6591}
6592
6593/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6594static bool refersToCompleteObject(const LValue &LVal) {
6595 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6596 return false;
6597
6598 if (!LVal.InvalidBase)
6599 return true;
6600
6601 auto *E = LVal.Base.dyn_cast<const Expr *>();
6602 (void)E;
6603 assert(E != nullptr && isa<MemberExpr>(E));
6604 return false;
6605}
6606
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006607/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6608/// true and stores the result in @p Size.
6609///
6610/// If @p WasError is non-null, this will report whether the failure to evaluate
6611/// is to be treated as an Error in IntExprEvaluator.
6612static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6613 EvalInfo &Info, uint64_t &Size,
6614 bool *WasError = nullptr) {
6615 if (WasError != nullptr)
6616 *WasError = false;
6617
6618 auto Error = [&](const Expr *E) {
6619 if (WasError != nullptr)
6620 *WasError = true;
6621 return false;
6622 };
6623
6624 auto Success = [&](uint64_t S, const Expr *E) {
6625 Size = S;
6626 return true;
6627 };
6628
George Burgess IVbdb5b262015-08-19 02:19:07 +00006629 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006630 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006631 {
6632 // The operand of __builtin_object_size is never evaluated for side-effects.
6633 // If there are any, but we can determine the pointed-to object anyway, then
6634 // ignore the side-effects.
6635 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006636 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006637
6638 if (E->isGLValue()) {
6639 // It's possible for us to be given GLValues if we're called via
6640 // Expr::tryEvaluateObjectSize.
6641 APValue RVal;
6642 if (!EvaluateAsRValue(Info, E, RVal))
6643 return false;
6644 Base.setFrom(Info.Ctx, RVal);
6645 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006646 return false;
6647 }
John McCall95007602010-05-10 23:27:23 +00006648
George Burgess IVbdb5b262015-08-19 02:19:07 +00006649 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006650 // If we point to before the start of the object, there are no accessible
6651 // bytes.
6652 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006653 return Success(0, E);
6654
George Burgess IV3a03fab2015-09-04 21:28:13 +00006655 // In the case where we're not dealing with a subobject, we discard the
6656 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006657 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006658
6659 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6660 // exist. If we can't verify the base, then we can't do that.
6661 //
6662 // As a special case, we produce a valid object size for an unknown object
6663 // with a known designator if Type & 1 is 1. For instance:
6664 //
6665 // extern struct X { char buff[32]; int a, b, c; } *p;
6666 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6667 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6668 //
6669 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006670 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006671 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006672
George Burgess IVa51c4072015-10-16 01:49:01 +00006673 // If we're not examining only the subobject, then we reset to a complete
6674 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006675 //
6676 // If Type is 1 and we've lost track of the subobject, just find the complete
6677 // object instead. (If Type is 3, that's not correct behavior and we should
6678 // return 0 instead.)
6679 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006680 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006681 QualType T = getObjectType(End.getLValueBase());
6682 if (T.isNull())
6683 End.Designator.setInvalid();
6684 else {
6685 End.Designator = SubobjectDesignator(T);
6686 End.Offset = CharUnits::Zero();
6687 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006688 }
John McCall95007602010-05-10 23:27:23 +00006689
George Burgess IVbdb5b262015-08-19 02:19:07 +00006690 // If it is not possible to determine which objects ptr points to at compile
6691 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6692 // and (size_t) 0 for type 2 or 3.
6693 if (End.Designator.Invalid)
6694 return false;
6695
6696 // According to the GCC documentation, we want the size of the subobject
6697 // denoted by the pointer. But that's not quite right -- what we actually
6698 // want is the size of the immediately-enclosing array, if there is one.
6699 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006700 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006701 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6702 // We got a pointer to an array. Step to its end.
6703 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006704 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006705 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006706 // We're already pointing at the end of the object.
6707 AmountToAdd = 0;
6708 }
6709
George Burgess IV3a03fab2015-09-04 21:28:13 +00006710 QualType PointeeType = End.Designator.MostDerivedType;
6711 assert(!PointeeType.isNull());
6712 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006713 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006714
George Burgess IVbdb5b262015-08-19 02:19:07 +00006715 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6716 AmountToAdd))
6717 return false;
John McCall95007602010-05-10 23:27:23 +00006718
George Burgess IVbdb5b262015-08-19 02:19:07 +00006719 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006720
6721 // The following is a moderately common idiom in C:
6722 //
6723 // struct Foo { int a; char c[1]; };
6724 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6725 // strcpy(&F->c[0], Bar);
6726 //
6727 // So, if we see that we're examining a 1-length (or 0-length) array at the
6728 // end of a struct with an unknown base, we give up instead of breaking code
6729 // that behaves this way. Note that we only do this when Type=1, because
6730 // Type=3 is a lower bound, so answering conservatively is fine.
6731 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6732 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6733 End.Designator.MostDerivedIsArrayElement &&
6734 End.Designator.MostDerivedArraySize < 2 &&
6735 isDesignatorAtObjectEnd(Info.Ctx, End))
6736 return false;
6737
George Burgess IVbdb5b262015-08-19 02:19:07 +00006738 if (BaseOffset > EndOffset)
6739 return Success(0, E);
6740
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006741 return Success((EndOffset - BaseOffset).getQuantity(), E);
6742}
6743
6744bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6745 unsigned Type) {
6746 uint64_t Size;
6747 bool WasError;
6748 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6749 return Success(Size, E);
6750 if (WasError)
6751 return Error(E);
6752 return false;
John McCall95007602010-05-10 23:27:23 +00006753}
6754
Peter Collingbournee9200682011-05-13 03:29:01 +00006755bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006756 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006757 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006758 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006759
6760 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006761 // The type was checked when we built the expression.
6762 unsigned Type =
6763 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6764 assert(Type <= 3 && "unexpected type");
6765
6766 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006767 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006768
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006769 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006770 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006771
Richard Smith01ade172012-05-23 04:13:20 +00006772 // Expression had no side effects, but we couldn't statically determine the
6773 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006774 switch (Info.EvalMode) {
6775 case EvalInfo::EM_ConstantExpression:
6776 case EvalInfo::EM_PotentialConstantExpression:
6777 case EvalInfo::EM_ConstantFold:
6778 case EvalInfo::EM_EvaluateForOverflow:
6779 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006780 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006781 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006782 return Error(E);
6783 case EvalInfo::EM_ConstantExpressionUnevaluated:
6784 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006785 // Reduce it to a constant now.
6786 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006787 }
Mike Stump722cedf2009-10-26 18:35:08 +00006788 }
6789
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006790 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006791 case Builtin::BI__builtin_bswap32:
6792 case Builtin::BI__builtin_bswap64: {
6793 APSInt Val;
6794 if (!EvaluateInteger(E->getArg(0), Val, Info))
6795 return false;
6796
6797 return Success(Val.byteSwap(), E);
6798 }
6799
Richard Smith8889a3d2013-06-13 06:26:32 +00006800 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006801 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00006802
6803 // FIXME: BI__builtin_clrsb
6804 // FIXME: BI__builtin_clrsbl
6805 // FIXME: BI__builtin_clrsbll
6806
Richard Smith80b3c8e2013-06-13 05:04:16 +00006807 case Builtin::BI__builtin_clz:
6808 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006809 case Builtin::BI__builtin_clzll:
6810 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006811 APSInt Val;
6812 if (!EvaluateInteger(E->getArg(0), Val, Info))
6813 return false;
6814 if (!Val)
6815 return Error(E);
6816
6817 return Success(Val.countLeadingZeros(), E);
6818 }
6819
Richard Smith8889a3d2013-06-13 06:26:32 +00006820 case Builtin::BI__builtin_constant_p:
6821 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6822
Richard Smith80b3c8e2013-06-13 05:04:16 +00006823 case Builtin::BI__builtin_ctz:
6824 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006825 case Builtin::BI__builtin_ctzll:
6826 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006827 APSInt Val;
6828 if (!EvaluateInteger(E->getArg(0), Val, Info))
6829 return false;
6830 if (!Val)
6831 return Error(E);
6832
6833 return Success(Val.countTrailingZeros(), E);
6834 }
6835
Richard Smith8889a3d2013-06-13 06:26:32 +00006836 case Builtin::BI__builtin_eh_return_data_regno: {
6837 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6838 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6839 return Success(Operand, E);
6840 }
6841
6842 case Builtin::BI__builtin_expect:
6843 return Visit(E->getArg(0));
6844
6845 case Builtin::BI__builtin_ffs:
6846 case Builtin::BI__builtin_ffsl:
6847 case Builtin::BI__builtin_ffsll: {
6848 APSInt Val;
6849 if (!EvaluateInteger(E->getArg(0), Val, Info))
6850 return false;
6851
6852 unsigned N = Val.countTrailingZeros();
6853 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6854 }
6855
6856 case Builtin::BI__builtin_fpclassify: {
6857 APFloat Val(0.0);
6858 if (!EvaluateFloat(E->getArg(5), Val, Info))
6859 return false;
6860 unsigned Arg;
6861 switch (Val.getCategory()) {
6862 case APFloat::fcNaN: Arg = 0; break;
6863 case APFloat::fcInfinity: Arg = 1; break;
6864 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6865 case APFloat::fcZero: Arg = 4; break;
6866 }
6867 return Visit(E->getArg(Arg));
6868 }
6869
6870 case Builtin::BI__builtin_isinf_sign: {
6871 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006872 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006873 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6874 }
6875
Richard Smithea3019d2013-10-15 19:07:14 +00006876 case Builtin::BI__builtin_isinf: {
6877 APFloat Val(0.0);
6878 return EvaluateFloat(E->getArg(0), Val, Info) &&
6879 Success(Val.isInfinity() ? 1 : 0, E);
6880 }
6881
6882 case Builtin::BI__builtin_isfinite: {
6883 APFloat Val(0.0);
6884 return EvaluateFloat(E->getArg(0), Val, Info) &&
6885 Success(Val.isFinite() ? 1 : 0, E);
6886 }
6887
6888 case Builtin::BI__builtin_isnan: {
6889 APFloat Val(0.0);
6890 return EvaluateFloat(E->getArg(0), Val, Info) &&
6891 Success(Val.isNaN() ? 1 : 0, E);
6892 }
6893
6894 case Builtin::BI__builtin_isnormal: {
6895 APFloat Val(0.0);
6896 return EvaluateFloat(E->getArg(0), Val, Info) &&
6897 Success(Val.isNormal() ? 1 : 0, E);
6898 }
6899
Richard Smith8889a3d2013-06-13 06:26:32 +00006900 case Builtin::BI__builtin_parity:
6901 case Builtin::BI__builtin_parityl:
6902 case Builtin::BI__builtin_parityll: {
6903 APSInt Val;
6904 if (!EvaluateInteger(E->getArg(0), Val, Info))
6905 return false;
6906
6907 return Success(Val.countPopulation() % 2, E);
6908 }
6909
Richard Smith80b3c8e2013-06-13 05:04:16 +00006910 case Builtin::BI__builtin_popcount:
6911 case Builtin::BI__builtin_popcountl:
6912 case Builtin::BI__builtin_popcountll: {
6913 APSInt Val;
6914 if (!EvaluateInteger(E->getArg(0), Val, Info))
6915 return false;
6916
6917 return Success(Val.countPopulation(), E);
6918 }
6919
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006920 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006921 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006922 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006923 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006924 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6925 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006926 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006927 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006928 case Builtin::BI__builtin_strlen: {
6929 // As an extension, we support __builtin_strlen() as a constant expression,
6930 // and support folding strlen() to a constant.
6931 LValue String;
6932 if (!EvaluatePointer(E->getArg(0), String, Info))
6933 return false;
6934
6935 // Fast path: if it's a string literal, search the string value.
6936 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6937 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006938 // The string literal may have embedded null characters. Find the first
6939 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006940 StringRef Str = S->getBytes();
6941 int64_t Off = String.Offset.getQuantity();
6942 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6943 S->getCharByteWidth() == 1) {
6944 Str = Str.substr(Off);
6945
6946 StringRef::size_type Pos = Str.find(0);
6947 if (Pos != StringRef::npos)
6948 Str = Str.substr(0, Pos);
6949
6950 return Success(Str.size(), E);
6951 }
6952
6953 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006954 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006955
6956 // Slow path: scan the bytes of the string looking for the terminating 0.
6957 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6958 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6959 APValue Char;
6960 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6961 !Char.isInt())
6962 return false;
6963 if (!Char.getInt())
6964 return Success(Strlen, E);
6965 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6966 return false;
6967 }
6968 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006969
Richard Smith01ba47d2012-04-13 00:45:38 +00006970 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006971 case Builtin::BI__atomic_is_lock_free:
6972 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006973 APSInt SizeVal;
6974 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6975 return false;
6976
6977 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6978 // of two less than the maximum inline atomic width, we know it is
6979 // lock-free. If the size isn't a power of two, or greater than the
6980 // maximum alignment where we promote atomics, we know it is not lock-free
6981 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6982 // the answer can only be determined at runtime; for example, 16-byte
6983 // atomics have lock-free implementations on some, but not all,
6984 // x86-64 processors.
6985
6986 // Check power-of-two.
6987 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006988 if (Size.isPowerOfTwo()) {
6989 // Check against inlining width.
6990 unsigned InlineWidthBits =
6991 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6992 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6993 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6994 Size == CharUnits::One() ||
6995 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6996 Expr::NPC_NeverValueDependent))
6997 // OK, we will inline appropriately-aligned operations of this size,
6998 // and _Atomic(T) is appropriately-aligned.
6999 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007000
Richard Smith01ba47d2012-04-13 00:45:38 +00007001 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7002 castAs<PointerType>()->getPointeeType();
7003 if (!PointeeType->isIncompleteType() &&
7004 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7005 // OK, we will inline operations on this object.
7006 return Success(1, E);
7007 }
7008 }
7009 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007010
Richard Smith01ba47d2012-04-13 00:45:38 +00007011 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7012 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007013 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007014 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007015}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007016
Richard Smith8b3497e2011-10-31 01:37:14 +00007017static bool HasSameBase(const LValue &A, const LValue &B) {
7018 if (!A.getLValueBase())
7019 return !B.getLValueBase();
7020 if (!B.getLValueBase())
7021 return false;
7022
Richard Smithce40ad62011-11-12 22:28:03 +00007023 if (A.getLValueBase().getOpaqueValue() !=
7024 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007025 const Decl *ADecl = GetLValueBaseDecl(A);
7026 if (!ADecl)
7027 return false;
7028 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007029 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007030 return false;
7031 }
7032
7033 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007034 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007035}
7036
Richard Smithd20f1e62014-10-21 23:01:04 +00007037/// \brief Determine whether this is a pointer past the end of the complete
7038/// object referred to by the lvalue.
7039static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7040 const LValue &LV) {
7041 // A null pointer can be viewed as being "past the end" but we don't
7042 // choose to look at it that way here.
7043 if (!LV.getLValueBase())
7044 return false;
7045
7046 // If the designator is valid and refers to a subobject, we're not pointing
7047 // past the end.
7048 if (!LV.getLValueDesignator().Invalid &&
7049 !LV.getLValueDesignator().isOnePastTheEnd())
7050 return false;
7051
David Majnemerc378ca52015-08-29 08:32:55 +00007052 // A pointer to an incomplete type might be past-the-end if the type's size is
7053 // zero. We cannot tell because the type is incomplete.
7054 QualType Ty = getType(LV.getLValueBase());
7055 if (Ty->isIncompleteType())
7056 return true;
7057
Richard Smithd20f1e62014-10-21 23:01:04 +00007058 // We're a past-the-end pointer if we point to the byte after the object,
7059 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007060 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007061 return LV.getLValueOffset() == Size;
7062}
7063
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007064namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007065
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007066/// \brief Data recursive integer evaluator of certain binary operators.
7067///
7068/// We use a data recursive algorithm for binary operators so that we are able
7069/// to handle extreme cases of chained binary operators without causing stack
7070/// overflow.
7071class DataRecursiveIntBinOpEvaluator {
7072 struct EvalResult {
7073 APValue Val;
7074 bool Failed;
7075
7076 EvalResult() : Failed(false) { }
7077
7078 void swap(EvalResult &RHS) {
7079 Val.swap(RHS.Val);
7080 Failed = RHS.Failed;
7081 RHS.Failed = false;
7082 }
7083 };
7084
7085 struct Job {
7086 const Expr *E;
7087 EvalResult LHSResult; // meaningful only for binary operator expression.
7088 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007089
David Blaikie73726062015-08-12 23:09:24 +00007090 Job() = default;
7091 Job(Job &&J)
7092 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
George Burgess IV8c892b52016-05-25 22:31:54 +00007093 SpecEvalRAII(std::move(J.SpecEvalRAII)) {}
David Blaikie73726062015-08-12 23:09:24 +00007094
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007095 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007096 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007097 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007098
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007099 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007100 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007101 };
7102
7103 SmallVector<Job, 16> Queue;
7104
7105 IntExprEvaluator &IntEval;
7106 EvalInfo &Info;
7107 APValue &FinalResult;
7108
7109public:
7110 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7111 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7112
7113 /// \brief True if \param E is a binary operator that we are going to handle
7114 /// data recursively.
7115 /// We handle binary operators that are comma, logical, or that have operands
7116 /// with integral or enumeration type.
7117 static bool shouldEnqueue(const BinaryOperator *E) {
7118 return E->getOpcode() == BO_Comma ||
7119 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007120 (E->isRValue() &&
7121 E->getType()->isIntegralOrEnumerationType() &&
7122 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007123 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007124 }
7125
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007126 bool Traverse(const BinaryOperator *E) {
7127 enqueue(E);
7128 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007129 while (!Queue.empty())
7130 process(PrevResult);
7131
7132 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007133
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007134 FinalResult.swap(PrevResult.Val);
7135 return true;
7136 }
7137
7138private:
7139 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7140 return IntEval.Success(Value, E, Result);
7141 }
7142 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7143 return IntEval.Success(Value, E, Result);
7144 }
7145 bool Error(const Expr *E) {
7146 return IntEval.Error(E);
7147 }
7148 bool Error(const Expr *E, diag::kind D) {
7149 return IntEval.Error(E, D);
7150 }
7151
7152 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7153 return Info.CCEDiag(E, D);
7154 }
7155
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007156 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7157 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007158 bool &SuppressRHSDiags);
7159
7160 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7161 const BinaryOperator *E, APValue &Result);
7162
7163 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7164 Result.Failed = !Evaluate(Result.Val, Info, E);
7165 if (Result.Failed)
7166 Result.Val = APValue();
7167 }
7168
Richard Trieuba4d0872012-03-21 23:30:30 +00007169 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007170
7171 void enqueue(const Expr *E) {
7172 E = E->IgnoreParens();
7173 Queue.resize(Queue.size()+1);
7174 Queue.back().E = E;
7175 Queue.back().Kind = Job::AnyExprKind;
7176 }
7177};
7178
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007179}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007180
7181bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007182 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007183 bool &SuppressRHSDiags) {
7184 if (E->getOpcode() == BO_Comma) {
7185 // Ignore LHS but note if we could not evaluate it.
7186 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007187 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007188 return true;
7189 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007190
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007191 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007192 bool LHSAsBool;
7193 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007194 // We were able to evaluate the LHS, see if we can get away with not
7195 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007196 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7197 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007198 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007199 }
7200 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007201 LHSResult.Failed = true;
7202
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007203 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007204 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007205 if (!Info.noteSideEffect())
7206 return false;
7207
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007208 // We can't evaluate the LHS; however, sometimes the result
7209 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7210 // Don't ignore RHS and suppress diagnostics from this arm.
7211 SuppressRHSDiags = true;
7212 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007213
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007214 return true;
7215 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007216
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007217 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7218 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007219
George Burgess IVa145e252016-05-25 22:38:36 +00007220 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007221 return false; // Ignore RHS;
7222
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007223 return true;
7224}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007225
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007226bool DataRecursiveIntBinOpEvaluator::
7227 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7228 const BinaryOperator *E, APValue &Result) {
7229 if (E->getOpcode() == BO_Comma) {
7230 if (RHSResult.Failed)
7231 return false;
7232 Result = RHSResult.Val;
7233 return true;
7234 }
7235
7236 if (E->isLogicalOp()) {
7237 bool lhsResult, rhsResult;
7238 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7239 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7240
7241 if (LHSIsOK) {
7242 if (RHSIsOK) {
7243 if (E->getOpcode() == BO_LOr)
7244 return Success(lhsResult || rhsResult, E, Result);
7245 else
7246 return Success(lhsResult && rhsResult, E, Result);
7247 }
7248 } else {
7249 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007250 // We can't evaluate the LHS; however, sometimes the result
7251 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7252 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007253 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007254 }
7255 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007256
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007257 return false;
7258 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007259
7260 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7261 E->getRHS()->getType()->isIntegralOrEnumerationType());
7262
7263 if (LHSResult.Failed || RHSResult.Failed)
7264 return false;
7265
7266 const APValue &LHSVal = LHSResult.Val;
7267 const APValue &RHSVal = RHSResult.Val;
7268
7269 // Handle cases like (unsigned long)&a + 4.
7270 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7271 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007272 CharUnits AdditionalOffset =
7273 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007274 if (E->getOpcode() == BO_Add)
7275 Result.getLValueOffset() += AdditionalOffset;
7276 else
7277 Result.getLValueOffset() -= AdditionalOffset;
7278 return true;
7279 }
7280
7281 // Handle cases like 4 + (unsigned long)&a
7282 if (E->getOpcode() == BO_Add &&
7283 RHSVal.isLValue() && LHSVal.isInt()) {
7284 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007285 Result.getLValueOffset() +=
7286 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007287 return true;
7288 }
7289
7290 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7291 // Handle (intptr_t)&&A - (intptr_t)&&B.
7292 if (!LHSVal.getLValueOffset().isZero() ||
7293 !RHSVal.getLValueOffset().isZero())
7294 return false;
7295 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7296 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7297 if (!LHSExpr || !RHSExpr)
7298 return false;
7299 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7300 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7301 if (!LHSAddrExpr || !RHSAddrExpr)
7302 return false;
7303 // Make sure both labels come from the same function.
7304 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7305 RHSAddrExpr->getLabel()->getDeclContext())
7306 return false;
7307 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7308 return true;
7309 }
Richard Smith43e77732013-05-07 04:50:00 +00007310
7311 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007312 if (!LHSVal.isInt() || !RHSVal.isInt())
7313 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007314
7315 // Set up the width and signedness manually, in case it can't be deduced
7316 // from the operation we're performing.
7317 // FIXME: Don't do this in the cases where we can deduce it.
7318 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7319 E->getType()->isUnsignedIntegerOrEnumerationType());
7320 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7321 RHSVal.getInt(), Value))
7322 return false;
7323 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007324}
7325
Richard Trieuba4d0872012-03-21 23:30:30 +00007326void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007327 Job &job = Queue.back();
7328
7329 switch (job.Kind) {
7330 case Job::AnyExprKind: {
7331 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7332 if (shouldEnqueue(Bop)) {
7333 job.Kind = Job::BinOpKind;
7334 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007335 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007336 }
7337 }
7338
7339 EvaluateExpr(job.E, Result);
7340 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007341 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007342 }
7343
7344 case Job::BinOpKind: {
7345 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007346 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007347 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007348 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007349 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007350 }
7351 if (SuppressRHSDiags)
7352 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007353 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007354 job.Kind = Job::BinOpVisitedLHSKind;
7355 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007356 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007357 }
7358
7359 case Job::BinOpVisitedLHSKind: {
7360 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7361 EvalResult RHS;
7362 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007363 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007364 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007365 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007366 }
7367 }
7368
7369 llvm_unreachable("Invalid Job::Kind!");
7370}
7371
George Burgess IV8c892b52016-05-25 22:31:54 +00007372namespace {
7373/// Used when we determine that we should fail, but can keep evaluating prior to
7374/// noting that we had a failure.
7375class DelayedNoteFailureRAII {
7376 EvalInfo &Info;
7377 bool NoteFailure;
7378
7379public:
7380 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7381 : Info(Info), NoteFailure(NoteFailure) {}
7382 ~DelayedNoteFailureRAII() {
7383 if (NoteFailure) {
7384 bool ContinueAfterFailure = Info.noteFailure();
7385 (void)ContinueAfterFailure;
7386 assert(ContinueAfterFailure &&
7387 "Shouldn't have kept evaluating on failure.");
7388 }
7389 }
7390};
7391}
7392
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007393bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007394 // We don't call noteFailure immediately because the assignment happens after
7395 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007396 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007397 return Error(E);
7398
George Burgess IV8c892b52016-05-25 22:31:54 +00007399 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007400 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7401 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007402
Anders Carlssonacc79812008-11-16 07:17:21 +00007403 QualType LHSTy = E->getLHS()->getType();
7404 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007405
Chandler Carruthb29a7432014-10-11 11:03:30 +00007406 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007407 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007408 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007409 if (E->isAssignmentOp()) {
7410 LValue LV;
7411 EvaluateLValue(E->getLHS(), LV, Info);
7412 LHSOK = false;
7413 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007414 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7415 if (LHSOK) {
7416 LHS.makeComplexFloat();
7417 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7418 }
7419 } else {
7420 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7421 }
George Burgess IVa145e252016-05-25 22:38:36 +00007422 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007423 return false;
7424
Chandler Carruthb29a7432014-10-11 11:03:30 +00007425 if (E->getRHS()->getType()->isRealFloatingType()) {
7426 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7427 return false;
7428 RHS.makeComplexFloat();
7429 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7430 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007431 return false;
7432
7433 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007434 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007435 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007436 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007437 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7438
John McCalle3027922010-08-25 11:45:40 +00007439 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007440 return Success((CR_r == APFloat::cmpEqual &&
7441 CR_i == APFloat::cmpEqual), E);
7442 else {
John McCalle3027922010-08-25 11:45:40 +00007443 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007444 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007445 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007446 CR_r == APFloat::cmpLessThan ||
7447 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007448 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007449 CR_i == APFloat::cmpLessThan ||
7450 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007451 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007452 } else {
John McCalle3027922010-08-25 11:45:40 +00007453 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007454 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7455 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7456 else {
John McCalle3027922010-08-25 11:45:40 +00007457 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007458 "Invalid compex comparison.");
7459 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7460 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7461 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007462 }
7463 }
Mike Stump11289f42009-09-09 15:08:12 +00007464
Anders Carlssonacc79812008-11-16 07:17:21 +00007465 if (LHSTy->isRealFloatingType() &&
7466 RHSTy->isRealFloatingType()) {
7467 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007468
Richard Smith253c2a32012-01-27 01:14:48 +00007469 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007470 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007471 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007472
Richard Smith253c2a32012-01-27 01:14:48 +00007473 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007474 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007475
Anders Carlssonacc79812008-11-16 07:17:21 +00007476 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007477
Anders Carlssonacc79812008-11-16 07:17:21 +00007478 switch (E->getOpcode()) {
7479 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007480 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007481 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007482 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007483 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007484 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007485 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007486 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007487 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007488 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007489 E);
John McCalle3027922010-08-25 11:45:40 +00007490 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007491 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007492 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007493 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007494 || CR == APFloat::cmpLessThan
7495 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007496 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007497 }
Mike Stump11289f42009-09-09 15:08:12 +00007498
Eli Friedmana38da572009-04-28 19:17:36 +00007499 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007500 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007501 LValue LHSValue, RHSValue;
7502
7503 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007504 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007505 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007506
Richard Smith253c2a32012-01-27 01:14:48 +00007507 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007508 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007509
Richard Smith8b3497e2011-10-31 01:37:14 +00007510 // Reject differing bases from the normal codepath; we special-case
7511 // comparisons to null.
7512 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007513 if (E->getOpcode() == BO_Sub) {
7514 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007515 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007516 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007517 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007518 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007519 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007520 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007521 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7522 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7523 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007524 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007525 // Make sure both labels come from the same function.
7526 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7527 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007528 return Error(E);
7529 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007530 }
Richard Smith83c68212011-10-31 05:11:32 +00007531 // Inequalities and subtractions between unrelated pointers have
7532 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007533 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007534 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007535 // A constant address may compare equal to the address of a symbol.
7536 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007537 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007538 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7539 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007540 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007541 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007542 // distinct addresses. In clang, the result of such a comparison is
7543 // unspecified, so it is not a constant expression. However, we do know
7544 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007545 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7546 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007547 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007548 // We can't tell whether weak symbols will end up pointing to the same
7549 // object.
7550 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007551 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007552 // We can't compare the address of the start of one object with the
7553 // past-the-end address of another object, per C++ DR1652.
7554 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7555 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7556 (RHSValue.Base && RHSValue.Offset.isZero() &&
7557 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7558 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007559 // We can't tell whether an object is at the same address as another
7560 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007561 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7562 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007563 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007564 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007565 // (Note that clang defaults to -fmerge-all-constants, which can
7566 // lead to inconsistent results for comparisons involving the address
7567 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007568 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007569 }
Eli Friedman64004332009-03-23 04:38:34 +00007570
Richard Smith1b470412012-02-01 08:10:20 +00007571 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7572 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7573
Richard Smith84f6dcf2012-02-02 01:16:57 +00007574 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7575 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7576
John McCalle3027922010-08-25 11:45:40 +00007577 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007578 // C++11 [expr.add]p6:
7579 // Unless both pointers point to elements of the same array object, or
7580 // one past the last element of the array object, the behavior is
7581 // undefined.
7582 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7583 !AreElementsOfSameArray(getType(LHSValue.Base),
7584 LHSDesignator, RHSDesignator))
7585 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7586
Chris Lattner882bdf22010-04-20 17:13:14 +00007587 QualType Type = E->getLHS()->getType();
7588 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007589
Richard Smithd62306a2011-11-10 06:34:14 +00007590 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007591 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007592 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007593
Richard Smith84c6b3d2013-09-10 21:34:14 +00007594 // As an extension, a type may have zero size (empty struct or union in
7595 // C, array of zero length). Pointer subtraction in such cases has
7596 // undefined behavior, so is not constant.
7597 if (ElementSize.isZero()) {
7598 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7599 << ElementType;
7600 return false;
7601 }
7602
Richard Smith1b470412012-02-01 08:10:20 +00007603 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7604 // and produce incorrect results when it overflows. Such behavior
7605 // appears to be non-conforming, but is common, so perhaps we should
7606 // assume the standard intended for such cases to be undefined behavior
7607 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007608
Richard Smith1b470412012-02-01 08:10:20 +00007609 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7610 // overflow in the final conversion to ptrdiff_t.
7611 APSInt LHS(
7612 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7613 APSInt RHS(
7614 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7615 APSInt ElemSize(
7616 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7617 APSInt TrueResult = (LHS - RHS) / ElemSize;
7618 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7619
Richard Smith0c6124b2015-12-03 01:36:22 +00007620 if (Result.extend(65) != TrueResult &&
7621 !HandleOverflow(Info, E, TrueResult, E->getType()))
7622 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007623 return Success(Result, E);
7624 }
Richard Smithde21b242012-01-31 06:41:30 +00007625
7626 // C++11 [expr.rel]p3:
7627 // Pointers to void (after pointer conversions) can be compared, with a
7628 // result defined as follows: If both pointers represent the same
7629 // address or are both the null pointer value, the result is true if the
7630 // operator is <= or >= and false otherwise; otherwise the result is
7631 // unspecified.
7632 // We interpret this as applying to pointers to *cv* void.
7633 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007634 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007635 CCEDiag(E, diag::note_constexpr_void_comparison);
7636
Richard Smith84f6dcf2012-02-02 01:16:57 +00007637 // C++11 [expr.rel]p2:
7638 // - If two pointers point to non-static data members of the same object,
7639 // or to subobjects or array elements fo such members, recursively, the
7640 // pointer to the later declared member compares greater provided the
7641 // two members have the same access control and provided their class is
7642 // not a union.
7643 // [...]
7644 // - Otherwise pointer comparisons are unspecified.
7645 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7646 E->isRelationalOp()) {
7647 bool WasArrayIndex;
7648 unsigned Mismatch =
7649 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7650 RHSDesignator, WasArrayIndex);
7651 // At the point where the designators diverge, the comparison has a
7652 // specified value if:
7653 // - we are comparing array indices
7654 // - we are comparing fields of a union, or fields with the same access
7655 // Otherwise, the result is unspecified and thus the comparison is not a
7656 // constant expression.
7657 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7658 Mismatch < RHSDesignator.Entries.size()) {
7659 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7660 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7661 if (!LF && !RF)
7662 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7663 else if (!LF)
7664 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7665 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7666 << RF->getParent() << RF;
7667 else if (!RF)
7668 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7669 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7670 << LF->getParent() << LF;
7671 else if (!LF->getParent()->isUnion() &&
7672 LF->getAccess() != RF->getAccess())
7673 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7674 << LF << LF->getAccess() << RF << RF->getAccess()
7675 << LF->getParent();
7676 }
7677 }
7678
Eli Friedman6c31cb42012-04-16 04:30:08 +00007679 // The comparison here must be unsigned, and performed with the same
7680 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007681 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7682 uint64_t CompareLHS = LHSOffset.getQuantity();
7683 uint64_t CompareRHS = RHSOffset.getQuantity();
7684 assert(PtrSize <= 64 && "Unexpected pointer width");
7685 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7686 CompareLHS &= Mask;
7687 CompareRHS &= Mask;
7688
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007689 // If there is a base and this is a relational operator, we can only
7690 // compare pointers within the object in question; otherwise, the result
7691 // depends on where the object is located in memory.
7692 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7693 QualType BaseTy = getType(LHSValue.Base);
7694 if (BaseTy->isIncompleteType())
7695 return Error(E);
7696 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7697 uint64_t OffsetLimit = Size.getQuantity();
7698 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7699 return Error(E);
7700 }
7701
Richard Smith8b3497e2011-10-31 01:37:14 +00007702 switch (E->getOpcode()) {
7703 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007704 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7705 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7706 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7707 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7708 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7709 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007710 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007711 }
7712 }
Richard Smith7bb00672012-02-01 01:42:44 +00007713
7714 if (LHSTy->isMemberPointerType()) {
7715 assert(E->isEqualityOp() && "unexpected member pointer operation");
7716 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7717
7718 MemberPtr LHSValue, RHSValue;
7719
7720 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007721 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00007722 return false;
7723
7724 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7725 return false;
7726
7727 // C++11 [expr.eq]p2:
7728 // If both operands are null, they compare equal. Otherwise if only one is
7729 // null, they compare unequal.
7730 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7731 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7732 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7733 }
7734
7735 // Otherwise if either is a pointer to a virtual member function, the
7736 // result is unspecified.
7737 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7738 if (MD->isVirtual())
7739 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7740 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7741 if (MD->isVirtual())
7742 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7743
7744 // Otherwise they compare equal if and only if they would refer to the
7745 // same member of the same most derived object or the same subobject if
7746 // they were dereferenced with a hypothetical object of the associated
7747 // class type.
7748 bool Equal = LHSValue == RHSValue;
7749 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7750 }
7751
Richard Smithab44d9b2012-02-14 22:35:28 +00007752 if (LHSTy->isNullPtrType()) {
7753 assert(E->isComparisonOp() && "unexpected nullptr operation");
7754 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7755 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7756 // are compared, the result is true of the operator is <=, >= or ==, and
7757 // false otherwise.
7758 BinaryOperator::Opcode Opcode = E->getOpcode();
7759 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7760 }
7761
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007762 assert((!LHSTy->isIntegralOrEnumerationType() ||
7763 !RHSTy->isIntegralOrEnumerationType()) &&
7764 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7765 // We can't continue from here for non-integral types.
7766 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007767}
7768
Peter Collingbournee190dee2011-03-11 19:24:49 +00007769/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7770/// a result as the expression's type.
7771bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7772 const UnaryExprOrTypeTraitExpr *E) {
7773 switch(E->getKind()) {
7774 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007775 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007776 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007777 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007778 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007779 }
Eli Friedman64004332009-03-23 04:38:34 +00007780
Peter Collingbournee190dee2011-03-11 19:24:49 +00007781 case UETT_VecStep: {
7782 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007783
Peter Collingbournee190dee2011-03-11 19:24:49 +00007784 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007785 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007786
Peter Collingbournee190dee2011-03-11 19:24:49 +00007787 // The vec_step built-in functions that take a 3-component
7788 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7789 if (n == 3)
7790 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007791
Peter Collingbournee190dee2011-03-11 19:24:49 +00007792 return Success(n, E);
7793 } else
7794 return Success(1, E);
7795 }
7796
7797 case UETT_SizeOf: {
7798 QualType SrcTy = E->getTypeOfArgument();
7799 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7800 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007801 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7802 SrcTy = Ref->getPointeeType();
7803
Richard Smithd62306a2011-11-10 06:34:14 +00007804 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007805 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007806 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007807 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007808 }
Alexey Bataev00396512015-07-02 03:40:19 +00007809 case UETT_OpenMPRequiredSimdAlign:
7810 assert(E->isArgumentType());
7811 return Success(
7812 Info.Ctx.toCharUnitsFromBits(
7813 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7814 .getQuantity(),
7815 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007816 }
7817
7818 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007819}
7820
Peter Collingbournee9200682011-05-13 03:29:01 +00007821bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007822 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007823 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007824 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007825 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007826 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007827 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00007828 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00007829 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00007830 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007831 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007832 APSInt IdxResult;
7833 if (!EvaluateInteger(Idx, IdxResult, Info))
7834 return false;
7835 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7836 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007837 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007838 CurrentType = AT->getElementType();
7839 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7840 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007841 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007842 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007843
James Y Knight7281c352015-12-29 22:31:18 +00007844 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00007845 FieldDecl *MemberDecl = ON.getField();
7846 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007847 if (!RT)
7848 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007849 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007850 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007851 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007852 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007853 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007854 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007855 CurrentType = MemberDecl->getType().getNonReferenceType();
7856 break;
7857 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007858
James Y Knight7281c352015-12-29 22:31:18 +00007859 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00007860 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007861
James Y Knight7281c352015-12-29 22:31:18 +00007862 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00007863 CXXBaseSpecifier *BaseSpec = ON.getBase();
7864 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007865 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007866
7867 // Find the layout of the class whose base we are looking into.
7868 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007869 if (!RT)
7870 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007871 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007872 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007873 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7874
7875 // Find the base class itself.
7876 CurrentType = BaseSpec->getType();
7877 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7878 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007879 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007880
7881 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007882 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007883 break;
7884 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007885 }
7886 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007887 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007888}
7889
Chris Lattnere13042c2008-07-11 19:10:17 +00007890bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007891 switch (E->getOpcode()) {
7892 default:
7893 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7894 // See C99 6.6p3.
7895 return Error(E);
7896 case UO_Extension:
7897 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7898 // If so, we could clear the diagnostic ID.
7899 return Visit(E->getSubExpr());
7900 case UO_Plus:
7901 // The result is just the value.
7902 return Visit(E->getSubExpr());
7903 case UO_Minus: {
7904 if (!Visit(E->getSubExpr()))
7905 return false;
7906 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007907 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00007908 if (Value.isSigned() && Value.isMinSignedValue() &&
7909 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7910 E->getType()))
7911 return false;
Richard Smithfe800032012-01-31 04:08:20 +00007912 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007913 }
7914 case UO_Not: {
7915 if (!Visit(E->getSubExpr()))
7916 return false;
7917 if (!Result.isInt()) return Error(E);
7918 return Success(~Result.getInt(), E);
7919 }
7920 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007921 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007922 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007923 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007924 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007925 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007926 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007927}
Mike Stump11289f42009-09-09 15:08:12 +00007928
Chris Lattner477c4be2008-07-12 01:15:53 +00007929/// HandleCast - This is used to evaluate implicit or explicit casts where the
7930/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007931bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7932 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007933 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007934 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007935
Eli Friedmanc757de22011-03-25 00:43:55 +00007936 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007937 case CK_BaseToDerived:
7938 case CK_DerivedToBase:
7939 case CK_UncheckedDerivedToBase:
7940 case CK_Dynamic:
7941 case CK_ToUnion:
7942 case CK_ArrayToPointerDecay:
7943 case CK_FunctionToPointerDecay:
7944 case CK_NullToPointer:
7945 case CK_NullToMemberPointer:
7946 case CK_BaseToDerivedMemberPointer:
7947 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007948 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007949 case CK_ConstructorConversion:
7950 case CK_IntegralToPointer:
7951 case CK_ToVoid:
7952 case CK_VectorSplat:
7953 case CK_IntegralToFloating:
7954 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007955 case CK_CPointerToObjCPointerCast:
7956 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007957 case CK_AnyPointerToBlockPointerCast:
7958 case CK_ObjCObjectLValueCast:
7959 case CK_FloatingRealToComplex:
7960 case CK_FloatingComplexToReal:
7961 case CK_FloatingComplexCast:
7962 case CK_FloatingComplexToIntegralComplex:
7963 case CK_IntegralRealToComplex:
7964 case CK_IntegralComplexCast:
7965 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007966 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007967 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007968 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007969 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007970 llvm_unreachable("invalid cast kind for integral value");
7971
Eli Friedman9faf2f92011-03-25 19:07:11 +00007972 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007973 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007974 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007975 case CK_ARCProduceObject:
7976 case CK_ARCConsumeObject:
7977 case CK_ARCReclaimReturnedObject:
7978 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007979 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007980 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007981
Richard Smith4ef685b2012-01-17 21:17:26 +00007982 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007983 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007984 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007985 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007986 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007987
7988 case CK_MemberPointerToBoolean:
7989 case CK_PointerToBoolean:
7990 case CK_IntegralToBoolean:
7991 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00007992 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00007993 case CK_FloatingComplexToBoolean:
7994 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007995 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007996 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007997 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00007998 uint64_t IntResult = BoolResult;
7999 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8000 IntResult = (uint64_t)-1;
8001 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008002 }
8003
Eli Friedmanc757de22011-03-25 00:43:55 +00008004 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008005 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008006 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008007
Eli Friedman742421e2009-02-20 01:15:07 +00008008 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008009 // Allow casts of address-of-label differences if they are no-ops
8010 // or narrowing. (The narrowing case isn't actually guaranteed to
8011 // be constant-evaluatable except in some narrow cases which are hard
8012 // to detect here. We let it through on the assumption the user knows
8013 // what they are doing.)
8014 if (Result.isAddrLabelDiff())
8015 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008016 // Only allow casts of lvalues if they are lossless.
8017 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8018 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008019
Richard Smith911e1422012-01-30 22:27:01 +00008020 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8021 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008022 }
Mike Stump11289f42009-09-09 15:08:12 +00008023
Eli Friedmanc757de22011-03-25 00:43:55 +00008024 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008025 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8026
John McCall45d55e42010-05-07 21:00:08 +00008027 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008028 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008029 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008030
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008031 if (LV.getLValueBase()) {
8032 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008033 // FIXME: Allow a larger integer size than the pointer size, and allow
8034 // narrowing back down to pointer width in subsequent integral casts.
8035 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008036 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008037 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008038
Richard Smithcf74da72011-11-16 07:18:12 +00008039 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008040 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008041 return true;
8042 }
8043
Ken Dyck02990832010-01-15 12:37:54 +00008044 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8045 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008046 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008047 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008048
Eli Friedmanc757de22011-03-25 00:43:55 +00008049 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008050 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008051 if (!EvaluateComplex(SubExpr, C, Info))
8052 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008053 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008054 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008055
Eli Friedmanc757de22011-03-25 00:43:55 +00008056 case CK_FloatingToIntegral: {
8057 APFloat F(0.0);
8058 if (!EvaluateFloat(SubExpr, F, Info))
8059 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008060
Richard Smith357362d2011-12-13 06:39:58 +00008061 APSInt Value;
8062 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8063 return false;
8064 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008065 }
8066 }
Mike Stump11289f42009-09-09 15:08:12 +00008067
Eli Friedmanc757de22011-03-25 00:43:55 +00008068 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008069}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008070
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008071bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8072 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008073 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008074 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8075 return false;
8076 if (!LV.isComplexInt())
8077 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008078 return Success(LV.getComplexIntReal(), E);
8079 }
8080
8081 return Visit(E->getSubExpr());
8082}
8083
Eli Friedman4e7a2412009-02-27 04:45:43 +00008084bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008085 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008086 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008087 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8088 return false;
8089 if (!LV.isComplexInt())
8090 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008091 return Success(LV.getComplexIntImag(), E);
8092 }
8093
Richard Smith4a678122011-10-24 18:44:57 +00008094 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008095 return Success(0, E);
8096}
8097
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008098bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8099 return Success(E->getPackLength(), E);
8100}
8101
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008102bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8103 return Success(E->getValue(), E);
8104}
8105
Chris Lattner05706e882008-07-11 18:11:29 +00008106//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008107// Float Evaluation
8108//===----------------------------------------------------------------------===//
8109
8110namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008111class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008112 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008113 APFloat &Result;
8114public:
8115 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008116 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008117
Richard Smith2e312c82012-03-03 22:46:17 +00008118 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008119 Result = V.getFloat();
8120 return true;
8121 }
Eli Friedman24c01542008-08-22 00:06:13 +00008122
Richard Smithfddd3842011-12-30 21:15:51 +00008123 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008124 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8125 return true;
8126 }
8127
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008128 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008129
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008130 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008131 bool VisitBinaryOperator(const BinaryOperator *E);
8132 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008133 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008134
John McCallb1fb0d32010-05-07 22:08:54 +00008135 bool VisitUnaryReal(const UnaryOperator *E);
8136 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008137
Richard Smithfddd3842011-12-30 21:15:51 +00008138 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008139};
8140} // end anonymous namespace
8141
8142static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008143 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008144 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008145}
8146
Jay Foad39c79802011-01-12 09:06:06 +00008147static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008148 QualType ResultTy,
8149 const Expr *Arg,
8150 bool SNaN,
8151 llvm::APFloat &Result) {
8152 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8153 if (!S) return false;
8154
8155 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8156
8157 llvm::APInt fill;
8158
8159 // Treat empty strings as if they were zero.
8160 if (S->getString().empty())
8161 fill = llvm::APInt(32, 0);
8162 else if (S->getString().getAsInteger(0, fill))
8163 return false;
8164
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008165 if (Context.getTargetInfo().isNan2008()) {
8166 if (SNaN)
8167 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8168 else
8169 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8170 } else {
8171 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8172 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8173 // a different encoding to what became a standard in 2008, and for pre-
8174 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8175 // sNaN. This is now known as "legacy NaN" encoding.
8176 if (SNaN)
8177 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8178 else
8179 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8180 }
8181
John McCall16291492010-02-28 13:00:19 +00008182 return true;
8183}
8184
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008185bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008186 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008187 default:
8188 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8189
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008190 case Builtin::BI__builtin_huge_val:
8191 case Builtin::BI__builtin_huge_valf:
8192 case Builtin::BI__builtin_huge_vall:
8193 case Builtin::BI__builtin_inf:
8194 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008195 case Builtin::BI__builtin_infl: {
8196 const llvm::fltSemantics &Sem =
8197 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008198 Result = llvm::APFloat::getInf(Sem);
8199 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008200 }
Mike Stump11289f42009-09-09 15:08:12 +00008201
John McCall16291492010-02-28 13:00:19 +00008202 case Builtin::BI__builtin_nans:
8203 case Builtin::BI__builtin_nansf:
8204 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008205 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8206 true, Result))
8207 return Error(E);
8208 return true;
John McCall16291492010-02-28 13:00:19 +00008209
Chris Lattner0b7282e2008-10-06 06:31:58 +00008210 case Builtin::BI__builtin_nan:
8211 case Builtin::BI__builtin_nanf:
8212 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008213 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008214 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008215 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8216 false, Result))
8217 return Error(E);
8218 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008219
8220 case Builtin::BI__builtin_fabs:
8221 case Builtin::BI__builtin_fabsf:
8222 case Builtin::BI__builtin_fabsl:
8223 if (!EvaluateFloat(E->getArg(0), Result, Info))
8224 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008225
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008226 if (Result.isNegative())
8227 Result.changeSign();
8228 return true;
8229
Richard Smith8889a3d2013-06-13 06:26:32 +00008230 // FIXME: Builtin::BI__builtin_powi
8231 // FIXME: Builtin::BI__builtin_powif
8232 // FIXME: Builtin::BI__builtin_powil
8233
Mike Stump11289f42009-09-09 15:08:12 +00008234 case Builtin::BI__builtin_copysign:
8235 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008236 case Builtin::BI__builtin_copysignl: {
8237 APFloat RHS(0.);
8238 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8239 !EvaluateFloat(E->getArg(1), RHS, Info))
8240 return false;
8241 Result.copySign(RHS);
8242 return true;
8243 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008244 }
8245}
8246
John McCallb1fb0d32010-05-07 22:08:54 +00008247bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008248 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8249 ComplexValue CV;
8250 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8251 return false;
8252 Result = CV.FloatReal;
8253 return true;
8254 }
8255
8256 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008257}
8258
8259bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008260 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8261 ComplexValue CV;
8262 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8263 return false;
8264 Result = CV.FloatImag;
8265 return true;
8266 }
8267
Richard Smith4a678122011-10-24 18:44:57 +00008268 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008269 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8270 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008271 return true;
8272}
8273
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008274bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008275 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008276 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008277 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008278 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008279 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008280 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8281 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008282 Result.changeSign();
8283 return true;
8284 }
8285}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008286
Eli Friedman24c01542008-08-22 00:06:13 +00008287bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008288 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8289 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008290
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008291 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008292 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008293 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008294 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008295 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8296 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008297}
8298
8299bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8300 Result = E->getValue();
8301 return true;
8302}
8303
Peter Collingbournee9200682011-05-13 03:29:01 +00008304bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8305 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008306
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008307 switch (E->getCastKind()) {
8308 default:
Richard Smith11562c52011-10-28 17:51:58 +00008309 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008310
8311 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008312 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008313 return EvaluateInteger(SubExpr, IntResult, Info) &&
8314 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8315 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008316 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008317
8318 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008319 if (!Visit(SubExpr))
8320 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008321 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8322 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008323 }
John McCalld7646252010-11-14 08:17:51 +00008324
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008325 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008326 ComplexValue V;
8327 if (!EvaluateComplex(SubExpr, V, Info))
8328 return false;
8329 Result = V.getComplexFloatReal();
8330 return true;
8331 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008332 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008333}
8334
Eli Friedman24c01542008-08-22 00:06:13 +00008335//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008336// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008337//===----------------------------------------------------------------------===//
8338
8339namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008340class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008341 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008342 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008343
Anders Carlsson537969c2008-11-16 20:27:53 +00008344public:
John McCall93d91dc2010-05-07 17:22:02 +00008345 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008346 : ExprEvaluatorBaseTy(info), Result(Result) {}
8347
Richard Smith2e312c82012-03-03 22:46:17 +00008348 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008349 Result.setFrom(V);
8350 return true;
8351 }
Mike Stump11289f42009-09-09 15:08:12 +00008352
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008353 bool ZeroInitialization(const Expr *E);
8354
Anders Carlsson537969c2008-11-16 20:27:53 +00008355 //===--------------------------------------------------------------------===//
8356 // Visitor Methods
8357 //===--------------------------------------------------------------------===//
8358
Peter Collingbournee9200682011-05-13 03:29:01 +00008359 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008360 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008361 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008362 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008363 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008364};
8365} // end anonymous namespace
8366
John McCall93d91dc2010-05-07 17:22:02 +00008367static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8368 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008369 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008370 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008371}
8372
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008373bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008374 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008375 if (ElemTy->isRealFloatingType()) {
8376 Result.makeComplexFloat();
8377 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8378 Result.FloatReal = Zero;
8379 Result.FloatImag = Zero;
8380 } else {
8381 Result.makeComplexInt();
8382 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8383 Result.IntReal = Zero;
8384 Result.IntImag = Zero;
8385 }
8386 return true;
8387}
8388
Peter Collingbournee9200682011-05-13 03:29:01 +00008389bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8390 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008391
8392 if (SubExpr->getType()->isRealFloatingType()) {
8393 Result.makeComplexFloat();
8394 APFloat &Imag = Result.FloatImag;
8395 if (!EvaluateFloat(SubExpr, Imag, Info))
8396 return false;
8397
8398 Result.FloatReal = APFloat(Imag.getSemantics());
8399 return true;
8400 } else {
8401 assert(SubExpr->getType()->isIntegerType() &&
8402 "Unexpected imaginary literal.");
8403
8404 Result.makeComplexInt();
8405 APSInt &Imag = Result.IntImag;
8406 if (!EvaluateInteger(SubExpr, Imag, Info))
8407 return false;
8408
8409 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8410 return true;
8411 }
8412}
8413
Peter Collingbournee9200682011-05-13 03:29:01 +00008414bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008415
John McCallfcef3cf2010-12-14 17:51:41 +00008416 switch (E->getCastKind()) {
8417 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008418 case CK_BaseToDerived:
8419 case CK_DerivedToBase:
8420 case CK_UncheckedDerivedToBase:
8421 case CK_Dynamic:
8422 case CK_ToUnion:
8423 case CK_ArrayToPointerDecay:
8424 case CK_FunctionToPointerDecay:
8425 case CK_NullToPointer:
8426 case CK_NullToMemberPointer:
8427 case CK_BaseToDerivedMemberPointer:
8428 case CK_DerivedToBaseMemberPointer:
8429 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008430 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008431 case CK_ConstructorConversion:
8432 case CK_IntegralToPointer:
8433 case CK_PointerToIntegral:
8434 case CK_PointerToBoolean:
8435 case CK_ToVoid:
8436 case CK_VectorSplat:
8437 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008438 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008439 case CK_IntegralToBoolean:
8440 case CK_IntegralToFloating:
8441 case CK_FloatingToIntegral:
8442 case CK_FloatingToBoolean:
8443 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008444 case CK_CPointerToObjCPointerCast:
8445 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008446 case CK_AnyPointerToBlockPointerCast:
8447 case CK_ObjCObjectLValueCast:
8448 case CK_FloatingComplexToReal:
8449 case CK_FloatingComplexToBoolean:
8450 case CK_IntegralComplexToReal:
8451 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008452 case CK_ARCProduceObject:
8453 case CK_ARCConsumeObject:
8454 case CK_ARCReclaimReturnedObject:
8455 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008456 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008457 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008458 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008459 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008460 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008461 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008462
John McCallfcef3cf2010-12-14 17:51:41 +00008463 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008464 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008465 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008466 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008467
8468 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008469 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008470 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008471 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008472
8473 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008474 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008475 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008476 return false;
8477
John McCallfcef3cf2010-12-14 17:51:41 +00008478 Result.makeComplexFloat();
8479 Result.FloatImag = APFloat(Real.getSemantics());
8480 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008481 }
8482
John McCallfcef3cf2010-12-14 17:51:41 +00008483 case CK_FloatingComplexCast: {
8484 if (!Visit(E->getSubExpr()))
8485 return false;
8486
8487 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8488 QualType From
8489 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8490
Richard Smith357362d2011-12-13 06:39:58 +00008491 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8492 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008493 }
8494
8495 case CK_FloatingComplexToIntegralComplex: {
8496 if (!Visit(E->getSubExpr()))
8497 return false;
8498
8499 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8500 QualType From
8501 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8502 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008503 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8504 To, Result.IntReal) &&
8505 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8506 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008507 }
8508
8509 case CK_IntegralRealToComplex: {
8510 APSInt &Real = Result.IntReal;
8511 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8512 return false;
8513
8514 Result.makeComplexInt();
8515 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8516 return true;
8517 }
8518
8519 case CK_IntegralComplexCast: {
8520 if (!Visit(E->getSubExpr()))
8521 return false;
8522
8523 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8524 QualType From
8525 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8526
Richard Smith911e1422012-01-30 22:27:01 +00008527 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8528 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008529 return true;
8530 }
8531
8532 case CK_IntegralComplexToFloatingComplex: {
8533 if (!Visit(E->getSubExpr()))
8534 return false;
8535
Ted Kremenek28831752012-08-23 20:46:57 +00008536 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008537 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008538 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008539 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008540 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8541 To, Result.FloatReal) &&
8542 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8543 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008544 }
8545 }
8546
8547 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008548}
8549
John McCall93d91dc2010-05-07 17:22:02 +00008550bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008551 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008552 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8553
Chandler Carrutha216cad2014-10-11 00:57:18 +00008554 // Track whether the LHS or RHS is real at the type system level. When this is
8555 // the case we can simplify our evaluation strategy.
8556 bool LHSReal = false, RHSReal = false;
8557
8558 bool LHSOK;
8559 if (E->getLHS()->getType()->isRealFloatingType()) {
8560 LHSReal = true;
8561 APFloat &Real = Result.FloatReal;
8562 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8563 if (LHSOK) {
8564 Result.makeComplexFloat();
8565 Result.FloatImag = APFloat(Real.getSemantics());
8566 }
8567 } else {
8568 LHSOK = Visit(E->getLHS());
8569 }
George Burgess IVa145e252016-05-25 22:38:36 +00008570 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008571 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008572
John McCall93d91dc2010-05-07 17:22:02 +00008573 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008574 if (E->getRHS()->getType()->isRealFloatingType()) {
8575 RHSReal = true;
8576 APFloat &Real = RHS.FloatReal;
8577 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8578 return false;
8579 RHS.makeComplexFloat();
8580 RHS.FloatImag = APFloat(Real.getSemantics());
8581 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008582 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008583
Chandler Carrutha216cad2014-10-11 00:57:18 +00008584 assert(!(LHSReal && RHSReal) &&
8585 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008586 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008587 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008588 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008589 if (Result.isComplexFloat()) {
8590 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8591 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008592 if (LHSReal)
8593 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8594 else if (!RHSReal)
8595 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8596 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008597 } else {
8598 Result.getComplexIntReal() += RHS.getComplexIntReal();
8599 Result.getComplexIntImag() += RHS.getComplexIntImag();
8600 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008601 break;
John McCalle3027922010-08-25 11:45:40 +00008602 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008603 if (Result.isComplexFloat()) {
8604 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8605 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008606 if (LHSReal) {
8607 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8608 Result.getComplexFloatImag().changeSign();
8609 } else if (!RHSReal) {
8610 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8611 APFloat::rmNearestTiesToEven);
8612 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008613 } else {
8614 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8615 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8616 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008617 break;
John McCalle3027922010-08-25 11:45:40 +00008618 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008619 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008620 // This is an implementation of complex multiplication according to the
8621 // constraints laid out in C11 Annex G. The implemantion uses the
8622 // following naming scheme:
8623 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008624 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008625 APFloat &A = LHS.getComplexFloatReal();
8626 APFloat &B = LHS.getComplexFloatImag();
8627 APFloat &C = RHS.getComplexFloatReal();
8628 APFloat &D = RHS.getComplexFloatImag();
8629 APFloat &ResR = Result.getComplexFloatReal();
8630 APFloat &ResI = Result.getComplexFloatImag();
8631 if (LHSReal) {
8632 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8633 ResR = A * C;
8634 ResI = A * D;
8635 } else if (RHSReal) {
8636 ResR = C * A;
8637 ResI = C * B;
8638 } else {
8639 // In the fully general case, we need to handle NaNs and infinities
8640 // robustly.
8641 APFloat AC = A * C;
8642 APFloat BD = B * D;
8643 APFloat AD = A * D;
8644 APFloat BC = B * C;
8645 ResR = AC - BD;
8646 ResI = AD + BC;
8647 if (ResR.isNaN() && ResI.isNaN()) {
8648 bool Recalc = false;
8649 if (A.isInfinity() || B.isInfinity()) {
8650 A = APFloat::copySign(
8651 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8652 B = APFloat::copySign(
8653 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8654 if (C.isNaN())
8655 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8656 if (D.isNaN())
8657 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8658 Recalc = true;
8659 }
8660 if (C.isInfinity() || D.isInfinity()) {
8661 C = APFloat::copySign(
8662 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8663 D = APFloat::copySign(
8664 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8665 if (A.isNaN())
8666 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8667 if (B.isNaN())
8668 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8669 Recalc = true;
8670 }
8671 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8672 AD.isInfinity() || BC.isInfinity())) {
8673 if (A.isNaN())
8674 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8675 if (B.isNaN())
8676 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8677 if (C.isNaN())
8678 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8679 if (D.isNaN())
8680 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8681 Recalc = true;
8682 }
8683 if (Recalc) {
8684 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8685 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8686 }
8687 }
8688 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008689 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008690 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008691 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008692 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8693 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008694 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008695 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8696 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8697 }
8698 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008699 case BO_Div:
8700 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008701 // This is an implementation of complex division according to the
8702 // constraints laid out in C11 Annex G. The implemantion uses the
8703 // following naming scheme:
8704 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008705 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008706 APFloat &A = LHS.getComplexFloatReal();
8707 APFloat &B = LHS.getComplexFloatImag();
8708 APFloat &C = RHS.getComplexFloatReal();
8709 APFloat &D = RHS.getComplexFloatImag();
8710 APFloat &ResR = Result.getComplexFloatReal();
8711 APFloat &ResI = Result.getComplexFloatImag();
8712 if (RHSReal) {
8713 ResR = A / C;
8714 ResI = B / C;
8715 } else {
8716 if (LHSReal) {
8717 // No real optimizations we can do here, stub out with zero.
8718 B = APFloat::getZero(A.getSemantics());
8719 }
8720 int DenomLogB = 0;
8721 APFloat MaxCD = maxnum(abs(C), abs(D));
8722 if (MaxCD.isFinite()) {
8723 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00008724 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8725 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008726 }
8727 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00008728 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8729 APFloat::rmNearestTiesToEven);
8730 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8731 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008732 if (ResR.isNaN() && ResI.isNaN()) {
8733 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8734 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8735 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8736 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8737 D.isFinite()) {
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 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8743 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8744 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8745 C = APFloat::copySign(
8746 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8747 D = APFloat::copySign(
8748 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8749 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8750 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8751 }
8752 }
8753 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008754 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008755 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8756 return Error(E, diag::note_expr_divide_by_zero);
8757
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008758 ComplexValue LHS = Result;
8759 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8760 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8761 Result.getComplexIntReal() =
8762 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8763 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8764 Result.getComplexIntImag() =
8765 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8766 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8767 }
8768 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008769 }
8770
John McCall93d91dc2010-05-07 17:22:02 +00008771 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008772}
8773
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008774bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8775 // Get the operand value into 'Result'.
8776 if (!Visit(E->getSubExpr()))
8777 return false;
8778
8779 switch (E->getOpcode()) {
8780 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008781 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008782 case UO_Extension:
8783 return true;
8784 case UO_Plus:
8785 // The result is always just the subexpr.
8786 return true;
8787 case UO_Minus:
8788 if (Result.isComplexFloat()) {
8789 Result.getComplexFloatReal().changeSign();
8790 Result.getComplexFloatImag().changeSign();
8791 }
8792 else {
8793 Result.getComplexIntReal() = -Result.getComplexIntReal();
8794 Result.getComplexIntImag() = -Result.getComplexIntImag();
8795 }
8796 return true;
8797 case UO_Not:
8798 if (Result.isComplexFloat())
8799 Result.getComplexFloatImag().changeSign();
8800 else
8801 Result.getComplexIntImag() = -Result.getComplexIntImag();
8802 return true;
8803 }
8804}
8805
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008806bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8807 if (E->getNumInits() == 2) {
8808 if (E->getType()->isComplexType()) {
8809 Result.makeComplexFloat();
8810 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8811 return false;
8812 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8813 return false;
8814 } else {
8815 Result.makeComplexInt();
8816 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8817 return false;
8818 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8819 return false;
8820 }
8821 return true;
8822 }
8823 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8824}
8825
Anders Carlsson537969c2008-11-16 20:27:53 +00008826//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008827// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8828// implicit conversion.
8829//===----------------------------------------------------------------------===//
8830
8831namespace {
8832class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008833 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008834 APValue &Result;
8835public:
8836 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8837 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8838
8839 bool Success(const APValue &V, const Expr *E) {
8840 Result = V;
8841 return true;
8842 }
8843
8844 bool ZeroInitialization(const Expr *E) {
8845 ImplicitValueInitExpr VIE(
8846 E->getType()->castAs<AtomicType>()->getValueType());
8847 return Evaluate(Result, Info, &VIE);
8848 }
8849
8850 bool VisitCastExpr(const CastExpr *E) {
8851 switch (E->getCastKind()) {
8852 default:
8853 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8854 case CK_NonAtomicToAtomic:
8855 return Evaluate(Result, Info, E->getSubExpr());
8856 }
8857 }
8858};
8859} // end anonymous namespace
8860
8861static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8862 assert(E->isRValue() && E->getType()->isAtomicType());
8863 return AtomicExprEvaluator(Info, Result).Visit(E);
8864}
8865
8866//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008867// Void expression evaluation, primarily for a cast to void on the LHS of a
8868// comma operator
8869//===----------------------------------------------------------------------===//
8870
8871namespace {
8872class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008873 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008874public:
8875 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8876
Richard Smith2e312c82012-03-03 22:46:17 +00008877 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008878
8879 bool VisitCastExpr(const CastExpr *E) {
8880 switch (E->getCastKind()) {
8881 default:
8882 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8883 case CK_ToVoid:
8884 VisitIgnoredValue(E->getSubExpr());
8885 return true;
8886 }
8887 }
Hal Finkela8443c32014-07-17 14:49:58 +00008888
8889 bool VisitCallExpr(const CallExpr *E) {
8890 switch (E->getBuiltinCallee()) {
8891 default:
8892 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8893 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008894 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008895 // The argument is not evaluated!
8896 return true;
8897 }
8898 }
Richard Smith42d3af92011-12-07 00:43:50 +00008899};
8900} // end anonymous namespace
8901
8902static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8903 assert(E->isRValue() && E->getType()->isVoidType());
8904 return VoidExprEvaluator(Info).Visit(E);
8905}
8906
8907//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008908// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008909//===----------------------------------------------------------------------===//
8910
Richard Smith2e312c82012-03-03 22:46:17 +00008911static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008912 // In C, function designators are not lvalues, but we evaluate them as if they
8913 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008914 QualType T = E->getType();
8915 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008916 LValue LV;
8917 if (!EvaluateLValue(E, LV, Info))
8918 return false;
8919 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008920 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008921 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008922 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008923 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008924 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008925 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008926 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008927 LValue LV;
8928 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008929 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008930 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008931 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008932 llvm::APFloat F(0.0);
8933 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008934 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008935 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008936 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008937 ComplexValue C;
8938 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008939 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008940 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008941 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008942 MemberPtr P;
8943 if (!EvaluateMemberPointer(E, P, Info))
8944 return false;
8945 P.moveInto(Result);
8946 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008947 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008948 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008949 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008950 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8951 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008952 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008953 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008954 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008955 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008956 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008957 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8958 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008959 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008960 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008961 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008962 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008963 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008964 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008965 if (!EvaluateVoid(E, Info))
8966 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008967 } else if (T->isAtomicType()) {
8968 if (!EvaluateAtomic(E, Result, Info))
8969 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008970 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008971 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008972 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008973 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008974 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008975 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008976 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008977
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008978 return true;
8979}
8980
Richard Smithb228a862012-02-15 02:18:13 +00008981/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8982/// cases, the in-place evaluation is essential, since later initializers for
8983/// an object can indirectly refer to subobjects which were initialized earlier.
8984static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008985 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008986 assert(!E->isValueDependent());
8987
Richard Smith7525ff62013-05-09 07:14:00 +00008988 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008989 return false;
8990
8991 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008992 // Evaluate arrays and record types in-place, so that later initializers can
8993 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008994 if (E->getType()->isArrayType())
8995 return EvaluateArray(E, This, Result, Info);
8996 else if (E->getType()->isRecordType())
8997 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008998 }
8999
9000 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009001 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009002}
9003
Richard Smithf57d8cb2011-12-09 22:58:01 +00009004/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9005/// lvalue-to-rvalue cast if it is an lvalue.
9006static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009007 if (E->getType().isNull())
9008 return false;
9009
Richard Smithfddd3842011-12-30 21:15:51 +00009010 if (!CheckLiteralType(Info, E))
9011 return false;
9012
Richard Smith2e312c82012-03-03 22:46:17 +00009013 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009014 return false;
9015
9016 if (E->isGLValue()) {
9017 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009018 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009019 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009020 return false;
9021 }
9022
Richard Smith2e312c82012-03-03 22:46:17 +00009023 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009024 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009025}
Richard Smith11562c52011-10-28 17:51:58 +00009026
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009027static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9028 const ASTContext &Ctx, bool &IsConst) {
9029 // Fast-path evaluations of integer literals, since we sometimes see files
9030 // containing vast quantities of these.
9031 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9032 Result.Val = APValue(APSInt(L->getValue(),
9033 L->getType()->isUnsignedIntegerType()));
9034 IsConst = true;
9035 return true;
9036 }
James Dennett0492ef02014-03-14 17:44:10 +00009037
9038 // This case should be rare, but we need to check it before we check on
9039 // the type below.
9040 if (Exp->getType().isNull()) {
9041 IsConst = false;
9042 return true;
9043 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009044
9045 // FIXME: Evaluating values of large array and record types can cause
9046 // performance problems. Only do so in C++11 for now.
9047 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9048 Exp->getType()->isRecordType()) &&
9049 !Ctx.getLangOpts().CPlusPlus11) {
9050 IsConst = false;
9051 return true;
9052 }
9053 return false;
9054}
9055
9056
Richard Smith7b553f12011-10-29 00:50:52 +00009057/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009058/// any crazy technique (that has nothing to do with language standards) that
9059/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009060/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9061/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009062bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009063 bool IsConst;
9064 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9065 return IsConst;
9066
Richard Smith6d4c6582013-11-05 22:18:15 +00009067 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009068 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009069}
9070
Jay Foad39c79802011-01-12 09:06:06 +00009071bool Expr::EvaluateAsBooleanCondition(bool &Result,
9072 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009073 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009074 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009075 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009076}
9077
Richard Smithce8eca52015-12-08 03:21:47 +00009078static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9079 Expr::SideEffectsKind SEK) {
9080 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9081 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9082}
9083
Richard Smith5fab0c92011-12-28 19:48:30 +00009084bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9085 SideEffectsKind AllowSideEffects) const {
9086 if (!getType()->isIntegralOrEnumerationType())
9087 return false;
9088
Richard Smith11562c52011-10-28 17:51:58 +00009089 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009090 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009091 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009092 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009093
Richard Smith11562c52011-10-28 17:51:58 +00009094 Result = ExprResult.Val.getInt();
9095 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009096}
9097
Richard Trieube234c32016-04-21 21:04:55 +00009098bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9099 SideEffectsKind AllowSideEffects) const {
9100 if (!getType()->isRealFloatingType())
9101 return false;
9102
9103 EvalResult ExprResult;
9104 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9105 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9106 return false;
9107
9108 Result = ExprResult.Val.getFloat();
9109 return true;
9110}
9111
Jay Foad39c79802011-01-12 09:06:06 +00009112bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009113 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009114
John McCall45d55e42010-05-07 21:00:08 +00009115 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009116 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9117 !CheckLValueConstantExpression(Info, getExprLoc(),
9118 Ctx.getLValueReferenceType(getType()), LV))
9119 return false;
9120
Richard Smith2e312c82012-03-03 22:46:17 +00009121 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009122 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009123}
9124
Richard Smithd0b4dd62011-12-19 06:19:21 +00009125bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9126 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009127 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009128 // FIXME: Evaluating initializers for large array and record types can cause
9129 // performance problems. Only do so in C++11 for now.
9130 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009131 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009132 return false;
9133
Richard Smithd0b4dd62011-12-19 06:19:21 +00009134 Expr::EvalStatus EStatus;
9135 EStatus.Diag = &Notes;
9136
Richard Smith0c6124b2015-12-03 01:36:22 +00009137 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9138 ? EvalInfo::EM_ConstantExpression
9139 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009140 InitInfo.setEvaluatingDecl(VD, Value);
9141
9142 LValue LVal;
9143 LVal.set(VD);
9144
Richard Smithfddd3842011-12-30 21:15:51 +00009145 // C++11 [basic.start.init]p2:
9146 // Variables with static storage duration or thread storage duration shall be
9147 // zero-initialized before any other initialization takes place.
9148 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009149 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009150 !VD->getType()->isReferenceType()) {
9151 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009152 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009153 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009154 return false;
9155 }
9156
Richard Smith7525ff62013-05-09 07:14:00 +00009157 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9158 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009159 EStatus.HasSideEffects)
9160 return false;
9161
9162 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9163 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009164}
9165
Richard Smith7b553f12011-10-29 00:50:52 +00009166/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9167/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009168bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009169 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009170 return EvaluateAsRValue(Result, Ctx) &&
9171 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009172}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009173
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009174APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009175 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009176 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009177 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009178 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009179 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009180 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009181 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009182
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009183 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009184}
John McCall864e3962010-05-07 05:32:02 +00009185
Richard Smithe9ff7702013-11-05 22:23:30 +00009186void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009187 bool IsConst;
9188 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009189 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009190 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009191 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9192 }
9193}
9194
Richard Smithe6c01442013-06-05 00:46:14 +00009195bool Expr::EvalResult::isGlobalLValue() const {
9196 assert(Val.isLValue());
9197 return IsGlobalLValue(Val.getLValueBase());
9198}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009199
9200
John McCall864e3962010-05-07 05:32:02 +00009201/// isIntegerConstantExpr - this recursive routine will test if an expression is
9202/// an integer constant expression.
9203
9204/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9205/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009206
9207// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009208// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9209// and a (possibly null) SourceLocation indicating the location of the problem.
9210//
John McCall864e3962010-05-07 05:32:02 +00009211// Note that to reduce code duplication, this helper does no evaluation
9212// itself; the caller checks whether the expression is evaluatable, and
9213// in the rare cases where CheckICE actually cares about the evaluated
9214// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009215
Dan Gohman28ade552010-07-26 21:25:24 +00009216namespace {
9217
Richard Smith9e575da2012-12-28 13:25:52 +00009218enum ICEKind {
9219 /// This expression is an ICE.
9220 IK_ICE,
9221 /// This expression is not an ICE, but if it isn't evaluated, it's
9222 /// a legal subexpression for an ICE. This return value is used to handle
9223 /// the comma operator in C99 mode, and non-constant subexpressions.
9224 IK_ICEIfUnevaluated,
9225 /// This expression is not an ICE, and is not a legal subexpression for one.
9226 IK_NotICE
9227};
9228
John McCall864e3962010-05-07 05:32:02 +00009229struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009230 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009231 SourceLocation Loc;
9232
Richard Smith9e575da2012-12-28 13:25:52 +00009233 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009234};
9235
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009236}
Dan Gohman28ade552010-07-26 21:25:24 +00009237
Richard Smith9e575da2012-12-28 13:25:52 +00009238static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9239
9240static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009241
Craig Toppera31a8822013-08-22 07:09:37 +00009242static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009243 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009244 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009245 !EVResult.Val.isInt())
9246 return ICEDiag(IK_NotICE, E->getLocStart());
9247
John McCall864e3962010-05-07 05:32:02 +00009248 return NoDiag();
9249}
9250
Craig Toppera31a8822013-08-22 07:09:37 +00009251static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009252 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009253 if (!E->getType()->isIntegralOrEnumerationType())
9254 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009255
9256 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009257#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009258#define STMT(Node, Base) case Expr::Node##Class:
9259#define EXPR(Node, Base)
9260#include "clang/AST/StmtNodes.inc"
9261 case Expr::PredefinedExprClass:
9262 case Expr::FloatingLiteralClass:
9263 case Expr::ImaginaryLiteralClass:
9264 case Expr::StringLiteralClass:
9265 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009266 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009267 case Expr::MemberExprClass:
9268 case Expr::CompoundAssignOperatorClass:
9269 case Expr::CompoundLiteralExprClass:
9270 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009271 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009272 case Expr::NoInitExprClass:
9273 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009274 case Expr::ImplicitValueInitExprClass:
9275 case Expr::ParenListExprClass:
9276 case Expr::VAArgExprClass:
9277 case Expr::AddrLabelExprClass:
9278 case Expr::StmtExprClass:
9279 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009280 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009281 case Expr::CXXDynamicCastExprClass:
9282 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009283 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009284 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009285 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009286 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009287 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009288 case Expr::CXXThisExprClass:
9289 case Expr::CXXThrowExprClass:
9290 case Expr::CXXNewExprClass:
9291 case Expr::CXXDeleteExprClass:
9292 case Expr::CXXPseudoDestructorExprClass:
9293 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009294 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009295 case Expr::DependentScopeDeclRefExprClass:
9296 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009297 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009298 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009299 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009300 case Expr::CXXTemporaryObjectExprClass:
9301 case Expr::CXXUnresolvedConstructExprClass:
9302 case Expr::CXXDependentScopeMemberExprClass:
9303 case Expr::UnresolvedMemberExprClass:
9304 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009305 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009306 case Expr::ObjCArrayLiteralClass:
9307 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009308 case Expr::ObjCEncodeExprClass:
9309 case Expr::ObjCMessageExprClass:
9310 case Expr::ObjCSelectorExprClass:
9311 case Expr::ObjCProtocolExprClass:
9312 case Expr::ObjCIvarRefExprClass:
9313 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009314 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009315 case Expr::ObjCIsaExprClass:
9316 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009317 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009318 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009319 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009320 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009321 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009322 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009323 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009324 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009325 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009326 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009327 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009328 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009329 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009330 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009331 case Expr::CoawaitExprClass:
9332 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009333 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009334
Richard Smithf137f932014-01-25 20:50:08 +00009335 case Expr::InitListExprClass: {
9336 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9337 // form "T x = { a };" is equivalent to "T x = a;".
9338 // Unless we're initializing a reference, T is a scalar as it is known to be
9339 // of integral or enumeration type.
9340 if (E->isRValue())
9341 if (cast<InitListExpr>(E)->getNumInits() == 1)
9342 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9343 return ICEDiag(IK_NotICE, E->getLocStart());
9344 }
9345
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009346 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009347 case Expr::GNUNullExprClass:
9348 // GCC considers the GNU __null value to be an integral constant expression.
9349 return NoDiag();
9350
John McCall7c454bb2011-07-15 05:09:51 +00009351 case Expr::SubstNonTypeTemplateParmExprClass:
9352 return
9353 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9354
John McCall864e3962010-05-07 05:32:02 +00009355 case Expr::ParenExprClass:
9356 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009357 case Expr::GenericSelectionExprClass:
9358 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009359 case Expr::IntegerLiteralClass:
9360 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009361 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009362 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009363 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009364 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009365 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009366 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009367 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009368 return NoDiag();
9369 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009370 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009371 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9372 // constant expressions, but they can never be ICEs because an ICE cannot
9373 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009374 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009375 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009376 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009377 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009378 }
Richard Smith6365c912012-02-24 22:12:32 +00009379 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009380 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9381 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009382 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009383 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009384 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009385 // Parameter variables are never constants. Without this check,
9386 // getAnyInitializer() can find a default argument, which leads
9387 // to chaos.
9388 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009389 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009390
9391 // C++ 7.1.5.1p2
9392 // A variable of non-volatile const-qualified integral or enumeration
9393 // type initialized by an ICE can be used in ICEs.
9394 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009395 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009396 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009397
Richard Smithd0b4dd62011-12-19 06:19:21 +00009398 const VarDecl *VD;
9399 // Look for a declaration of this variable that has an initializer, and
9400 // check whether it is an ICE.
9401 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9402 return NoDiag();
9403 else
Richard Smith9e575da2012-12-28 13:25:52 +00009404 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009405 }
9406 }
Richard Smith9e575da2012-12-28 13:25:52 +00009407 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009408 }
John McCall864e3962010-05-07 05:32:02 +00009409 case Expr::UnaryOperatorClass: {
9410 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9411 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009412 case UO_PostInc:
9413 case UO_PostDec:
9414 case UO_PreInc:
9415 case UO_PreDec:
9416 case UO_AddrOf:
9417 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009418 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009419 // C99 6.6/3 allows increment and decrement within unevaluated
9420 // subexpressions of constant expressions, but they can never be ICEs
9421 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009422 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009423 case UO_Extension:
9424 case UO_LNot:
9425 case UO_Plus:
9426 case UO_Minus:
9427 case UO_Not:
9428 case UO_Real:
9429 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009430 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009431 }
Richard Smith9e575da2012-12-28 13:25:52 +00009432
John McCall864e3962010-05-07 05:32:02 +00009433 // OffsetOf falls through here.
9434 }
9435 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009436 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9437 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9438 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9439 // compliance: we should warn earlier for offsetof expressions with
9440 // array subscripts that aren't ICEs, and if the array subscripts
9441 // are ICEs, the value of the offsetof must be an integer constant.
9442 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009443 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009444 case Expr::UnaryExprOrTypeTraitExprClass: {
9445 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9446 if ((Exp->getKind() == UETT_SizeOf) &&
9447 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009448 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009449 return NoDiag();
9450 }
9451 case Expr::BinaryOperatorClass: {
9452 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9453 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009454 case BO_PtrMemD:
9455 case BO_PtrMemI:
9456 case BO_Assign:
9457 case BO_MulAssign:
9458 case BO_DivAssign:
9459 case BO_RemAssign:
9460 case BO_AddAssign:
9461 case BO_SubAssign:
9462 case BO_ShlAssign:
9463 case BO_ShrAssign:
9464 case BO_AndAssign:
9465 case BO_XorAssign:
9466 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009467 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9468 // constant expressions, but they can never be ICEs because an ICE cannot
9469 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009470 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009471
John McCalle3027922010-08-25 11:45:40 +00009472 case BO_Mul:
9473 case BO_Div:
9474 case BO_Rem:
9475 case BO_Add:
9476 case BO_Sub:
9477 case BO_Shl:
9478 case BO_Shr:
9479 case BO_LT:
9480 case BO_GT:
9481 case BO_LE:
9482 case BO_GE:
9483 case BO_EQ:
9484 case BO_NE:
9485 case BO_And:
9486 case BO_Xor:
9487 case BO_Or:
9488 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009489 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9490 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009491 if (Exp->getOpcode() == BO_Div ||
9492 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009493 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009494 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009495 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009496 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009497 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009498 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009499 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009500 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009501 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009502 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009503 }
9504 }
9505 }
John McCalle3027922010-08-25 11:45:40 +00009506 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009507 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009508 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9509 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009510 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9511 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009512 } else {
9513 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009514 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009515 }
9516 }
Richard Smith9e575da2012-12-28 13:25:52 +00009517 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009518 }
John McCalle3027922010-08-25 11:45:40 +00009519 case BO_LAnd:
9520 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009521 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9522 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009523 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009524 // Rare case where the RHS has a comma "side-effect"; we need
9525 // to actually check the condition to see whether the side
9526 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009527 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009528 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009529 return RHSResult;
9530 return NoDiag();
9531 }
9532
Richard Smith9e575da2012-12-28 13:25:52 +00009533 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009534 }
9535 }
9536 }
9537 case Expr::ImplicitCastExprClass:
9538 case Expr::CStyleCastExprClass:
9539 case Expr::CXXFunctionalCastExprClass:
9540 case Expr::CXXStaticCastExprClass:
9541 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009542 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009543 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009544 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009545 if (isa<ExplicitCastExpr>(E)) {
9546 if (const FloatingLiteral *FL
9547 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9548 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9549 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9550 APSInt IgnoredVal(DestWidth, !DestSigned);
9551 bool Ignored;
9552 // If the value does not fit in the destination type, the behavior is
9553 // undefined, so we are not required to treat it as a constant
9554 // expression.
9555 if (FL->getValue().convertToInteger(IgnoredVal,
9556 llvm::APFloat::rmTowardZero,
9557 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009558 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009559 return NoDiag();
9560 }
9561 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009562 switch (cast<CastExpr>(E)->getCastKind()) {
9563 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009564 case CK_AtomicToNonAtomic:
9565 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009566 case CK_NoOp:
9567 case CK_IntegralToBoolean:
9568 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009569 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009570 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009571 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009572 }
John McCall864e3962010-05-07 05:32:02 +00009573 }
John McCallc07a0c72011-02-17 10:25:35 +00009574 case Expr::BinaryConditionalOperatorClass: {
9575 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9576 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009577 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009578 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009579 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9580 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9581 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009582 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009583 return FalseResult;
9584 }
John McCall864e3962010-05-07 05:32:02 +00009585 case Expr::ConditionalOperatorClass: {
9586 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9587 // If the condition (ignoring parens) is a __builtin_constant_p call,
9588 // then only the true side is actually considered in an integer constant
9589 // expression, and it is fully evaluated. This is an important GNU
9590 // extension. See GCC PR38377 for discussion.
9591 if (const CallExpr *CallCE
9592 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009593 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009594 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009595 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009596 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009597 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009598
Richard Smithf57d8cb2011-12-09 22:58:01 +00009599 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9600 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009601
Richard Smith9e575da2012-12-28 13:25:52 +00009602 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009603 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009604 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009605 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009606 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009607 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009608 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009609 return NoDiag();
9610 // Rare case where the diagnostics depend on which side is evaluated
9611 // Note that if we get here, CondResult is 0, and at least one of
9612 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009613 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009614 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009615 return TrueResult;
9616 }
9617 case Expr::CXXDefaultArgExprClass:
9618 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009619 case Expr::CXXDefaultInitExprClass:
9620 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009621 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009622 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009623 }
9624 }
9625
David Blaikiee4d798f2012-01-20 21:50:17 +00009626 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009627}
9628
Richard Smithf57d8cb2011-12-09 22:58:01 +00009629/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009630static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009631 const Expr *E,
9632 llvm::APSInt *Value,
9633 SourceLocation *Loc) {
9634 if (!E->getType()->isIntegralOrEnumerationType()) {
9635 if (Loc) *Loc = E->getExprLoc();
9636 return false;
9637 }
9638
Richard Smith66e05fe2012-01-18 05:21:49 +00009639 APValue Result;
9640 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009641 return false;
9642
Richard Smith98710fc2014-11-13 23:03:19 +00009643 if (!Result.isInt()) {
9644 if (Loc) *Loc = E->getExprLoc();
9645 return false;
9646 }
9647
Richard Smith66e05fe2012-01-18 05:21:49 +00009648 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009649 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009650}
9651
Craig Toppera31a8822013-08-22 07:09:37 +00009652bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9653 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009654 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009655 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009656
Richard Smith9e575da2012-12-28 13:25:52 +00009657 ICEDiag D = CheckICE(this, Ctx);
9658 if (D.Kind != IK_ICE) {
9659 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009660 return false;
9661 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009662 return true;
9663}
9664
Craig Toppera31a8822013-08-22 07:09:37 +00009665bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009666 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009667 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009668 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9669
9670 if (!isIntegerConstantExpr(Ctx, Loc))
9671 return false;
Richard Smith5c40f092015-12-04 03:00:44 +00009672 // The only possible side-effects here are due to UB discovered in the
9673 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9674 // required to treat the expression as an ICE, so we produce the folded
9675 // value.
9676 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +00009677 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009678 return true;
9679}
Richard Smith66e05fe2012-01-18 05:21:49 +00009680
Craig Toppera31a8822013-08-22 07:09:37 +00009681bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009682 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009683}
9684
Craig Toppera31a8822013-08-22 07:09:37 +00009685bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009686 SourceLocation *Loc) const {
9687 // We support this checking in C++98 mode in order to diagnose compatibility
9688 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009689 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009690
Richard Smith98a0a492012-02-14 21:38:30 +00009691 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009692 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009693 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009694 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009695 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009696
9697 APValue Scratch;
9698 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9699
9700 if (!Diags.empty()) {
9701 IsConstExpr = false;
9702 if (Loc) *Loc = Diags[0].first;
9703 } else if (!IsConstExpr) {
9704 // FIXME: This shouldn't happen.
9705 if (Loc) *Loc = getExprLoc();
9706 }
9707
9708 return IsConstExpr;
9709}
Richard Smith253c2a32012-01-27 01:14:48 +00009710
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009711bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9712 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009713 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009714 Expr::EvalStatus Status;
9715 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9716
9717 ArgVector ArgValues(Args.size());
9718 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9719 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009720 if ((*I)->isValueDependent() ||
9721 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009722 // If evaluation fails, throw away the argument entirely.
9723 ArgValues[I - Args.begin()] = APValue();
9724 if (Info.EvalStatus.HasSideEffects)
9725 return false;
9726 }
9727
9728 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009729 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009730 ArgValues.data());
9731 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9732}
9733
Richard Smith253c2a32012-01-27 01:14:48 +00009734bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009735 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009736 PartialDiagnosticAt> &Diags) {
9737 // FIXME: It would be useful to check constexpr function templates, but at the
9738 // moment the constant expression evaluator cannot cope with the non-rigorous
9739 // ASTs which we build for dependent expressions.
9740 if (FD->isDependentContext())
9741 return true;
9742
9743 Expr::EvalStatus Status;
9744 Status.Diag = &Diags;
9745
Richard Smith6d4c6582013-11-05 22:18:15 +00009746 EvalInfo Info(FD->getASTContext(), Status,
9747 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009748
9749 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009750 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009751
Richard Smith7525ff62013-05-09 07:14:00 +00009752 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009753 // is a temporary being used as the 'this' pointer.
9754 LValue This;
9755 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009756 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009757
Richard Smith253c2a32012-01-27 01:14:48 +00009758 ArrayRef<const Expr*> Args;
9759
9760 SourceLocation Loc = FD->getLocation();
9761
Richard Smith2e312c82012-03-03 22:46:17 +00009762 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009763 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9764 // Evaluate the call as a constant initializer, to allow the construction
9765 // of objects of non-literal types.
9766 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009767 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009768 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009769 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009770 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009771
9772 return Diags.empty();
9773}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009774
9775bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9776 const FunctionDecl *FD,
9777 SmallVectorImpl<
9778 PartialDiagnosticAt> &Diags) {
9779 Expr::EvalStatus Status;
9780 Status.Diag = &Diags;
9781
9782 EvalInfo Info(FD->getASTContext(), Status,
9783 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9784
9785 // Fabricate a call stack frame to give the arguments a plausible cover story.
9786 ArrayRef<const Expr*> Args;
9787 ArgVector ArgValues(0);
9788 bool Success = EvaluateArgs(Args, ArgValues, Info);
9789 (void)Success;
9790 assert(Success &&
9791 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009792 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009793
9794 APValue ResultScratch;
9795 Evaluate(ResultScratch, Info, E);
9796 return Diags.empty();
9797}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009798
9799bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9800 unsigned Type) const {
9801 if (!getType()->isPointerType())
9802 return false;
9803
9804 Expr::EvalStatus Status;
9805 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9806 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
9807}